aboutsummaryrefslogtreecommitdiffstats
path: root/Frameworks
diff options
context:
space:
mode:
Diffstat (limited to 'Frameworks')
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.h106
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.m466
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.h47
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.m186
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+Private.h45
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.h93
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.m373
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.h36
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.m34
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.h74
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.m183
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.h35
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.m57
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.h84
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.m230
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.h127
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.m1342
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation+Private.h46
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.h112
-rw-r--r--Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.m486
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPConnection.h282
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPConnection.m3402
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPConnectionDelegate.h81
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPConnectionProxy.h70
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPConstants.h82
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.h46
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.m113
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.h65
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.m785
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPKit.h44
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPNull.h35
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPNull.m43
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPNumber.h83
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPNumber.m301
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPResult.h86
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPResult.m1354
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.h42
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.m188
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.h74
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.m566
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.h46
-rw-r--r--Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.m50
-rw-r--r--Frameworks/MCPKit/MySQL/include/my_alloc.h51
-rw-r--r--Frameworks/MCPKit/MySQL/include/my_list.h45
-rw-r--r--Frameworks/MCPKit/MySQL/include/mysql.h870
-rw-r--r--Frameworks/MCPKit/MySQL/include/mysql_com.h532
-rw-r--r--Frameworks/MCPKit/MySQL/include/mysql_embed.h29
-rw-r--r--Frameworks/MCPKit/MySQL/include/mysql_time.h55
-rw-r--r--Frameworks/MCPKit/MySQL/include/mysql_version.h30
-rw-r--r--Frameworks/MCPKit/MySQL/include/typelib.h39
-rw-r--r--Frameworks/MCPKit/MySQL/lib/libmysqlclient.abin4560292 -> 0 bytes
-rw-r--r--Frameworks/MCPKit/MySQL/lib/libmysqlclient_r.abin4594252 -> 0 bytes
-rw-r--r--Frameworks/MCPKit/Support files/NSNotificationAdditions.h35
-rw-r--r--Frameworks/MCPKit/Support files/NSNotificationAdditions.m97
-rw-r--r--Frameworks/SPMySQLFramework/SPMySQLFramework.xcodeproj/project.pbxproj76
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQL.h3
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.h6
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.m21
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLConnection.h2
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLConnectionDelegate.h2
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLConnectionProxy.h2
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLConstants.h2
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.h38
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.m71
-rw-r--r--Frameworks/SPMySQLFramework/Source/SPMySQLResult.h3
65 files changed, 218 insertions, 13791 deletions
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.h
deleted file mode 100644
index 469d0808..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.h
+++ /dev/null
@@ -1,106 +0,0 @@
-//
-// $Id$
-//
-// MCPAttribute.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-@class MCPModel;
-@class MCPClassDescription;
-@class MCPRelation;
-@class MCPJoin;
-
-@interface MCPAttribute : NSObject < NSCoding >
-{
-@protected
- MCPClassDescription *classDescription; // ClassDescription of which the attribute is attribute
- NSString *name; // Name of the attribute (Obj-C side)
- Class valueClass; // Class used by the attribute (or NULL if the internal type is not an object)
- NSString *internalType; // Name of the class, or type used for the class definition
- NSString *externalName; // Name of the corresponding column in the DB
- NSString *externalType; // Type used to store the attribute (in the DB)
- NSUInteger width; // Width (for storing by the DB)
- BOOL allowsNull; // Attribute can be null
- BOOL autoGenerated; // Attribute is auto generated by the DB
- BOOL isPartOfKey; // Attribute is part of theprimary key of the class description
- BOOL isPartOfIdentity; // Attribute is part of the idclass description of the class description
- BOOL hasAccessor; // Does this attribute have an accessor
- id defaultValue; // Default value of the attribute
- NSMutableArray *joins; // An array of the joins using this attribute
-}
-
-#pragma mark Class methods
-+ (void) initialize;
-
-#pragma mark Life cycle
-- (id) initForClassDescription:(MCPClassDescription *) iClassDescription withName:(NSString *) iName;
-- (void) dealloc;
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder;
-- (void) encodeWithCoder:(NSCoder *) encoder;
-
-#pragma mark Setters
-- (void) setName:(NSString *) iName;
-- (void) setValueClass:(Class) iValueClass;
-- (void) setInternalType:(NSString *) iInternalType;
-- (void) setExternalType:(NSString *) iExternalType;
-- (void) setExternalName:(NSString *) iExternalName;
-- (void) setWidth:(NSUInteger) iWidth;
-- (void) setAllowsNull:(BOOL) iAllowsNull;
-- (void) setAutoGenerated:(BOOL) iAutoGenerated;
-- (void) setIsPartOfKey:(BOOL) iIsPartOfKey;
-- (void) setIsPartOfIdentity:(BOOL) iIsPartOfIdentity;
-- (void) setHasAccessor:(BOOL) iHasAccessor;
-- (void) setDefaultValue:(id) iDefaultValue;
-- (void) insertObject:(MCPJoin *) iJoin inJoinsAtIndex:(NSUInteger) index;
-- (void) removeObjectFromJoinsAtIndex:(NSUInteger) index;
-//- (void) addRelation:(MCPRelation *) iRelation;
-//- (void) removeRelation:(MCPRelation *) iRelation;
-
-#pragma mark Getters
-- (MCPClassDescription *) classDescription;
-- (NSString *) name;
-- (Class) valueClass;
-- (NSString *) valueClassName;
-- (NSString *) internalType;
-- (NSString *) externalName;
-- (NSString *) externalType;
-- (NSUInteger) width;
-- (BOOL) allowsNull;
-- (BOOL) autoGenerated;
-- (BOOL) isPartOfKey;
-- (BOOL) isPartOfIdentity;
-- (BOOL) hasAccessor;
-- (id) defaultValue;
-- (NSUInteger) countOfJoins;
-- (MCPJoin *) objectInJoinsAtIndex:(NSUInteger) index;
-- (NSUInteger) indexOfJoinIdenticalTo:(id) iJoin;
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.m
deleted file mode 100644
index 085c1114..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPAttribute.m
+++ /dev/null
@@ -1,466 +0,0 @@
-//
-// $Id$
-//
-// MCPAttribute.m
-// MCPkit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPAttribute.h"
-
-#import "MCPEntrepriseNotifications.h"
-
-#import "MCPModel.h"
-#import "MCPClassDescription.h"
-#import "MCPRelation.h"
-#import "MCPJoin.h"
-
-static NSArray *MCPRecognisedInternalType;
-
-@interface MCPAttribute (Private)
-
-- (void)setValueClassName:(NSString *) iClassName;
-
-@end
-
-@implementation MCPAttribute
-
-#pragma mark Class methods
-+ (void) initialize
-{
- if (self == [MCPAttribute class]) {
- [self setVersion:010101]; // Ma.Mi.Re -> MaMiRe
- MCPRecognisedInternalType = [[NSArray alloc] initWithObjects:@"NSCalendarDate", @"NSData", @"NSNumber", @"NSString", nil];
- [self setKeys:[NSArray arrayWithObject:@"internalType"] triggerChangeNotificationsForDependentKey:@"valueClassName"];
- [self setKeys:[NSArray arrayWithObject:@"valueClassName"] triggerChangeNotificationsForDependentKey:@"internalType"];
- }
- return;
-}
-
-
-#pragma mark Life cycle
-- (id) initForClassDescription:(MCPClassDescription *) iClassDescription withName:(NSString *) iName
-{
- self = [super init];
- {
- classDescription = iClassDescription;
- [self setName:iName];
-// relations = (NSMutableArray *)(CFArrayCreateMutable (kCFAllocatorDefault, 0, NULL));
- joins = [[NSMutableArray alloc] init];
- }
- return self;
-}
-
-- (void) dealloc
-{
-// NSArray *theRelations;
-// unsigned int i;
-
- [name release];
- [internalType release];
- [externalName release];
- [externalType release];
- [defaultValue release];
-/*
- while ([relations count]) {
- [(MCPRelation *)[relations objectAtIndex:0] unjoinAttribute:self];
- }
-// By now relation should be empty anyway...
- [relations release];
- */
- while ([joins count]) {
- [[self objectInJoinsAtIndex:0] invalidate];
- }
- // By now the joins array should be empty
- [joins release];
- [super dealloc];
-}
-
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder
-{
- self = [super init];
- if ((self) && ([decoder allowsKeyedCoding])) {
- NSString *theClassName = [decoder decodeObjectForKey:@"MCPvalueClassName"];
-
- classDescription = [decoder decodeObjectForKey:@"MCPclassDescription"];
- [self setName:[decoder decodeObjectForKey:@"MCPname"]];
- if (theClassName) {
- [self setValueClass:NSClassFromString(theClassName)];
- }
- [self setInternalType:[decoder decodeObjectForKey:@"MCPinternalType"]];
- [self setExternalName:[decoder decodeObjectForKey:@"MCPexternalName"]];
- [self setExternalType:[decoder decodeObjectForKey:@"MCPexternalType"]];
- [self setWidth:(NSUInteger)[decoder decodeInt32ForKey:@"MCPwidth"]];
- [self setAllowsNull:[decoder decodeBoolForKey:@"MCPallowsNull"]];
- [self setAutoGenerated:[decoder decodeBoolForKey:@"MCPautoGenerated"]];
- [self setIsPartOfKey:[decoder decodeBoolForKey:@"MCPisPartOfKey"]];
- [self setIsPartOfIdentity:[decoder decodeBoolForKey:@"MCPisPartOfIdentity"]];
- [self setHasAccessor:[decoder decodeBoolForKey:@"MCPhasAccessor"]];
- [self setDefaultValue:[decoder decodeObjectForKey:@"MCPdefaultValue"]];
-// Not sure that the next line is working (getting an array holding weak references), hence doing the thing expelcitly:
-// relations = [[decoder decodeObjectForKey:@"MCPrelations"] retain];
-// relations = (NSMutableArray *)(CFArrayCreateMutable (kCFAllocatorDefault, 0, NULL));
-// [relations addObjectsFromArray:[decoder decodeObjectForKey:@"MCPrelations"]];
- joins = [[NSMutableArray alloc] init]; // Will be filled in when the relations are read in.
- }
- else {
- NSLog(@"For some reason, unable to decode MCPAttribute from the coder!!!");
- }
-// NSLog(@"MAKING a new object : %@", self);
- return self;
-}
-
-- (void) encodeWithCoder:(NSCoder *) encoder
-{
- NSString *theValueClassName;
-
- if (! [encoder allowsKeyedCoding]) {
- NSLog(@"In MCPAttribute -encodeWithCoder : Unable to encode to a non-keyed encoder!!, will not perform encoding!!");
- return;
- }
-// theValueClassName = (valueClass) ? [valueClass className] : nil;
- theValueClassName = (valueClass) ? NSStringFromClass(valueClass) : nil;
- [encoder encodeObject:[self classDescription] forKey:@"MCPclassDescription"];
- [encoder encodeObject:[self name] forKey:@"MCPname"];
- if (theValueClassName) {
- [encoder encodeObject:theValueClassName forKey:@"MCPvalueClassName"];
- }
- [encoder encodeObject:[self internalType] forKey:@"MCPinternalType"];
- [encoder encodeObject:[self externalName] forKey:@"MCPexternalName"];
- [encoder encodeObject:[self externalType] forKey:@"MCPexternalType"];
- [encoder encodeInt32:(int32_t)[self width] forKey:@"MCPwidth"];
- [encoder encodeBool:[self allowsNull] forKey:@"MCPallowsNull"];
- [encoder encodeBool:[self autoGenerated] forKey:@"MCPautoGenerated"];
- [encoder encodeBool:[self isPartOfKey] forKey:@"MCPisPartOfKey"];
- [encoder encodeBool:[self isPartOfIdentity] forKey:@"MCPisPartOfIdentity"];
- [encoder encodeBool:[self hasAccessor] forKey:@"MCPhasAccessor"];
- [encoder encodeObject:[self defaultValue] forKey:@"MCPdefaultValue"];
-// [encoder encodeObject:relations forKey:@"MCPrelation"];
- // We don't have to save the joins here ... the joins are saving there attributes.
- // The links are recreated when the joins are decoded.
-}
-
-#pragma mark Setters
-- (void) setName:(NSString *) iName
-{
- if (iName != name) {
- [name release];
- name = [iName retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setValueClass:(Class) iValueClass
-{
- if (iValueClass != valueClass) {
- valueClass = iValueClass;
- if (valueClass) { // Not nil : set the internalType accrodingly.
- // [internalType release];
- // internalType = [[valueClass className] copy];
-// [self setValue:[NSString stringWithString:[valueClass className]] forKey:@"internalType"];
- [self setValue:[NSString stringWithString:NSStringFromClass(valueClass)] forKey:@"internalType"];
- }
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setInternalType:(NSString *) iInternalType
-{
- if (iInternalType != internalType) {
- [internalType release];
- internalType = [iInternalType retain];
- if ([MCPRecognisedInternalType containsObject:internalType]) {
- [self setValueClass:NSClassFromString(internalType)];
-// By itself does NOT provide observers the update.
-// but see setKeys:triggerChangeNotificationsForDependentKey... (in +initialize).
- }
- else {
- [self setValueClass:nil];
- }
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setExternalType:(NSString *) iExternalType
-{
- if (iExternalType != externalType) {
- [externalType release];
- externalType = [iExternalType retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setExternalName:(NSString *) iExternalName
-{
- if (iExternalName != externalName) {
- [externalName release];
- externalName = [iExternalName retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setWidth:(NSUInteger) iWidth
-{
- if (iWidth != width) {
- width = iWidth;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setAllowsNull:(BOOL) iAllowsNull
-{
- if (iAllowsNull != allowsNull) {
- allowsNull = iAllowsNull;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setAutoGenerated:(BOOL) iAutoGenerated
-{
- if (iAutoGenerated != autoGenerated) {
- autoGenerated = iAutoGenerated;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setIsPartOfKey:(BOOL) iIsPartOfKey
-{
- if (iIsPartOfKey != isPartOfKey) {
- isPartOfKey = iIsPartOfKey;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setIsPartOfIdentity:(BOOL) iIsPartOfIdentity
-{
- if (iIsPartOfIdentity != isPartOfIdentity) {
- isPartOfIdentity = iIsPartOfIdentity;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setHasAccessor:(BOOL) iHasAccessor
-{
- if (iHasAccessor != hasAccessor) {
- hasAccessor = iHasAccessor;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) setDefaultValue:(id) iDefaultValue
-{
- if (iDefaultValue != defaultValue) {
- [defaultValue release];
- defaultValue = [iDefaultValue retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[classDescription model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:classDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPAttributeChangedNotification object:self];
- }
-}
-
-- (void) insertObject:(MCPJoin *) iJoin inJoinsAtIndex:(NSUInteger) index
-{
- [joins insertObject:iJoin atIndex:index];
-}
-
-- (void) removeObjectFromJoinsAtIndex:(NSUInteger) index
-{
- [joins removeObjectAtIndex:index];
-}
-
-/*
-- (void) addRelation:(MCPRelation *) iRelation
-{
-// Following implementation make sure that a given relation is only added once... but I don't see the reason for that to be true.
- /* if (NSNotFound == [relations indexOfObjectIdenticalTo:iRelation]) {
- [relations addObject:iRelation];
- }
- *//*
- [relations addObject:iRelation];
-}
-
-- (void) removeRelation:(MCPRelation *) iRelation
-{
-// Following implementation needs only one reference to a given relation to be working properly (not true)
-// [relations removeObjectIdenticalTo:iRelation];
- unsigned int i;
-
- i = [relations indexOfObjectIdenticalTo:iRelation];
- if (NSNotFound != i) {
- [relations removeObjectAtIndex:i];
- }
-// If the relation is there more than once, remove it only once.
-}
-*/
-
-#pragma mark Getters
-- (MCPClassDescription *) classDescription
-{
- return classDescription;
-}
-
-- (NSString *) name
-{
- return name;
-}
-
-- (Class) valueClass
-{
- return valueClass;
-}
-
-- (NSString *) valueClassName
-{
- return NSStringFromClass(valueClass);
-}
-
-- (NSString *) internalType
-{
- return internalType;
-}
-
-- (NSString *) externalName
-{
- return externalName;
-}
-
-- (NSString *) externalType
-{
- return externalType;
-}
-
-- (NSUInteger) width
-{
- return width;
-}
-
-- (BOOL) allowsNull
-{
- return allowsNull;
-}
-
-- (BOOL) autoGenerated
-{
- return autoGenerated;
-}
-
-- (BOOL) isPartOfKey
-{
- return isPartOfKey;
-}
-
-- (BOOL) isPartOfIdentity
-{
- return isPartOfIdentity;
-}
-
-- (BOOL) hasAccessor
-{
- return hasAccessor;
-}
-
-- (id) defaultValue
-{
- return defaultValue;
-}
-
-- (NSUInteger) countOfJoins
-{
- return [joins count];
-}
-
-- (MCPJoin *) objectInJoinsAtIndex:(NSUInteger) index
-{
- return (MCPJoin *)((NSNotFound != index) ? [joins objectAtIndex:index] : nil);
-}
-
-- (NSUInteger) indexOfJoinIdenticalTo:(id) iJoin
-{
- return [joins indexOfObjectIdenticalTo:iJoin];
-}
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject
-// Equal to another attribute, if they have the same name and same class description.
-// Equal to a string (NSString), if the name of the attribute is equal to the string.
-{
- if ([iObject isKindOfClass:[MCPAttribute class]]) {
- MCPAttribute *theAttribute = (MCPAttribute *) iObject;
-
- return ([name isEqualToString:[theAttribute name]]) && ([classDescription isEqual:[theAttribute classDescription]]);
- }
- if ([iObject isKindOfClass:[NSString class]]) {
- return [name isEqualToString:(NSString *)iObject];
- }
- return NO;
-}
-
-#pragma mark For debugging the retain counting
-- (id) retain
-{
- [super retain];
- return self;
-}
-
-- (void) release
-{
- [super release];
- return;
-}
-
-@end
-
-@implementation MCPAttribute (Private)
-
-- (void)setValueClassName:(NSString *) iClassName
-{
- if (NSClassFromString(iClassName) != valueClass) {
- [self setValueClass:NSClassFromString(iClassName)];
- }
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.h
deleted file mode 100644
index 052eeadb..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.h
+++ /dev/null
@@ -1,47 +0,0 @@
-//
-// $Id$
-//
-// MCPClassDescription+MCPEntreprise.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 01/11/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-#import "MCPClassDescription.h"
-
-@interface MCPClassDescription (MCPEntreprise)
-
-#pragma mark Pseudo getters (for NSClassDescription overload)
-- (NSArray *) attributeKeys;
-- (NSString *) inverseRelationshipKey:(NSString *) relationshipKey;
-- (NSArray *) toManyRelationshipKeys;
-- (NSArray *) toOneRelationshipKeys;
-
-#pragma mark Specifics for MCPObject
-- (NSArray *) primaryKeyAttributes;
-- (NSArray *) identityAttributes;
-- (MCPAttribute *) attributeWithName: (NSString *) iName;
-- (MCPRelation *) relationWithName:(NSString *) iRelationName;
-- (BOOL) singleIntAutoGenKey;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.m
deleted file mode 100644
index 71a25911..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+MCPEntreprise.m
+++ /dev/null
@@ -1,186 +0,0 @@
-//
-// $Id$
-//
-// MCPClassDescription+MCPEntreprise.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 01/11/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPClassDescription+MCPEntreprise.h"
-
-#import "MCPAttribute.h"
-#import "MCPRelation.h"
-
-@implementation MCPClassDescription (MCPEntreprise)
-
-#pragma mark Pseudo getters (for NSClassDescription overload)
-- (NSArray *) attributeKeys
-{
- NSArray *theRet;
- NSMutableArray *theKeys =[[NSMutableArray alloc] init];
- NSUInteger i;
-
- for (i=0; i != [self countOfAttributes]; ++i) {
- [theKeys insertObject:[(MCPAttribute *)[self objectInAttributesAtIndex:i] name] atIndex:i];
- }
- theRet = [NSArray arrayWithArray:theKeys];
- [theKeys release];
- return theRet;
-}
-
-- (NSString *) inverseRelationshipKey:(NSString *) relationshipKey
-{
- NSUInteger index = [self indexOfRelation:relationshipKey];
-
- if (NSNotFound != index) {
- MCPRelation *theRelation;
-
- theRelation = (MCPRelation *)[self objectInRelationsAtIndex:index];
- return [[theRelation inverseRelation] name];
- }
- return nil;
-}
-
-- (NSArray *) toManyRelationshipKeys
-{
- NSArray *theRet;
- NSMutableArray *theToManyRel = [[NSMutableArray alloc] init];
- NSUInteger i, j;
-
- j=0;
- for (i=0; i != [self countOfRelations]; ++i) {
- MCPRelation *theRelation = (MCPRelation *)[self objectInRelationsAtIndex:i];
-
- if ([theRelation isToMany]) {
- [theToManyRel insertObject:[theRelation name] atIndex:j];
- ++j;
- }
- }
- theRet = [NSArray arrayWithArray:theToManyRel];
- [theToManyRel release];
- return theRet;
-}
-
-- (NSArray *) toOneRelationshipKeys;
-{
- NSArray *theRet;
- NSMutableArray *theToOneRel = [[NSMutableArray alloc] init];
- NSUInteger i, j;
-
- j=0;
- for (i=0; i != [self countOfRelations]; ++i) {
- MCPRelation *theRelation = (MCPRelation *)[self objectInRelationsAtIndex:i];
-
- if (! [theRelation isToMany]) {
- [theToOneRel insertObject:[theRelation name] atIndex:j];
- ++j;
- }
- }
- theRet = [NSArray arrayWithArray:theToOneRel];
- [theToOneRel release];
- return theRet;
-}
-
-#pragma mark Specifics for MCPObject
-- (NSArray *) primaryKeyAttributes
-{
- NSMutableArray *theRet = [NSMutableArray array];
- NSUInteger i, j;
-
- j = 0;
- for (i=0; i != [self countOfAttributes]; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *)[self objectInAttributesAtIndex:i];
-
- if ([theAttribute isPartOfKey]) {
- [theRet insertObject:theAttribute atIndex:j];
- ++j;
- }
- }
- return (NSArray *)theRet;
-}
-
-- (NSArray *) identityAttributes
-{
- NSMutableArray *theRet = [NSMutableArray array];
- NSUInteger i, j;
-
- j = 0;
- for (i=0; i != [self countOfAttributes]; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *)[self objectInAttributesAtIndex:i];
-
- if ([theAttribute isPartOfIdentity]) {
- [theRet insertObject:theAttribute atIndex:j];
- ++j;
- }
- }
- return (NSArray *)theRet;
-}
-
-- (MCPAttribute *) attributeWithName: (NSString *) iName
-{
-// This type of implementation is NOT working : most likely the isEqual method is called on iName rather than on the objects of the array
-/*
- unsigned int index = [self indexOfAttribute:iName];
-
- return (NSNotFound != index) ? (MCPAttribute *)[self objectInAttributesAtIndex:index] : nil ;
-*/
- NSUInteger i;
-
- for (i = 0; [attributes count] != i; ++i) {
- if ([[(MCPAttribute *)[attributes objectAtIndex:i] name] isEqualToString:iName]) {
- return (MCPAttribute *)[attributes objectAtIndex:i];
- }
- }
- return nil;
-}
-
-- (MCPRelation *) relationWithName:(NSString *) iRelationName
-{
-// This type of implementation is NOT working : most likely the isEqual method is called on iName rather than on the objects of the array
-/* unsigned int index = [relations indexOfObject:iRelationName];
-
- return (NSNotFound != index) ? (MCPRelation *)[relations objectAtIndex:index] : nil;
-*/
- NSUInteger i;
-
- for (i = 0; [relations count] != i; ++i) {
- if ([[(MCPRelation *)[relations objectAtIndex:i] name] isEqualToString:iRelationName]) {
- return (MCPRelation *)[relations objectAtIndex:i];
- }
- }
- return nil;
-}
-
-- (BOOL) singleIntAutoGenKey
-{
- NSArray *theKeys = [self primaryKeyAttributes];
-
- if (1 == [theKeys count]) {
- MCPAttribute *theSingleKey = (MCPAttribute *)[theKeys objectAtIndex:0];
-
- return [theSingleKey autoGenerated] && [[theSingleKey externalType] isEqualToString:@"INT"];
- }
- return NO;
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+Private.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+Private.h
deleted file mode 100644
index df86b763..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription+Private.h
+++ /dev/null
@@ -1,45 +0,0 @@
-//
-// $Id$
-//
-// MCPClassDescription+Private.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPClassDescription.h"
-
-@interface MCPClassDescription (Private)
-
-#pragma mark Setters
-- (void) setAttributes:(NSArray *) iAttributes;
-- (void) setRelations:(NSArray *) iRelations;
-- (void) insertObject:(MCPRelation *) iRelation inIncomingsAtIndex:(NSUInteger) index;
-- (void) removeObjectFromIncomingsAtIndex:(NSUInteger) index;
-
-#pragma mark Getters
-- (NSArray *) incomings;
-- (NSUInteger) countOfIncomings;
-- (MCPRelation *) objectInIncomingsAtIndex:(NSUInteger) index;
-- (NSUInteger) indexOfIncoming:(id) iRelation;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.h
deleted file mode 100644
index cff3cf17..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.h
+++ /dev/null
@@ -1,93 +0,0 @@
-//
-// $Id$
-//
-// MCPClassDescription.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-@class MCPModel;
-@class MCPAttribute;
-@class MCPRelation;
-@class MCPRelation;
-
-@interface MCPClassDescription : NSClassDescription <NSCoding>
-{
-@protected
- MCPModel *model; // The model where we stand
- NSString *name; // Name of the class (can not use className, as it is already used by NSObject).
- NSString *externalName; // Name of the table for storage
- NSMutableArray *attributes; // array of the attributes of the class description
- NSMutableArray *relations; // array of the relations of the class description (both origin and destination)
- NSMutableArray *incomings; // array if the INCOMMING relation (just to be sure we are able to invalidate those if necessary)
- Class representedClass; // the class object that the description represents.
-}
-
-// This correspond to the method singleIntAutoGenKey in the category MCPEntreprise... which name should I change...
-
-#pragma mark Class methods
-+ (void) initialize;
-
-#pragma mark Life cycle
-- (id) initInModel:(MCPModel *) iModel withName:(NSString *) iName;
-- (void) dealloc;
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder;
-- (void) encodeWithCoder:(NSCoder *) encoder;
-
-#pragma mark Making new attributes and relations
-- (MCPAttribute *) addNewAttributeWithName:(NSString *) iName inPosition:(NSInteger) index;
-- (MCPRelation *) addNewRelationTo:(MCPClassDescription *) iTo name:(NSString *) iName inPostion:(NSInteger) index;
-
-#pragma mark Setters
-- (void) setName:(NSString *) iName;
-- (void) setExternalName:(NSString *) iExternalName;
-- (void) insertObject:(MCPAttribute *) iAttribute inAttributesAtIndex:(NSUInteger) index;
-- (void) removeObjectFromAttributesAtIndex:(NSUInteger) index;
-- (void) insertObject:(MCPRelation *) iRelation inRelationsAtIndex:(NSUInteger) index;
-- (void) removeObjectFromRelationsAtIndex:(NSUInteger) index;
-
-#pragma mark Getters
-- (MCPModel *) model;
-- (NSString *) name;
-- (NSString *) externalName;
-- (NSArray *) attributes;
-- (NSUInteger) countOfAttributes;
-- (MCPAttribute *) objectInAttributesAtIndex:(NSUInteger) index;
-- (NSUInteger) indexOfAttribute:(id) iAttribute;
-- (NSArray *) relations;
-- (NSUInteger) countOfRelations;
-- (MCPRelation *) objectInRelationsAtIndex:(NSUInteger) index;
-- (NSUInteger) indexOfRelation:(id) iRelation;
-- (Class) representedClass;
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject;
-
-#pragma mark Output for logging
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.m
deleted file mode 100644
index 9f2ad18d..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPClassDescription.m
+++ /dev/null
@@ -1,373 +0,0 @@
-//
-// $Id$
-//
-// MCPClassDescription.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPClassDescription.h"
-#import "MCPClassDescription+Private.h"
-
-#import "MCPEntrepriseNotifications.h"
-
-#import "MCPModel.h"
-#import "MCPAttribute.h"
-#import "MCPRelation.h"
-
-@implementation MCPClassDescription
-
-#pragma mark Class methods
-+ (void) initialize
-{
- if (self = [MCPClassDescription class]) {
- [self setVersion:010101]; // Major.Minor.Revision -> MaMiRe
- }
- return;
-}
-
-#pragma mark Life cycle
-- (id) initInModel:(MCPModel *) iModel withName:(NSString *) iName
-{
- self = [super init];
- if (self) {
- model = iModel;
- [self setName:iName];
- attributes = [[NSMutableArray alloc] init];
- relations = [[NSMutableArray alloc] init];
- incomings = [[NSMutableArray alloc] init];
- representedClass = nil;
- // NSLog(@"MAKING a new object : %@", self);
- }
- return self;
-}
-
-- (void) dealloc
-{
-// NSArray *theRelations;
-// unsigned int i;
-
- [name release];
- [externalName release];
- [attributes release];
- while ([relations count]) {
- [(MCPRelation *)[relations objectAtIndex:0] invalidateRelation];
- }
- [relations release];
- while ([incomings count]) {
- [(MCPRelation *)[incomings objectAtIndex:0] invalidateRelation];
- }
- [incomings release];
- [super dealloc];
-}
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder
-{
- self = [super init];
- if ((self) && ([decoder allowsKeyedCoding])) {
- model = [decoder decodeObjectForKey:@"MCPmodel"];
-// NSLog(@"in MCPClassDescription initWithCoder, model = %@ (pointer = %p)", model, model);
- [self setName:[decoder decodeObjectForKey:@"MCPname"]];
- [self setExternalName:[decoder decodeObjectForKey:@"MCPexternalName"]];
- [self setAttributes:[decoder decodeObjectForKey:@"MCPattributes"]];
-// [self setRelations:[decoder decodeObjectForKey:@"MCPrelations"]];
- relations = [[NSMutableArray alloc] init];
- incomings = [[NSMutableArray alloc] init];
- representedClass = nil;
- [decoder decodeObjectForKey:@"MCPrelations"]; // The relation get linked properly while initted.
- }
- else {
- NSLog(@"For some reason, unable to decode MCPClassDescription from the coder!!!");
- }
-
- return self;
-}
-
-- (void) encodeWithCoder:(NSCoder *) encoder
-{
- if (! [encoder allowsKeyedCoding]) {
- NSLog(@"In MCPClassDescription -encodeWithCoder : Unable to encode to a non-keyed encoder!!, will not perform encoding!!");
- return;
- }
-// [encoder encodeObject:[self model] forKey:@"MCPmodel"];
- [encoder encodeConditionalObject:[self model] forKey:@"MCPmodel"];
- [encoder encodeObject:[self name] forKey:@"MCPname"];
- [encoder encodeObject:[self externalName] forKey:@"MCPexternalName"];
- [encoder encodeObject:[self attributes] forKey:@"MCPattributes"];
- [encoder encodeObject:[self relations] forKey:@"MCPrelations"];
- [encoder encodeObject:@"1.1.1" forKey:@"MCPversion"];
- return;
-}
-
-#pragma mark Making new attributes and relations
-- (MCPAttribute *) addNewAttributeWithName:(NSString *) iName inPosition:(NSInteger) index
-{
- MCPAttribute *theAttribute = [[MCPAttribute alloc] initForClassDescription:self withName:iName];
-
-// [self addAttribute:theAttribute];
- [self insertObject:theAttribute inAttributesAtIndex:(index < 0) ? ([self countOfAttributes] + index + 1) : index];
- [theAttribute release];
- return theAttribute;
-}
-
-- (MCPRelation *) addNewRelationTo:(MCPClassDescription *) iTo name:(NSString *) iName inPostion:(NSInteger) index
-{
- MCPRelation *theRelation = [[MCPRelation alloc] initWithName:iName from:self to:iTo];
-
- [theRelation release];
- return theRelation;
-}
-
-#pragma mark Setters
-- (void) setName:(NSString *) iName
-{
- if (iName != name) {
- [name release];
- name = [iName retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
- representedClass = nil;
- }
-}
-
-- (void) setExternalName:(NSString *) iExternalName
-{
- if (iExternalName != externalName) {
- [externalName release];
- externalName = [iExternalName retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
- }
-}
-
-- (void) insertObject:(MCPAttribute *) iAttribute inAttributesAtIndex:(NSUInteger) index
-{
- [attributes insertObject:iAttribute atIndex:index];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
-}
-
-- (void) removeObjectFromAttributesAtIndex:(NSUInteger) index
-{
- [attributes removeObjectAtIndex:index];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
-}
-
-- (void) insertObject:(MCPRelation *) iRelation inRelationsAtIndex:(NSUInteger) index
-{
- [relations insertObject:iRelation atIndex:index];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
-}
-
-- (void) removeObjectFromRelationsAtIndex:(NSUInteger) index
-{
- [relations removeObjectAtIndex:index];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
-}
-
-#pragma mark Getters
-- (MCPModel *) model
-{
- return model;
-}
-
-- (NSString *) name
-{
- return name;
-}
-
-- (NSString *) externalName
-{
- return externalName;
-}
-
-- (NSArray *) attributes
-{
- return [NSArray arrayWithArray:attributes];
-}
-
-- (NSUInteger) countOfAttributes
-{
- return [attributes count];
-}
-
-- (MCPAttribute *) objectInAttributesAtIndex:(NSUInteger) index
-{
- return (MCPAttribute *)((NSNotFound != index) ? [attributes objectAtIndex:index] : nil);
-}
-
-- (NSUInteger) indexOfAttribute:(id) iAttribute
-{
- return [attributes indexOfObject:iAttribute];
-}
-
-- (NSArray *) relations
-{
- return [NSArray arrayWithArray:relations];
-}
-
-- (NSUInteger) countOfRelations
-{
- return [relations count];
-}
-
-- (MCPRelation *) objectInRelationsAtIndex:(NSUInteger) index
-{
- return (MCPRelation *)((NSNotFound != index) ? [relations objectAtIndex:index] : nil);
-}
-
-- (NSUInteger) indexOfRelation:(id) iRelation
-{
- return [relations indexOfObject:iRelation];
-}
-
-- (Class) representedClass
-{
- if (representedClass) {
- return representedClass;
- }
- representedClass = NSClassFromString(name);
- return representedClass;
-}
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject
-// Equal to another class description if they have the same name.
-// Equal to a string if the string is equal to the className of the class description.
-{
- if ([iObject isKindOfClass:[MCPClassDescription class]]) {
- return [name isEqualToString:[(MCPClassDescription *)iObject name]];
- }
- if ([iObject isKindOfClass:[NSString class]]) {
- return [name isEqualToString:(NSString *)iObject];
- }
- return NO;
-}
-
-/*
-- (NSString *) description
-{
- return [NSString stringWithFormat:@"<MCPClassDescription for class named %@ : %p>", [self name], self];
-}
-
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale
-{
- return [self description];
-}
-*/
-
-#pragma mark Output for logging
-
-- (NSString *)descriptionWithLocale:(NSDictionary *) locale
-{
- NSUInteger i;
- NSMutableString *theOutput = [NSMutableString string];
-
- [theOutput appendFormat:@"MCPClassDescription for class : %@ (table : %@)\n", [self name], [self externalName]];
- for (i=0; [attributes count] != i; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *) [attributes objectAtIndex:i];
-
- [theOutput appendFormat:@"attribute %u, name = %@, column = %@. Allows null : %c\n", i, [theAttribute name], [theAttribute externalName], ([theAttribute allowsNull] ? 'Y' : 'N')];
- }
- return theOutput;
-}
-
-#pragma mark For debugging the retain counting
-- (id) retain
-{
- [super retain];
- return self;
-}
-
-- (void) release
-{
- [super release];
- return;
-}
-
-@end
-
-@implementation MCPClassDescription (Private)
-
-#pragma mark Setters
-- (void) setAttributes:(NSArray *) iAttributes
-{
- if (iAttributes != attributes) {
- [attributes release];
- attributes = [[NSMutableArray alloc] initWithArray:iAttributes];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
- }
-}
-
-- (void) setRelations:(NSArray *) iRelations
-{
- if (iRelations != relations) {
- [relations release];
- relations = [[NSMutableArray alloc] initWithArray:iRelations];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:model];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:self];
- }
-}
-
-- (void) insertObject:(MCPRelation *) iRelation inIncomingsAtIndex:(NSUInteger) index
-{
- if ([iRelation destination] == self) {
- [incomings insertObject:iRelation atIndex:index];
- }
- else {
- NSLog(@"in -[MCPClassDescription+Private insertObject:inIncomingsAtIndex:]. ERRROR : self is NOT the destination of the relation");
- }
-}
-
-- (void) removeObjectFromIncomingsAtIndex:(NSUInteger) index
-{
- [incomings removeObjectAtIndex:index];
-}
-
-#pragma mark Getters
-- (NSArray *) incomings
-{
- return [NSArray arrayWithArray:incomings];
-}
-
-- (NSUInteger) countOfIncomings
-{
- return [incomings count];
-}
-
-- (MCPRelation *) objectInIncomingsAtIndex:(NSUInteger) index
-{
- return (MCPRelation *)[incomings objectAtIndex:index];
-}
-
-- (NSUInteger) indexOfIncoming:(id) iRelation
-{
- return [incomings indexOfObject:iRelation];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.h
deleted file mode 100644
index 1bb903c4..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.h
+++ /dev/null
@@ -1,36 +0,0 @@
-//
-// $Id$
-//
-// MCPEnterpriseNotifications.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-#pragma mark Name for notification
-
-extern NSString *MCPModelChangedNotification;
-extern NSString *MCPClassDescriptionChangedNotification;
-extern NSString *MCPAttributeChangedNotification;
-extern NSString *MCPRelationChangedNotification;
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.m
deleted file mode 100644
index ec4f3793..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPEntrepriseNotifications.m
+++ /dev/null
@@ -1,34 +0,0 @@
-//
-// $Id$
-//
-// MCPEnterpriseNotifications.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-NSString *MCPModelChangedNotification = @"Model has changed";
-NSString *MCPClassDescriptionChangedNotification = @"ClassDescription has changed";
-NSString *MCPAttributeChangedNotification = @"Attribute has changed";
-NSString *MCPRelationChangedNotification = @"Relation has changed";
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.h
deleted file mode 100644
index 05e99f8d..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.h
+++ /dev/null
@@ -1,74 +0,0 @@
-//
-// $Id$
-//
-// MCPJoin.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 18/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-@class MCPModel;
-@class MCPClassDescription;
-@class MCPAttribute;
-@class MCPRelation;
-@class MCPRelation;
-
-@interface MCPJoin : NSObject <NSCoding>
-{
-@protected
- // Note that NONE of these attributes are retained!!!
- // Instead all these objects are notified of the existence of the join
- // and are responsible to invalidate/delete it if necessary.
- MCPRelation *relation;
- MCPAttribute *origin;
- MCPAttribute *destination;
-}
-
-#pragma mark Class methods
-+ (void) initialize;
-
-#pragma mark Life cycle
-- (id) initForRelation:(MCPRelation *) iRelation from:(MCPAttribute *) iOrigin to:(MCPAttribute *) iDestination;
-- (void) invalidate;
-- (void) dealloc;
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder;
-- (void) encodeWithCoder:(NSCoder *) encoder;
-
-#pragma mark Setters
-// No setter for relation : should be set at init time!
-- (void) setOrigin:(MCPAttribute *) iOrigin;
-- (void) setDestination:(MCPAttribute *) iDestination;
-
-#pragma mark Getters
-- (MCPRelation *) relation;
-- (MCPAttribute *) origin;
-- (MCPAttribute *) destination;
-- (NSUInteger) index;
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.m
deleted file mode 100644
index 576b1e10..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPJoin.m
+++ /dev/null
@@ -1,183 +0,0 @@
-//
-// $Id$
-//
-// MCPJoin.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 18/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPJoin.h"
-
-#import "MCPModel.h"
-#import "MCPClassDescription.h"
-#import "MCPAttribute.h"
-#import "MCPRelation.h"
-#import "MCPRelation.h"
-
-@implementation MCPJoin
-
-#pragma mark Class methods
-+ (void) initialize
-{
- if (self = [MCPJoin class]) {
- [self setVersion:010101]; // Ma.Mi.Re -> MaMiRe
- }
- return;
-}
-
-#pragma mark Life cycle
-- (id) initForRelation:(MCPRelation *) iRelation from:(MCPAttribute *) iOrigin to:(MCPAttribute *) iDestination;
-{
- self = [super init];
- if (self) {
- relation = iRelation;
- [self setOrigin:iOrigin];
- [self setDestination:iDestination];
- }
- return self;
-}
-
-- (void) invalidate
-{
- [self retain];
- NSLog(@"Enterring -[MCPJoin invalidate], retain count is %ld (after retaining : should be 4)", [self retainCount]);
- [origin removeObjectFromJoinsAtIndex:[origin indexOfJoinIdenticalTo:self]];
- [destination removeObjectFromJoinsAtIndex:[destination indexOfJoinIdenticalTo:self]];
- [relation removeObjectFromJoinsAtIndex:[relation indexOfJoinIdenticalTo:self]];
- NSLog(@"Enterring -[MCPJoin invalidate], retain count is %ld (before releasing : should be 1)", [self retainCount]);
- [self release];
- return;
-}
-
-- (void) dealloc
-{
- // Nothing to release, because the attributes are NOT retained.
- [super dealloc];
-}
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder
-{
- self = [super init];
- if ((self) && ([decoder allowsKeyedCoding])) {
- relation = [decoder decodeObjectForKey:@"MCPrelation"];
- [self setOrigin:[decoder decodeObjectForKey:@"MCPorigin"]];
- [self setDestination:[decoder decodeObjectForKey:@"MCPdestination"]];
- }
- else {
- NSLog(@"For some reason, unable to decode MCPJoin from the coder!!!");
- }
- return self;
-}
-
-- (void) encodeWithCoder:(NSCoder *) encoder
-{
- if (! [encoder allowsKeyedCoding]) {
- NSLog(@"In MCPJoin -encodeWithCoder : Unable to encode to a non-keyed encoder!!, will not perform encoding!!");
- return;
- }
- [encoder encodeObject:[self relation] forKey:@"MCPrelation"];
- [encoder encodeObject:[self origin] forKey:@"MCPorigin"];
- [encoder encodeObject:[self destination] forKey:@"MCPdestination"];
-}
-
-#pragma mark Setters
-- (void) setOrigin:(MCPAttribute *) iOrigin
-{
- if (origin != iOrigin) {
- if (origin) {
- [origin removeObjectFromJoinsAtIndex:[origin indexOfJoinIdenticalTo:self]];
- }
- origin = iOrigin;
- if (origin) {
- [origin insertObject:self inJoinsAtIndex:[origin countOfJoins]];
- }
- }
-}
-
-- (void) setDestination:(MCPAttribute *) iDestination
-{
- if (destination != iDestination) {
- if (destination) {
- [destination removeObjectFromJoinsAtIndex:[destination indexOfJoinIdenticalTo:self]];
- }
- destination = iDestination;
- if (destination) {
- [destination insertObject:self inJoinsAtIndex:[destination countOfJoins]];
- }
- }
-}
-
-#pragma mark Getters
-- (MCPRelation *) relation
-{
- return relation;
-}
-
-- (MCPAttribute *) origin
-{
- return origin;
-}
-
-- (MCPAttribute *) destination
-{
- return destination;
-}
-
-- (NSUInteger) index
-{
- return [relation indexOfJoinIdenticalTo:self];
-}
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject
-{
- if ([iObject isKindOfClass:[MCPJoin class]]) {
- MCPJoin *theJoin = (MCPJoin *)iObject;
-
- return ([relation isEqual:[theJoin relation]]) && ([origin isEqual:[theJoin origin]]) && ([destination isEqual:[theJoin destination]]);
- }
- if ([iObject isKindOfClass:[NSDictionary class]]) {
- NSDictionary *theDict = (NSDictionary *)iObject;
-
- return ([relation isEqual:[theDict valueForKey:@"relation"]]) && ([origin isEqual:[theDict valueForKey:@"origin"]]) && ([destination isEqual:[theDict valueForKey:@"destination"]]);
- }
- return NO;
-}
-
-#pragma mark For debugging the retain counting
-- (id) retain
-{
- [super retain];
-
- return self;
-}
-
-- (void) release
-{
- [super release];
-
- return;
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.h
deleted file mode 100644
index 15aa9ed3..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.h
+++ /dev/null
@@ -1,35 +0,0 @@
-//
-// $Id$
-//
-// MCPModel+MCPEntreprise.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 01/11/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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 "MCPModel.h"
-
-@interface MCPModel (MCPEntreprise)
-
-- (void) registerAsClassDescriptionServer;
-- (void) registerDescriptionForClass:(NSNotification *) notification;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.m
deleted file mode 100644
index 2652f0dc..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel+MCPEntreprise.m
+++ /dev/null
@@ -1,57 +0,0 @@
-//
-// $Id$
-//
-// MCPModel+MCPEntreprise.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 01/11/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPModel+MCPEntreprise.h"
-
-#import "MCPObject.h"
-
-@implementation MCPModel (MCPEntreprise)
-
-#pragma mark Work as a class description server
-
-- (void) registerAsClassDescriptionServer
-{
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerDescriptionForClass:) name:NSClassDescriptionNeededForClassNotification object:nil];
-}
-
-- (void) registerDescriptionForClass:(NSNotification *) notification
-{
- Class theClass = [notification object];
-
- if ([theClass isSubclassOfClass:[MCPObject class]]) {
-
- NSString *theClassName = NSStringFromClass(theClass);
- NSUInteger index = [self indexOfClassDescription:theClassName];
-
- if (NSNotFound != index) {
- [NSClassDescription registerClassDescription:(NSClassDescription *)[self objectInClassDescriptionsAtIndex:index] forClass:theClass];
- }
- }
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.h
deleted file mode 100644
index 0a6c6afd..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.h
+++ /dev/null
@@ -1,84 +0,0 @@
-//
-// $Id$
-//
-// MCPModel.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-@class MCPClassDescription;
-@class MCPAttribute;
-@class MCPRelation;
-
-@interface MCPModel : NSObject <NSCoding>
-{
-@protected
- NSString *name; // Name of the model ... useless.
- NSMutableArray *classDescriptions; // Order of the class descriptions in the model.
- BOOL usesInnoDBTables; // The database should use InnoDB tables.
- // Might add a string holding définition of tables.
- // Might also add some sort of template for generated files (at least the header).
-}
-
-#pragma mark Class methods
-+ (void) initialize;
-
-#pragma mark Life cycle
-- (id) initWithName:(NSString *) iName;
-- (void) dealloc;
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder;
-- (void) encodeWithCoder:(NSCoder *) encoder;
-
-#pragma mark Making new class description
-- (MCPClassDescription *) addNewClassDescriptionWithName:(NSString *) iName inPosition:(NSInteger) index;
-
-#pragma mark Setters
-- (void) setName:(NSString *) iName;
-- (void) setClassDescriptions:(NSArray *) iClassDescriptions;
-- (void) insertObject:(MCPClassDescription *) iClassDescription inClassDescriptionsAtIndex:(NSUInteger) index;
-- (void) removeObjectFromClassDescriptionsAtIndex:(NSUInteger) index;
-- (void) setUsesInnoDBTables:(BOOL) iUsesInnoDB;
-
-// Deprecated : non KVC
-//- (void) removeClassDescription:(MCPClassDescription *) iClassDescription;
-//- (void) addClassDescription:(MCPClassDescription *) iClassDescription;
-
-#pragma mark Getters
-- (NSString *) name;
-- (NSArray *) classDescriptions;
-- (NSUInteger) countOfClassDescriptions;
-- (MCPClassDescription *) objectInClassDescriptionsAtIndex:(NSUInteger) index;
-- (NSUInteger) indexOfClassDescription:(id) iClassDescription;
-- (BOOL) usesInnoDBTables;
-
-// Deprecated : non KVC
-//- (MCPClassDescription *) classDescriptionWithClassName:(NSString *) iClassDescriptionClassName;
-
-#pragma mark Output for logging
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.m
deleted file mode 100644
index 7c73eff1..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPModel.m
+++ /dev/null
@@ -1,230 +0,0 @@
-//
-// $Id$
-//
-// MCPModel.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 09/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPModel.h"
-
-#import "MCPEntrepriseNotifications.h"
-
-#import "MCPClassDescription.h"
-#import "MCPAttribute.h"
-#import "MCPRelation.h"
-
-@implementation MCPModel
-
-#pragma mark Class methods
-+ (void) initialize
-{
- if (self = [MCPModel class]) {
- [self setVersion:010101]; // Ma.Mi.Re -> MaMiRe
- }
- return;
-}
-
-#pragma mark Life cycle
-- (id) initWithName:(NSString *) iName
-{
- self = [super init];
- if (self) {
- [self setName:iName];
- classDescriptions = [[NSMutableArray alloc] init];
- }
-
- return self;
-}
-
-- (void) dealloc
-{
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- [name release];
- [classDescriptions release];
- [super dealloc];
-}
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder
-{
- self = [super init];
- if ((self) && ([decoder allowsKeyedCoding])) {
- [self setName:[decoder decodeObjectForKey:@"MCPname"]];
- [self setClassDescriptions:[decoder decodeObjectForKey:@"MCPclassDescriptions"]];
- [self setUsesInnoDBTables:[decoder decodeBoolForKey:@"MCPusesInnoDBTables"]];
- }
- else {
- NSLog(@"For some reason, unable to decode MCPModel from the coder!!!");
- }
-
- return self;
-}
-
-- (void) encodeWithCoder:(NSCoder *) encoder
-{
- if (! [encoder allowsKeyedCoding]) {
- NSLog(@"In MCPModel -encodeWithCoder : Unable to encode to a non-keyed encoder!!, will not perform encoding!!");
- return;
- }
-// [super encodeWithCoder:encoder];
- [encoder encodeObject:[self name] forKey:@"MCPname"];
- [encoder encodeObject:[self classDescriptions] forKey:@"MCPclassDescriptions"];
- [encoder encodeBool:[self usesInnoDBTables] forKey:@"MCPusesInnoDBTables"];
- [encoder encodeObject:@"1.1.1" forKey:@"MCPversion"];
- return;
-}
-
-#pragma mark Making new class description
-- (MCPClassDescription *) addNewClassDescriptionWithName:(NSString *) iName inPosition:(NSInteger) index;
-{
- MCPClassDescription *theClassDescription = [[MCPClassDescription alloc] initInModel:self withName:iName];
-
-// [self addClassDescription:theClassDescription];
- [self insertObject:theClassDescription inClassDescriptionsAtIndex:(index < 0) ? ([self countOfClassDescriptions] + index + 1) : index];
- [theClassDescription release];
- return theClassDescription;
-}
-
-#pragma mark Setters
-- (void) setName:(NSString *) iName
-{
- if (iName != name) {
- [name release];
- name = [iName retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:self];
- }
-}
-
-- (void) setClassDescriptions:(NSArray *) iClassDescriptions
-{
- if (iClassDescriptions != classDescriptions) {
- [classDescriptions release];
- classDescriptions = [[NSMutableArray alloc] initWithArray:iClassDescriptions];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:self];
- }
-}
-
-- (void) insertObject:(MCPClassDescription *) iClassDescription inClassDescriptionsAtIndex:(NSUInteger) index
-{
- [classDescriptions insertObject:iClassDescription atIndex:index];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:self];
-}
-
-- (void) removeObjectFromClassDescriptionsAtIndex:(NSUInteger) index
-{
- [classDescriptions removeObjectAtIndex:index];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:self];
-}
-
-- (void) setUsesInnoDBTables:(BOOL) iUsesInnoDB
-{
- usesInnoDBTables = iUsesInnoDB;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:self];
-}
-
-// Deprecated : non KVC
-/*
-- (void) removeClassDescription:(MCPClassDescription *) iClassDescription
-{
- [classDescriptions removeObject:iClassDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:self];
-}
-
- - (void) addClassDescription:(MCPClassDescription *) iClassDescription
- {
- [classDescriptions addObject:iClassDescription];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:self];
- }
-
- */
-
-#pragma mark Getters
-- (NSString *) name
-{
- return name;
-// return [NSString stringWithString:name];
-}
-
-- (NSArray *) classDescriptions
-{
- return [NSArray arrayWithArray:classDescriptions];
-}
-
-- (NSUInteger) countOfClassDescriptions
-{
- return [classDescriptions count];
-}
-
-- (MCPClassDescription *) objectInClassDescriptionsAtIndex:(NSUInteger) index
-{
- return (MCPClassDescription *)((NSNotFound != index) ? [classDescriptions objectAtIndex:index] : nil);
-}
-
-- (MCPClassDescription *) classDescriptionWithClassName:(NSString *) iClassDescriptionClassName
-{
-// Given the implementation of isEqual: for the MCPClassDescription, one should be able to use NSArray method directly:
- /* unsigned int i;
-
- for (i=0; ([classDescriptions count] != i) && (! [iClassDescriptionClassName isEqualToString:[(MCPClassDescription *) [classDescriptions objectAtIndex:i] className]]); ++i ) {
- }
- return (i == [classDescriptions count]) ? nil : (MCPClassDescription *)[classDescriptions objectAtIndex:i];
- */
- NSUInteger theIndex = [classDescriptions indexOfObject:iClassDescriptionClassName];
- return (NSNotFound == theIndex) ? nil : [classDescriptions objectAtIndex:theIndex];
-}
-
-- (NSUInteger) indexOfClassDescription:(id) iClassDescription
-{
- return [classDescriptions indexOfObject:iClassDescription];
-}
-
-- (BOOL) usesInnoDBTables
-{
- return usesInnoDBTables;
-}
-
-// Deprecated : non KVC
-
-#pragma mark Output for logging
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale
-{
- return [NSString stringWithFormat:@"<MCPModel with name %@ : %p>", [self name], self];
-}
-
-#pragma mark For debugging the retain counting
-- (id) retain
-{
- [super retain];
-
- return self;
-}
-
-- (void) release
-{
- [super release];
-
- return;
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.h
deleted file mode 100644
index 4f126928..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.h
+++ /dev/null
@@ -1,127 +0,0 @@
-//
-// $Id$
-//
-// MCPObject.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 19/05/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-/*" Possible return code on some operations of the database interaction. "*/
-enum {
- MCPDBReturnUnknown = 0, /*"Unknown state, should not happen."*/
- MCPDBReturnDeleted = 1, /*"The entry have been successfuly deleted from DB."*/
- MCPDBReturnUsed = 2, /*"The entry can not be removed, because some entries are still connected to it (some delete restrict/inhibit delete)."*/
- MCPDBReturnNone = 3, /*"No entry exist with this Id."*/
- MCPDBReturnNew = 4, /*"The entry was indeed new and inserted in the database."*/
- MCPDBReturnUpdated = 5, /*"The entry was updated in the DB."*/
- MCPDBReturnIncompleteKey = 6, /*"Part of the primary key is missing, action not taken."*/
- MCPDBReturnMultiple = 7, /*"Multiple rows are found with a query supposed to return at most one row."*/
- MCPDBReturnNoIdentity = 8, /*"The object does not have attributes that defines identity."*/
- MCPDBReturnNoKey = 9, /*"There is no primary key defined for this entity."*/
- MCPDBReturnNoConnection = 10, /*"The MCPObject is not having a connection."*/
- MCPDBReturnWrongRelationOrigin = 11, /*"Looking for a relation not which origin is not of the specified class."*/
- MCPDBReturnWrongRelationCardinality = 12, /*"Using a method assuming a cardinality of the relation while the relation as the other one."*/
- MCPDBReturnNoSuchRelation = 13, /*"There is no relation with such a name starting from this class."*/
- MCPDBReturnNotTarget = 14, /*"Tried to remove an object from a relation, while the objects does NOT belong to the relation."*/
- MCPDBReturnOK = 100 /*"Everything went OK."*/
-};
-typedef NSUInteger MCPDBReturnCode;
-
-@class MCPConnection;
-@class MCPClassDescription;
-@class MCPRelation;
-
-@interface MCPObject : NSObject {
- MCPClassDescription *classDescription;
- MCPConnection *connection;
-}
-
-#pragma mark Life of the Object
-/*" Life of the object "*/
-- (id) init;
-- (id) initWithDictionary:(NSDictionary *) dictionary;
-
-- (void) dealloc;
-
-- (void) setAttributesToDefault;
-
-#pragma mark Accessors
-/*" Accessor(s) "*/
-- (MCPClassDescription *) classDescription;
-- (MCPConnection *) connection;
-
-- (void) setConnection:(MCPConnection *) iConnection;
-
-#pragma mark Database interface
-/*" Database interface "*/
-- (id) readFromDBRow:(NSDictionary *) iDictionary withTableName:(NSString *) iTableName;
-- (MCPDBReturnCode) setPrimaryKey:(id) iDictionary andFetchFromDB:(MCPConnection *) iConnection;
-//- (MCPDBReturnCode) setPrimaryKey:(NSDictionary *) iDictionary andFetchFromDB:(MCPConnection *) iConnection;
-- (NSDictionary *) checkDBId; // the returned dictionary contains a MCPDBReturnCode key with the return code.
-- (NSDictionary *) saveInDB; // the returned dictionary contains a MCPDBReturnCode key with the return code.
-- (MCPDBReturnCode) getAutoGenerated;
-- (MCPDBReturnCode) updateInDB;
-- (MCPDBReturnCode) deleteInDB;
-+ (MCPDBReturnCode) deleteInDBUsingConnection:(MCPConnection *) iConnection withId:(id) iId;
-
-#pragma mark Handling relations
-/*" Handling realtions "*/
-- (id) getTargetOfRelation:(MCPRelation *) iRelation;
-- (id) getTargetOfRelationNamed:(NSString *) iRelationName;
-- (MCPDBReturnCode) setTarget:(id) iTarget forRelation:(MCPRelation *) iRelation;
-- (MCPDBReturnCode) setTarget:(id) iTarget forRelationNamed:(NSString *) iRelationName;
-- (NSUInteger) countTargetForRelation:(MCPRelation *) iRelation;
-- (NSUInteger) countTargetForRelationNamed:(NSString *) iRelationName;
-- (MCPObject *) getTargetOfRelation:(MCPRelation *) iRelation atIndex:(NSUInteger) iIndex;
-- (MCPObject *) getTargetOfRelationNamed:(NSString *) iRelationName atIndex:(NSUInteger) iIndex;
-- (MCPDBReturnCode) addTarget:(MCPObject *) iTarget toRelation:(MCPRelation *) iRelation;
-- (MCPDBReturnCode) addTarget:(MCPObject *) iTarget toRelationNamed:(NSString *) iRelationName;
-- (MCPDBReturnCode) removeTarget:(MCPObject *) iTarget toRelation:(MCPRelation *) iRelation;
-- (MCPDBReturnCode) removeTarget:(MCPObject *) iTarget toRelationNamed:(NSString *) iRelationName;
-- (MCPDBReturnCode) removeTargetToRelation:(MCPRelation *) iRelation atIndex:(NSUInteger) iIndex;
-- (MCPDBReturnCode) removeTargetToRelationNamed:(NSString *) iRelationName atIndex:(NSUInteger) iIndex;
-- (NSUInteger) indexOfTarget:(MCPObject *) iTarget inRelation:(MCPRelation *) iRelation;
-- (NSUInteger) indexOfTarget:(MCPObject *) iTarget inRelationNamed:(NSString *) iRelationName;
-
-#pragma mark Utilities
-/*" Utility methods "*/
-- (id) defaultValueForKey:(NSString *) iKey;
-- (NSDictionary *) primaryKey;
-
-/*" Testing equality (VERY important for relation management)"*/
-- (BOOL) isEqual:(id) iObject;
-
-#pragma mark Output
-/*" Output : "*/
-- (NSString *) description;
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale;
-
-#pragma mark Ordering the array for relations
-- (NSString *) orderSQLForClassDescription:(MCPClassDescription *) iClassDescription;
-
-/*" Anti-crash method... "*/
-- (void) setNilValueForKey:(NSString *) iKey;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.m
deleted file mode 100644
index dba963c6..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPObject.m
+++ /dev/null
@@ -1,1342 +0,0 @@
-//
-// $Id$
-//
-// MCPObject.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 19/05/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPObject.h"
-
-#import <MCPKit/MCPKit.h>
-
-#import "MCPClassDescription.h"
-#import "MCPClassDescription+MCPEntreprise.h"
-#import "MCPAttribute.h"
-#import "MCPRelation.h"
-#import "MCPJoin.h"
-
-@implementation MCPObject
-
-#pragma mark Life of the object
-- (id) init
-/*" Taking care of getting the class description for self (after passing the message up). "*/
-{
-// NSArray theAttributes;
-// unsigned int i;
-
- if (self = [super init]) {
- classDescription = [[NSClassDescription classDescriptionForClass:[self class]] retain];
- [self setAttributesToDefault];
-/*
- theAttributes = [classDescription attributeKeys];
- for (i=0; [theAttributes count] != i; ++i) { // setting the attributtes with proper defaults.
- NSString *theKey = (NSString *) [theAttributes objectAtIndex:i];
-
- [self setValue:[self defaultValueForKey:theKey] forKey:theKey];
- }
- */
- }
- return self;
-}
-
-- (id) initWithDictionary:(NSDictionary *) dictionary
-/*" This method will use the class description to fetch in the dictionary the values of the attributes of the object....
- Should try to get this description a bit clearer."*/
-{
- self = [super init];
- if (self) {
- NSUInteger i;
- NSArray *attrArray;
-
- classDescription = [[NSClassDescription classDescriptionForClass:[self class]] retain];
- [self setAttributesToDefault];
- attrArray = [classDescription attributes];
- for (i=0; [attrArray count] != i; ++i) {
- MCPAttribute *currentAttribute = (MCPAttribute *)[attrArray objectAtIndex:i];
- id currentValue = [dictionary objectForKey:[currentAttribute name]];
-
- if (! currentValue) {
- currentValue = [dictionary objectForKey:[currentAttribute externalName]];
- }
- if (currentValue) {
- [self setValue:currentValue forKey:[currentAttribute name]];
- }
- }
- }
- return self;
-}
-
-- (void) dealloc
-/*" Deallocating the class description, then passes the message to super. "*/
-{
-// unsigned int i;
-// NSArray *tmpAttributes = [classDescription attributes];
-
-/* for (i=0; [tmpAttributes count] != i; ++i) {
- MCPAttribute *tmpAttr = [tmpAttributes objectAtIndex:i];
- if ([tmpAttr valueClass]) {
- [self setValue:nil forKey:[tmpAttr name]];
- }
- }
-*/
- [classDescription release];
- [connection release];
- [super dealloc];
-}
-
-- (void) setAttributesToDefault
-/*" Set all the attributes to default values, except for auto-generated and primary key attributes, which are set to NULL.
-
- NOTE : !! In the current version the auto-generated and key are ALSO set to default values!!.
- "*/
-{
- NSArray *theAttributes = [classDescription attributes];
-// NSArray *thePrimKeys = [classDescription primaryKeyAttributes];
- NSUInteger i;
-
- for (i=0; [theAttributes count] != i; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *) [theAttributes objectAtIndex:i];
- NSString *theKey = [theAttribute name];
-
- if (! [theAttribute autoGenerated]) {
- [self setValue:[self defaultValueForKey:theKey] forKey:theKey];
- }
- else { // Auto-generated attribute ... set it to NULL:
- [self setValue:[self defaultValueForKey:theKey] forKey:theKey];
- }
- }
-/*
- for (i=0; [thePrimKeys count] != i; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *) [thePrimKeys objectAtIndex:i];
- if (! [theAttribute autoGenerated]) {
- NSString *theKey = [theAttribute name];
-
- [[self valueForKey:theKey] release];
- [self setValue:NULL forKey:theKey];
- }
- }
- */
- return;
-}
-
-#pragma mark Accessor(s)
-- (MCPClassDescription *) classDescription
-{
- return classDescription;
-}
-
-- (MCPConnection *) connection
-{
- if ((! connection) || (! [connection checkConnection])) {
- [self setConnection:nil];
- }
- return connection;
-}
-
-- (void) setConnection:(MCPConnection *) iConnection
-{
- if (iConnection != connection) {
- [connection release];
- connection = [iConnection retain];
- }
-}
-
-
-
-#pragma mark Database interface
-- (id) readFromDBRow:(NSDictionary *) iDictionary withTableName:(NSString *) iTableName
-/*" Uses a query result row (described as a NSDictionary) to set the instance variables of self. If
- the result contains columns from multiple tables, the iTableName can be used to specify the alias
- used for the table name corresponding to the class.
-
-If iTableName == nil, the columns will be searched first without table name (column_name) and if
- not found then with the table name in front (from the class description : table_name.column_name).
-
-Otherwise, the search will be performed in the following order : iTableName.column_name, column_name,
- table_name.column_name.
- "*/
-{
- NSArray *theAttributeKeys = [classDescription attributeKeys];
- NSArray *thePrefixArray;
- NSUInteger i;
-
-// Depending on the value of iTableName, get the search order.
- if ((nil == iTableName) || ([@"" isEqualToString:iTableName])) {
- thePrefixArray = [NSArray arrayWithObjects:@"", [NSMutableString stringWithFormat:@"%@.", [classDescription externalName]], nil];
- }
- else {
- thePrefixArray = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@.", iTableName], [NSMutableString stringWithFormat:@"%@.", [classDescription externalName]], @"", nil];
- }
- for (i=0; [theAttributeKeys count] != i; ++i) {
- id theValue = nil;
- MCPAttribute *theAttribute = [classDescription attributeWithName:[theAttributeKeys objectAtIndex:i]];
- NSUInteger j;
-
- for (j=0; [thePrefixArray count] != j; ++j) {
- if (theValue = [iDictionary objectForKey:[NSString stringWithFormat:@"%@%@", [thePrefixArray objectAtIndex:j], [theAttribute externalName]]]) {
- break;
- }
- }
- if (theValue) {
- [self takeValue:theValue forKey:[theAttribute name]];
- }
- }
- return self;
-}
-
-
-//- (MCPDBReturnCode) setPrimaryKey:(NSDictionary *) iDictionary andFetchFromDB:(MCPConnection *) iConnection
-- (MCPDBReturnCode) setPrimaryKey:(id) iDictionary andFetchFromDB:(MCPConnection *) iConnection
-/*" This method is used to retrieve an object from the DB given its precise primary key. It will return self.
- If the object is not found in the DB, then all instance variable are set to the default
- (and autogenerated/primary-key attributes are set to null)."*/
-{
- BOOL missingKey = NO;
- NSArray *theKeyAttr = [classDescription primaryKeyAttributes];
- NSUInteger i;
- NSMutableString *query = [NSMutableString stringWithFormat:@"SELECT * FROM %@ WHERE ", [classDescription externalName]];
- MCPResult *result;
- NSDictionary *row;
-
- [self setConnection:iConnection];
- if (! iConnection) {
- return MCPDBReturnNoConnection;
- }
- for (i=0; [theKeyAttr count] != i; ++i) {
- MCPAttribute *theAttr = [classDescription attributeWithName:[(MCPAttribute *)[theKeyAttr objectAtIndex:i] name]];
- id theKeyValue;
-
-// if (theKeyValue = [iDictionary objectForKey:[theAttr name]]) {
- if (theKeyValue = [iDictionary valueForKey:[theAttr name]]) {
- if (i != 0) {
- [query appendString:@" and "];
- }
-// Implies the iDictionary IS a dictionary:
-// [query appendFormat:@"(%@ = %@)", [theAttr externalName], [iConnection quoteObject:[iDictionary objectForKey:[theAttr name]]]];
-// If the iDictionary is just an object complying with NSValueCodeing:
- [query appendFormat:@"(%@ = %@)", [theAttr externalName], [iConnection quoteObject:theKeyValue]];
- }
- else { // Part of the primary key is missing... look for the DB name of the attribute
- if (theKeyValue = [iDictionary valueForKey:[theAttr externalName]]) {
- if (i != 0) {
- [query appendString:@" and "];
- }
- [query appendFormat:@"(%@ = %@)", [theAttr externalName], [iConnection quoteObject:theKeyValue]];
- }
- else { // Not able to find the value for this attribute !!!
- missingKey = YES;
- NSLog(@"Unable to find the value for attribute %@ of object of class %@, will make it default", [theAttr name], [self className]);
- break;
- }
- }
- } // Now the query is prepared... or a key part is missing:
- if (missingKey) {
- [self setAttributesToDefault];
- return MCPDBReturnIncompleteKey;
- }
- result = [iConnection queryString:query];
- if ([result numOfRows] == 0) {
- [self setAttributesToDefault];
- return MCPDBReturnNone;
- }
- row = [result fetchRowAsDictionary];
- [self readFromDBRow:row withTableName:@""];
- if ([result numOfRows] != 1) {
- NSLog(@"Got more than one row when querying : %@.... will take only the first one!!! that an IMPORTANT flaw in your data model!!!", query);
- return MCPDBReturnMultiple;
- }
- return MCPDBReturnOK;
-}
-
-
-- (NSDictionary *) checkDBId
-/*" Using the identity properties of the class, this method will check if self already exists in the DB,
- in which case it will set the primary key attributes to match the DB entry. If the object is not present
- in the DB, the primary key attributes are set to null if they are declared as aut-generated (untouched otherwise).
-
-The returned dictionary contains the values of the primary key attributes. It also contains one entry with
- key MCPDBReturnCode, which contains the result of the operation (was the object in DB?).
-
-If the identityAttributes of the class description is empty, the entry will always be considered not to be
- in the DB, AND the primary key attributes of the object will be left unchnaged and returned as they are at
- call time."*/
-{
- NSArray *theIdAttr = [classDescription identityAttributes];
- NSMutableDictionary *theKeys = [NSMutableDictionary dictionary];
- NSArray *theKeyAttr = [classDescription primaryKeyAttributes];
- MCPConnection *theConnection = [self connection];
- MCPResult *theResult;
- NSUInteger i;
-
- if (! theConnection) {
- return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:MCPDBReturnNoConnection], @"MCPDBReturnCode", nil];
- }
- if (! [theKeyAttr count]) { // There is no primary key for this object.
- [theKeys setObject:[NSNumber numberWithInteger:MCPDBReturnNoKey] forKey:@"MCPDBReturnCode"];
- return [NSDictionary dictionaryWithDictionary:theKeys];
- }
- if (! [theIdAttr count]) { // Identity is not defined for this object.
- [theKeys setObject:[NSNumber numberWithInteger:MCPDBReturnNoIdentity] forKey:@"MCPDBReturnCode"];
- for (i=0; [theKeyAttr count] != i; ++i) {
- NSString *theKey = [(MCPAttribute*)[theKeyAttr objectAtIndex:i] name];
- [theKeys setObject:[self valueForKey:theKey] forKey:theKey];
- }
- return [NSDictionary dictionaryWithDictionary:theKeys];
- }
-// Do the fetch in the DB.
- NSMutableString *theQuery = [NSMutableString stringWithString:@"SELECT "];
-
- for (i = 0; [theKeyAttr count] != i; ++i) {
- if (i) {
- [theQuery appendString:@", "];
- }
- [theQuery appendString:[(MCPAttribute *)[theKeyAttr objectAtIndex:i] externalName]];
- }
- [theQuery appendFormat:@" FROM %@ WHERE ", [classDescription externalName]];
- for (i = 0; [theIdAttr count] != i; ++i) {
- if (i) {
- [theQuery appendString:@" AND "];
- }
-/*
- if ([[(MCPAttribute *)[theIdAttr objectAtIndex:i] valueClass] isSubclassOfClass:[NSString class]]) {
- if ([(MCPAttribute *)[theIdAttr objectAtIndex:i] width] != 0) {
- [theQuery appendFormat:@"(BINARY %@ = SUBSTRING(%@ FROM 1 FOR %u)", [(MCPAttribute *)[theIdAttr objectAtIndex:i] externalName], [theConnection quoteObject:[self valueForKey:[(MCPAttribute *)[theIdAttr objectAtIndex:i] name]]], [(MCPAttribute *)[theIdAttr objectAtIndex:i] width]];
- }
- else {
- [theQuery appendFormat:@"(BINARY %@ = %@)", [(MCPAttribute *)[theIdAttr objectAtIndex:i] externalName], [theConnection quoteObject:[self valueForKey:[(MCPAttribute *)[theIdAttr objectAtIndex:i] name]]]];
- }
- }
- */
- if (([[(MCPAttribute *)[theIdAttr objectAtIndex:i] valueClass] isSubclassOfClass:[NSString class]]) && ([(MCPAttribute *)[theIdAttr objectAtIndex:i] width] != 0)) {
- [theQuery appendFormat:@"(%@ = SUBSTRING(%@ FROM 1 FOR %ld))", [(MCPAttribute *)[theIdAttr objectAtIndex:i] externalName], [theConnection quoteObject:[self valueForKey:[(MCPAttribute *)[theIdAttr objectAtIndex:i] name]]], [(MCPAttribute *)[theIdAttr objectAtIndex:i] width]];
- }
- else {
- [theQuery appendFormat:@"(%@ = %@)", [(MCPAttribute *)[theIdAttr objectAtIndex:i] externalName], [theConnection quoteObject:[self valueForKey:[(MCPAttribute *)[theIdAttr objectAtIndex:i] name]]]];
- }
- }
- [theQuery appendString:@" ORDER BY "];
- for (i = 0; [theKeyAttr count] != i; ++i) {
- if (i) {
- [theQuery appendString:@", "];
- }
- [theQuery appendString:[(MCPAttribute *)[theKeyAttr objectAtIndex:i] externalName]];
- }
- theResult = [theConnection queryString:theQuery];
- if ([theResult numOfRows]) { // the object was found.
- NSDictionary *theFirstRow = [theResult fetchRowAsDictionary];
- if ([theResult numOfRows] != 1) {
- NSLog(@"in MCPObject -checkDBIdWithConnection: method.... not only one (as expected) but %ld results were found, will take the first one.");
- [theKeys setObject:[NSNumber numberWithInteger:MCPDBReturnMultiple] forKey:@"MCPDBReturnCode"];
- }
- else {
- [theKeys setObject:[NSNumber numberWithInteger:MCPDBReturnOK] forKey:@"MCPDBReturnCode"];
- }
- [theKeys addEntriesFromDictionary:theFirstRow];
-// Setting the value of self for the primary key to the one just found.
- for (i=0; [theKeyAttr count] != i; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *) [theKeyAttr objectAtIndex:i];
-
- [self setValue:[theFirstRow objectForKey:[theAttribute externalName]] forKey:[theAttribute name]];
- }
- }
- else { // Object not found in the DB.
- for (i = 0; [theKeyAttr count] != i; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *)[theKeyAttr objectAtIndex:i];
-
- if ([theAttribute autoGenerated]) {
- [self setValue:[self defaultValueForKey:[theAttribute name]] forKey:[theAttribute name]];
- }
- [theKeys setObject:[self valueForKey:[theAttribute name]] forKey:[theAttribute name]];
- }
- [theKeys setObject:[NSNumber numberWithInteger:MCPDBReturnNone] forKey:@"MCPDBReturnCode"];
-// Setting the value of self for the primary key to the default values.
-/*
- for (i=0; [theKeyAttr count] != i; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *) [theKeyAttr objectAtIndex:i];
-
- [self setValue:[self defaultValueForKey:[theAttribute name]] forKey:[theAttribute name]];
- }
-*/
- }
- return [NSDictionary dictionaryWithDictionary:theKeys];
-}
-
-
-- (NSDictionary *) saveInDB
-/*" First will use the checkDBIdWithConnection method to check if the entry is already in the database. If this is the case,
- it will use the updateInDB... method to update the current DB instance. Otherwise it will make an insert into the database
- to save the entry, than it makes a select to get the value of autogenerated column, and use them (if necessary) to return
- the primary key (as NSDictionary).
-
- As for checkDBId... the returned dictionary also have a MCPDBReturnCode key with a NSNumber as value containing the
- return code of the operation."*/
-{
- MCPConnection *theConnection = [self connection];
- NSDictionary *theCheckReturn = [self checkDBId];
- NSMutableDictionary *theRet;
- NSInteger theCheckCode = [(NSNumber *)[theCheckReturn objectForKey:@"MCPDBReturnCode"] integerValue];
- NSUInteger i;
- NSUInteger j;
- NSMutableString *theQuery = [NSMutableString string];
- NSArray *theAttr = [classDescription attributes];
-
- switch (theCheckCode) {
- case MCPDBReturnNoIdentity : // For this object the identity is not set... so we try to save.
- break;
-
- case MCPDBReturnOK : // Object already in the DB (found using checkDBId... method).
- // NSLog(@"in saveUsingConnection: the entry already existed so will update the one with key : %@", theCheckReturn);
- theCheckCode = [self updateInDB];
- theRet = [NSMutableDictionary dictionaryWithDictionary:[self primaryKey]];
- [theRet setObject:[NSNumber numberWithInteger:theCheckCode] forKey:@"MCPDBReturnCode"];
- return [NSDictionary dictionaryWithDictionary:theRet];
- break;
-
- case MCPDBReturnMultiple : // Multiple were found, the first one will be updated.
- NSLog(@"Multiple entries found with the same identity ... will update the first one.");
- theCheckCode = [self updateInDB];
- theRet = [NSMutableDictionary dictionaryWithDictionary:[self primaryKey]];
- [theRet setObject:[NSNumber numberWithInteger:theCheckCode] forKey:@"MCPDBReturnCode"];
- return [NSDictionary dictionaryWithDictionary:theRet];
- break;
-
- case MCPDBReturnNone : // The entry is not already in the DB, save it...
- break;
-
- case MCPDBReturnNoConnection : // Self does not have a connection.
- NSLog(@"Can not save when the connection is not working...");
- break;
-
- default : // We should not arrive here anyway.
- NSLog(@"For some resons we got a unexpected result from checkDBId : %ld", theCheckCode);
- break;
- }
-
-// Generate the INSERT query:
- [theQuery appendFormat:@"INSERT INTO %@ (", [classDescription externalName]];
- j = 0;
- for (i=0; [theAttr count] != i; ++i) {
- if (! [(MCPAttribute *)[theAttr objectAtIndex:i] autoGenerated]) {
- if (j) {
- [theQuery appendString:@", "];
- }
- [theQuery appendString:[(MCPAttribute *)[theAttr objectAtIndex:i] externalName]];
- ++j;
- }
- }
- [theQuery appendString:@") VALUES ("];
- j = 0;
- for (i=0; [theAttr count] != i; ++i) {
- if (! [(MCPAttribute *)[theAttr objectAtIndex:i] autoGenerated]) {
- if (j) {
- [theQuery appendString:@", "];
- }
- [theQuery appendString:[theConnection quoteObject:[self valueForKey:[(MCPAttribute *)[theAttr objectAtIndex:i] name]]]];
- ++j;
- }
- }
- [theQuery appendString:@")"];
-// Finished preparing the query.
-
-// Now we perform the query...
- [theConnection queryString:theQuery];
- if (1 != (i = [theConnection affectedRows])) { // More than one row affected ... Should NEVER occure.
- NSLog(@"Problem while saving a MCPObject to the database : number of inserted rows is : %ld !!!", i);
- NSLog(@"Maybe there is an error : %@ ", [theConnection getLastErrorMessage]);
- NSLog(@"The class of the object is : %@, and it's description is :\n%@", [self className], [self descriptionWithLocale:nil]);
- theCheckCode = (i == 0) ? MCPDBReturnNone : MCPDBReturnMultiple;
- }
- else {
- theCheckCode = MCPDBReturnOK;
- }
-
-// Finally we get the primary key of the inserted object:
- if ([classDescription singleIntAutoGenKey]) {
- NSString *thePrimKey = [(MCPAttribute *) [[classDescription primaryKeyAttributes] objectAtIndex:0] name];
-
- [self setValue:[NSNumber numberWithLongLong:[theConnection insertId]] forKey:thePrimKey];
- }
- [self getAutoGenerated];
- theRet = [NSMutableDictionary dictionaryWithDictionary:[self primaryKey]];
- [theRet setObject:[NSNumber numberWithInteger:theCheckCode] forKey:@"MCPDBReturnCode"];
-
- return [NSDictionary dictionaryWithDictionary:theRet];
-}
-
-
-
-- (MCPDBReturnCode) getAutoGenerated
-/*" This method will use the Identity attributes of the object to retrieve the autogenerated
-attributes from the database.
-
-If the identity is not defined for this class/entity, then it will try to use the primary key
-to get the auto-generated values.
-
-Obviously this might generate a bug if one of the Identity attributes is autogenerated.
-This will create a trouble if some object does not have an identity defined but still contains
-some auto-generated attributes.
-"*/
-{
- NSMutableArray *theAutoAttr = [NSMutableArray array];
- NSArray *theAttr = [classDescription attributes];
- NSArray *theKeyAttr = [classDescription primaryKeyAttributes];
- NSUInteger i,j;
- NSMutableString *theQuery;
- NSInteger theCheckCode;
- MCPResult *theResult;
- NSDictionary *theRow;
- MCPConnection *theConnection = [self connection];
-
- if (! theConnection) {
- return MCPDBReturnNoConnection;
- }
-
- if (0 != [[classDescription identityAttributes] count]) {
- theCheckCode = [(NSNumber *)[[self checkDBId] objectForKey:@"MCPDBReturnCode"] integerValue];
- if ((MCPDBReturnOK != theCheckCode) && (MCPDBReturnMultiple != theCheckCode)) {
- NSLog(@"Unable to get the primary key for the object, will abort now the fetch of autoGenerated attributes (left unchanged)!");
- return theCheckCode;
- }
- if (MCPDBReturnMultiple == theCheckCode) {
- NSLog(@"Will get the autoGenerated values for the first entry....");
- }
- }
- j = 0;
- for (i=0; [theAttr count] != i; ++i) { // generate the array with autoGenerated attributes.
- if ([(MCPAttribute *)[theAttr objectAtIndex:i] autoGenerated]) {
- [theAutoAttr insertObject:[theAttr objectAtIndex:i] atIndex:j];
- ++j;
- }
- }
- if (0 == [theAutoAttr count]) {
- return MCPDBReturnOK;
- }
-
-// Make the query:
- theQuery = [NSMutableString stringWithString:@"SELECT "];
- for (i=0; [theAutoAttr count] != i; ++i) {
- if (i) {
- [theQuery appendString:@", "];
- }
- [theQuery appendString:[(MCPAttribute *)[theAutoAttr objectAtIndex:i] externalName]];
- }
- [theQuery appendFormat:@" FROM %@ WHERE ", [classDescription externalName]];
-// Preparing the Where Clause:
- for (i=0; [theKeyAttr count] != i; ++i) {
- if (i) {
- [theQuery appendString:@" AND "];
- }
- [theQuery appendFormat:@"( %@ = %@ )", [(MCPAttribute*)[theKeyAttr objectAtIndex:i] externalName], [theConnection quoteObject:[self valueForKey:[(MCPAttribute*)[theKeyAttr objectAtIndex:i] name]]]];
- }
-// Query is ready:
- theResult = [theConnection queryString:theQuery];
- if (! theResult) {
- NSLog(@"While fetching the auto-generated part of the object, got an error -a nil MCPResult-. Will report that as a MCPDBReturnNone.");
- return MCPDBReturnNone;
- }
- if (0 == [theResult numOfRows]) { // The entry was not found in the DB.
- if (0 == [[classDescription identityAttributes] count]) {
- NSLog(@"It seems that the object is not in the DB... but the identity is not defined so there might be a trouble with having the proper ID.");
- }
- return MCPDBReturnNone;
- }
-// Getting the values from the DB select:
- theRow = [theResult fetchRowAsDictionary];
- for (i=0; [theAutoAttr count] != i; ++i) {
- [self setValue:[theRow objectForKey:[(MCPAttribute*)[theAutoAttr objectAtIndex:i] externalName]] forKey:[(MCPAttribute*)[theAutoAttr objectAtIndex:i] name]];
- }
-// Returning the proper value:
- if (1 != [theResult numOfRows]) {
- NSLog(@"Multiple entries (or none : %llu), got the values for the first one...", [theResult numOfRows]);
- return MCPDBReturnMultiple;
- }
- return MCPDBReturnOK;
-}
-
-
-- (MCPDBReturnCode) updateInDB
-/*"This method will use the primary key value held by the object to modify the object that is saved in the DB.
-
- (NO YET IMPLEMENTED) If the primary key is not complete (some of the attributes are to null or 0) and the identityAttributes
- (from class description) is not an empty list then it will perform a checkDBId... to try to retrieve the
- missing part of the primary key.
- "*/
-{
- NSArray *theAttributes = [classDescription attributes];
- NSArray *thePrimKeyAttributes = [classDescription primaryKeyAttributes];
- NSMutableString *theQuery = [NSMutableString string];
- NSInteger theCheckCode;
- NSUInteger i, j;
- MCPConnection *theConnection = [self connection];
-
- if (! theConnection) {
- return MCPDBReturnNoConnection;
- }
-// Generate the query
- [theQuery appendFormat:@"UPDATE %@ SET ", [classDescription externalName]];
- // Prepare the value key pairs:
- j=0;
- for (i=0 ; [theAttributes count] != i; ++i) {
- id theValue = [self valueForKey:[(MCPAttribute *)[theAttributes objectAtIndex:i] name]];
-
- if ((theValue) && (! [(MCPAttribute *)[theAttributes objectAtIndex:i] autoGenerated])) {
- if (j) {
- [theQuery appendString:@", "];
- }
- [theQuery appendFormat:@"%@ = %@ ", [(MCPAttribute *)[theAttributes objectAtIndex:i] externalName], [theConnection quoteObject:theValue]];
- ++j;
- }
- }
- if (0 == j) { // Nothing has to be updated in this entry....
- NSLog(@"Tried to update a row from an object that does NOT contain any information!!");
- return MCPDBReturnNone;
- }
- // Prepare the WHERE clause:
- [theQuery appendFormat:@" WHERE "];
- j = 0;
- for (i=0; [thePrimKeyAttributes count] != i; ++i) {
- id theValue = [self valueForKey:[(MCPAttribute *)[thePrimKeyAttributes objectAtIndex:i] name]];
-
- if (j) {
- [theQuery appendString:@" AND "];
- }
- if (theValue) {
- [theQuery appendFormat:@"%@ = %@", [(MCPAttribute *)[thePrimKeyAttributes objectAtIndex:i] externalName], [theConnection quoteObject:theValue]];
- ++j;
- }
- }
-// Perform the update:
- if (j == [thePrimKeyAttributes count]) {
- [theConnection queryString:theQuery];
- i = [theConnection affectedRows];
- switch (i) {
- case 0 :
- theCheckCode = MCPDBReturnNone;
- break;
- case 1 :
- theCheckCode = MCPDBReturnOK;
- break;
- default :
- theCheckCode = MCPDBReturnMultiple;
- break;
- }
- }
- else {
- NSDictionary *theKeyCheck = [self checkDBId];
- NSInteger theIdCheckCode = [(NSNumber *) [theKeyCheck objectForKey:@"MCPDBReturnCode"] integerValue];
-
- if (MCPDBReturnOK == theIdCheckCode) {
- theCheckCode = [self updateInDB];
- }
- else {
- theCheckCode = MCPDBReturnNoKey;
- }
- }
-// Return proper code:
- return theCheckCode;
-}
-
-
-- (MCPDBReturnCode) deleteInDB
-/*" Uses the connection to delete the object from the DB. In this process the autoGenerated attributes are set to null.
- If the primary key is not completely set, this method calls checkDBId... method to try to complete it
- (if the identityAttributes of the class description is not empty)."*/
-{
- NSArray *theKeyAttributes = [classDescription primaryKeyAttributes];
- NSArray *theAttributes = [classDescription attributes];
- NSUInteger i;
-// NSMutableDictionary *theKeyValue = [NSMutableDictionary dictionary];
- NSInteger theCheckCode = MCPDBReturnOK;
- MCPConnection *theConnection = [self connection];
-
- if (! theConnection) {
- return MCPDBReturnNoConnection;
- }
-// Get the value of the primary key:
- for (i=0; [theKeyAttributes count] != i; ++i) {
- id theValue = [self valueForKey:[(MCPAttribute*) [theKeyAttributes objectAtIndex:i] name]];
- if ((! theValue) || ([theValue isKindOfClass:[NSNumber class]] && (0 == [theValue integerValue]))) {
- theCheckCode = MCPDBReturnIncompleteKey;
- break;
- }
- }
-// If incomplete, try to find the rest, and perform again:
- if (MCPDBReturnIncompleteKey == theCheckCode) {
- if (MCPDBReturnOK == [(NSNumber *)[[self checkDBId] objectForKey:@"MCPDBReturnCode"] integerValue]) {
- return [self deleteInDB];
- }
- else {
- return MCPDBReturnIncompleteKey;
- }
- }
-
-// Perform the deletion from the DB:
- theCheckCode = [[self class] deleteInDBUsingConnection:theConnection withId:self];
-
-// set the auto-generated attributes to proper values:
- for (i=0 ; [theAttributes count] != i; ++i) {
- MCPAttribute *theAttribute = (MCPAttribute *) [theAttributes objectAtIndex:i];
- if ([theAttribute autoGenerated]) {
-// [self setValue:NULL forKey:[theAttribute name]];
- [self setValue:[self defaultValueForKey:[theAttribute name]] forKey:[theAttribute name]];
- }
- }
-
-// Finished... just have to return the proper value:
- return theCheckCode;
-}
-
-
-+ (MCPDBReturnCode) deleteInDBUsingConnection:(MCPConnection *) iConnection withId:(id) iId
-/*" Uses the connection to remove from the DB the entry corresponding to the primary key id given by iId.
- If any part of the primary key is missing, nothing is done."*/
-{
- NSMutableString *theQuery = [NSMutableString string];
- MCPClassDescription *theClassDescription = (MCPClassDescription *) [NSClassDescription classDescriptionForClass:[self class]];
- NSArray *theKeyAttributes = [theClassDescription primaryKeyAttributes];
- NSUInteger i;
-
- if (! [iConnection checkConnection]) {
- return MCPDBReturnNoConnection;
- }
-// Generate the query:
- [theQuery appendFormat:@"DELETE FROM %@ WHERE ", [theClassDescription externalName]];
-// Prepare the WHERE STATEMENT:
- for (i=0; [theKeyAttributes count] != i; ++i) {
- if (i) {
- [theQuery appendString:@" AND "];
- }
-// [theQuery appendFormat:@"( %@ = %@ )", [(MCPAttribute*)[theKeyAttributes objectAtIndex:i] externalName], [iConnection quoteObject:[iId objectForKey:[(MCPAttribute*)[theKeyAttributes objectAtIndex:i] name]]]];
- [theQuery appendFormat:@"( %@ = %@ )", [(MCPAttribute*)[theKeyAttributes objectAtIndex:i] externalName], [iConnection quoteObject:[iId valueForKey:[(MCPAttribute*)[theKeyAttributes objectAtIndex:i] name]]]];
- }
-// Perform the query:
- [iConnection queryString:theQuery];
-// Return the proper code:
- i = [iConnection affectedRows];
-
- if (1 < i) {
- return MCPDBReturnMultiple;
- }
- if (0 == i) {
- return MCPDBReturnNone;
- }
- return MCPDBReturnOK;
-}
-
-
-#pragma mark Handling realtions
-- (id) getTargetOfRelation:(MCPRelation *) iRelation
-/*" This method is using the information from iRelation to fetch the targe of the relation in the DB.
-
-If iRelation is flagged as a to-one, then the return type is the type of the target object (value might be nil, if the target was not found).
-If iRelation is flagged as a to-many, then the return type is NSArray (and might be empty if no target were found).
-
-In any case this method is first checking that iRelation is starting from the class of self, and that self is connected to the DB.
-Also the returned object is ALWAYS autoreleased before being returned.
-"*/
-{
- NSMutableString *query;
- MCPClassDescription *destinationDesc;
- NSArray *joins;
- NSArray *keys;
- NSArray *ids;
- MCPResult *result;
- NSUInteger i;
- NSDictionary *theRow;
- id theRet;
-
- if (! iRelation) {
- NSLog(@"Tried to get the target of a relation... but the relation object is nil");
- }
- else {
-// NSLog(@"Trying to get the target of the realtion : %@", [iRelation descriptionWithLocale:nil]);
- }
- if ((! [connection isConnected]) || (! [classDescription isEqual:[iRelation origin]])) { // Error condition.
- return nil;
- }
-// Generating the query:
- destinationDesc = [iRelation destination];
- keys = [destinationDesc primaryKeyAttributes];
- joins = [iRelation joins];
- ids = [destinationDesc identityAttributes];
- query = [[NSMutableString alloc] initWithString:@"SELECT "];
- for (i=0; [keys count] != i; ++i) {
- if (i) {
- [query appendString:@", "];
- }
- [query appendString:[(MCPAttribute *)[keys objectAtIndex:i] externalName]];
- }
- [query appendFormat:@" FROM %@ WHERE ", [destinationDesc externalName]];
- for (i=0; [joins count] != i; ++i) {
- MCPJoin *theJoin = (MCPJoin *)[joins objectAtIndex:i];
-
- if (i) {
- [query appendString:@" and "];
- }
- [query appendFormat:@"(%@ = %@)", [[theJoin destination] externalName], [connection quoteObject:[self valueForKey:[[theJoin origin] name]]]];
- }
-// NSLog(@"in -[MCPObject getTargetOfRelation:%@]; query is %@...", [iRelation descriptionWithLocale:nil], query);
- [query appendString:[self orderSQLForClassDescription:destinationDesc]];
-// NSLog(@"in -[MCPObject getTargetOfRelation:%@]; query is %@...", [iRelation descriptionWithLocale:nil], query);
-/*
- [query appendString:@" ORDER BY "];
- for (i=0; [ids count] != i; ++i) { // Generating the order :
- if (i) {
- [query appendString:@", "];
- }
- [query appendString:[(MCPAttribute *)[ids objectAtIndex:i] externalName]];
- }
-*/
- result = [connection queryString:query];
- [query release];
-
-// Getting the results in proper objects:
- if ([iRelation isToMany]) { // To-Many relation
- NSMutableArray *theArrayRet = [[NSMutableArray alloc] init];
-
- theRet = theArrayRet;
- while (theRow = [result fetchRowAsDictionary]) {
- MCPObject *theTarget = [[[destinationDesc representedClass] alloc] init];
-
- [theTarget setPrimaryKey:theRow andFetchFromDB:connection];
- [theArrayRet insertObject:theTarget atIndex:[theArrayRet count]];
- [theTarget release];
- }
- }
- else { // To-One relation
- theRow = [result fetchRowAsDictionary];
- if (theRow) {
- theRet = [[[destinationDesc representedClass] alloc] init];
- [theRet setPrimaryKey:theRow andFetchFromDB:connection];
- }
- else {
- theRet = nil;
- }
- }
- [theRet autorelease];
- return theRet;
-}
-
-- (id) getTargetOfRelationNamed:(NSString *) iRelationName
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self getTargetOfRelation:theRelation] : nil;
-}
-
-- (MCPDBReturnCode) setTarget:(id) iTarget forRelation:(MCPRelation *) iRelation
-/*" This method will modify the DB content so that the corresponding relation is deleted.
- If any value corresping to an attribute of self is modified in the DB, then it will update all attributes of self to reflect DB status.
-
-Obviuosly this method is taking care of only to-one relation. It will hence check that iRelation is a to-one relation starting from self.
-Finally, you can use setTarget:nil forRelation:... to 'delete' a previously establlished relation (if the model and DB permit it)."*/
-{
- NSUInteger i;
- MCPObject *oldTarget;
-
- if (! [connection isConnected]) {
- return MCPDBReturnNoConnection;
- }
- if (! [classDescription isEqual:[iRelation origin]]) {
- return MCPDBReturnWrongRelationOrigin;
- }
- if ([iRelation isToMany]) {
- return MCPDBReturnWrongRelationCardinality;
- }
-
- oldTarget = [self getTargetOfRelation:iRelation];
- if ((oldTarget) && ([iTarget isEqual:oldTarget])) { // No need to change the relation's target.
- return MCPDBReturnOK;
- }
- for (i=0; [iRelation countOfJoins] != i; ++i) {
- MCPJoin *theJoin = [iRelation objectInJoinsAtIndex:i];
-
- if (([[theJoin origin] isPartOfKey]) && (![[theJoin destination] isPartOfKey])) { // Will change the destination...
- [iTarget setValue:[self valueForKey:[[theJoin origin] name]] forKey:[[theJoin destination] name]];
- [oldTarget setValue:[oldTarget defaultValueForKey:[[theJoin destination] name]] forKey:[[theJoin destination] name]];
- }
- else { // Will change the origin
- [self setValue:[iTarget valueForKey:[[theJoin destination] name]] forKey:[[theJoin origin] name]];
- }
- }
- if ([iRelation ownsDestination]) {
- [oldTarget deleteInDB];
- }
- return MCPDBReturnOK;
-}
-
-- (MCPDBReturnCode) setTarget:(id) iTarget forRelationNamed:(NSString *) iRelationName
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self setTarget:iTarget forRelation:theRelation] : MCPDBReturnNoSuchRelation;
-}
-
-- (NSUInteger) countTargetForRelation:(MCPRelation *) iRelation
-{
- NSMutableString *theQuery;
- NSUInteger i;
- NSArray *theJoinArray;
- MCPResult *theResult;
- NSDictionary *theRow;
-
- if ((! [connection isConnected]) || (! [classDescription isEqual:[iRelation origin]])){
- return 0;
- }
- theJoinArray = [iRelation joins];
- theQuery = [[NSMutableString alloc] initWithFormat:@"SELECT COUNT(1) FROM %@ WHERE ", [[iRelation destination] externalName]];
- for (i=0; [theJoinArray count] != i; ++i) {
- MCPJoin *theJoin = (MCPJoin *)[theJoinArray objectAtIndex:i];
- if (i) {
- [theQuery appendString:@" AND "];
- }
- [theQuery appendFormat:@"( %@ = %@ )", [[theJoin destination] externalName], [connection quoteObject:[self valueForKey:[[theJoin origin] name]]]];
- }
- theResult = [connection queryString:theQuery];
- [theQuery release];
- theRow = [theResult fetchRowAsDictionary];
- return [(NSNumber *)[theRow objectForKey:@"COUNT(1)"] unsignedIntegerValue];
-}
-
-- (NSUInteger) countTargetForRelationNamed:(NSString *) iRelationName
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self countTargetForRelation:theRelation] : 0;
-}
-
-
-- (MCPObject *) getTargetOfRelation:(MCPRelation *) iRelation atIndex:(NSUInteger) iIndex
-/*" This method will return the specific object which is the iIndex'th object of th relation (after ordering the object using the destination identity).
-
-This method (like other assuming order in the relation targets) will be doubtfull if the class does NOT have a single identity attribute."*/
-{
- NSMutableString *query;
- MCPClassDescription *destinationDesc;
- NSArray *joins;
- NSArray *keys;
- NSArray *ids;
- MCPResult *result;
- NSUInteger i;
- NSDictionary *theRow;
- MCPObject *theRet;
-
- if (! iRelation) {
- NSLog(@"Tried to get the target of a relation... but the relation object is nil");
- }
- else {
-// NSLog(@"Trying to get the target of the realtion : %@", [iRelation descriptionWithLocale:nil]);
- }
- if ((! [connection isConnected]) || (! [classDescription isEqual:[iRelation origin]])) { // Error condition.
- return nil;
- }
- if (! [iRelation isToMany]) {
- NSLog(@"Tried to use the -[MCPObject getTargetOfRelation:atIndex:] on a to-one relation... this does NOT works!!! You should use -[MCPObject getTargetOfRelation:] instead!!!");
- return [self getTargetOfRelation:iRelation];
- }
-// Generating the query:
- destinationDesc = [iRelation destination];
- keys = [destinationDesc primaryKeyAttributes];
- joins = [iRelation joins];
- ids = [destinationDesc identityAttributes];
- query = [[NSMutableString alloc] initWithString:@"SELECT "];
- for (i=0; [keys count] != i; ++i) {
- if (i) {
- [query appendString:@", "];
- }
- [query appendString:[(MCPAttribute *)[keys objectAtIndex:i] externalName]];
- }
- [query appendFormat:@" FROM %@ WHERE ", [destinationDesc externalName]];
- for (i=0; [joins count] != i; ++i) {
- MCPJoin *theJoin = (MCPJoin *)[joins objectAtIndex:i];
-
- if (i) {
- [query appendString:@" and "];
- }
- [query appendFormat:@"(%@ = %@)", [[theJoin destination] externalName], [connection quoteObject:[self valueForKey:[[theJoin origin] name]]]];
- }
- [query appendString:[self orderSQLForClassDescription:destinationDesc]];
-/*
- [query appendString:@" ORDER BY "];
- for (i=0; [ids count] != i; ++i) { // Generating the order :
- if (i) {
- [query appendString:@", "];
- }
- [query appendString:[(MCPAttribute *)[ids objectAtIndex:i] externalName]];
- }
-*/
- [query appendFormat:@" LIMIT 1 OFFSET %ld", iIndex];
- result = [connection queryString:query];
- [query release];
-
-// Getting the results in proper objects:
- theRow = [result fetchRowAsDictionary];
- if (theRow) {
- theRet = (MCPObject *)[[[destinationDesc representedClass] alloc] init];
- [theRet setPrimaryKey:theRow andFetchFromDB:connection];
- [theRet autorelease];
- }
- else {
- theRet = nil;
- }
- return theRet;
-}
-
-- (MCPObject *) getTargetOfRelationNamed:(NSString *) iRelationName atIndex:(NSUInteger) iIndex
-/*"This is the equivalent of the getTargetOfRelation:atIndex:, but giving a relation name instead of the MCPRelation object itself."*/
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self getTargetOfRelation:theRelation atIndex:iIndex]: nil;
-}
-
-- (MCPDBReturnCode) addTarget:(MCPObject *) iTarget toRelation:(MCPRelation *) iRelation
-/*" This method will modify the DB content so that the corresponding relation is added.
-If any value corresping to an attribute of self i modified in the DB, then it will update all attributes of self to reflect DB status.
-
-Obviuosly this method is taking care of only to-many relation. It will hence check that iRelation is a to-many relation starting from self."*/
-{
- NSArray *joins;
- NSUInteger i;
- NSDictionary *saveReturn;
-
- if (! [connection isConnected]) {
- return MCPDBReturnNoConnection;
- }
- if (! [classDescription isEqual:[iRelation origin]]) {
- return MCPDBReturnWrongRelationOrigin;
- }
- if (! [iRelation isToMany]) {
- return MCPDBReturnWrongRelationCardinality;
- }
- joins = [iRelation joins];
- for (i=0; [joins count] != i; ++i) { // Will change only values of iTarget, because it is a to-many relation.
- MCPJoin *join = (MCPJoin *)[joins objectAtIndex:i];
-
- [iTarget setValue:[self valueForKey:[[join origin] name]] forKey:[[join destination] name]];
- }
- if (! [[iTarget connection] isConnected]) {
- [iTarget setConnection:connection];
- }
- saveReturn = [iTarget saveInDB];
- return (MCPDBReturnCode)[(NSNumber *)[saveReturn objectForKey:@"MCPDBReturnCode"] unsignedIntegerValue];
-}
-
-- (MCPDBReturnCode) addTarget:(MCPObject *) iTarget toRelationNamed:(NSString *) iRelationName
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self addTarget:iTarget toRelation:theRelation] : MCPDBReturnNoSuchRelation;
-}
-
-- (MCPDBReturnCode) removeTarget:(MCPObject *) iTarget toRelation:(MCPRelation *) iRelation
-/*" This method will modify the DB content so that the corresponding relation is removed.
-If any value corresping to an attribute of self i modified in the DB, then it will update all attributes of self to reflect DB status.
-
-Obviuosly this method is taking care of only to-many relation. It will hence check that iRelation is a to-many relation starting from self."*/
-{
- NSArray *joins;
- NSUInteger i;
-// NSDictionary *saveReturn;
- BOOL targetIsTarget = YES;
- MCPDBReturnCode returnCode;
-
- if (! [connection isConnected]) {
- return MCPDBReturnNoConnection;
- }
- if (! [classDescription isEqual:[iRelation origin]]) {
- return MCPDBReturnWrongRelationOrigin;
- }
- if (! [iRelation isToMany]) {
- return MCPDBReturnWrongRelationCardinality;
- }
- joins = [iRelation joins];
- for (i=0; [joins count] != i; ++i) {
- MCPJoin *join = (MCPJoin *)[joins objectAtIndex:i];
- targetIsTarget = targetIsTarget && [[iTarget valueForKey:[[join destination] name]] isEqual:[self valueForKey:[[join origin] name]]];
- }
- if (! targetIsTarget) {
- return MCPDBReturnNotTarget;
- }
- if ([iRelation ownsDestination]) { // just delete the target from the DB.
- returnCode = [iTarget deleteInDB];
- }
- for (i=0; [joins count] != i; ++i) { // Put all the destination to default...
- MCPJoin *join = (MCPJoin *)[joins objectAtIndex:i];
-
- [iTarget setValue:[[join destination] defaultValue] forKey:[[join destination] name]];
- }
- if (! [iRelation ownsDestination]) {
- returnCode = [(NSNumber *)[[iTarget saveInDB] objectForKey:@"MCPDBReturnCode"] unsignedIntegerValue];
- }
- return returnCode;
-}
-
-- (MCPDBReturnCode) removeTarget:(MCPObject *) iTarget toRelationNamed:(NSString *) iRelationName
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self removeTarget:iTarget toRelation:theRelation] : MCPDBReturnNoSuchRelation;
-}
-
-- (MCPDBReturnCode) removeTargetToRelation:(MCPRelation *) iRelation atIndex:(NSUInteger) iIndex
-/*" This method will use an index t first query the object that it should remove from the relation, then uses the -[MCPObject removeTarget:toRelation:]
- method to remove the object from the relation. If the index is out of bound (the returned object is nil), it will return MCPDBReturnNone, to signal
- there was no object with this index in the relation."*/
-{
- MCPObject *target;
-
- if (! [connection isConnected]) {
- return MCPDBReturnNoConnection;
- }
- if (! [classDescription isEqual:[iRelation origin]]) {
- return MCPDBReturnWrongRelationOrigin;
- }
- if (! [iRelation isToMany]) {
- return MCPDBReturnWrongRelationCardinality;
- }
- target = [self getTargetOfRelation:iRelation atIndex:iIndex];
- if (target) {
- return [self removeTarget:target toRelation:iRelation];
- }
- else {
- return MCPDBReturnNone;
- }
-}
-
-- (MCPDBReturnCode) removeTargetToRelationNamed:(NSString *) iRelationName atIndex:(NSUInteger) iIndex
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self removeTargetToRelation:theRelation atIndex:iIndex] : MCPDBReturnNoSuchRelation;
-}
-
-- (NSUInteger) indexOfTarget:(MCPObject *) iTarget inRelation:(MCPRelation *) iRelation
-/*" Returns the index of the target object within the relation. Return NSNotFound if the objkect is NOT in the relation!!"*/
-{
- NSMutableString *query;
- NSArray *joins;
- NSArray *keys;
- NSArray *ids;
- NSUInteger i;
- MCPResult *result;
- NSDictionary *row;
- NSMutableDictionary *targetKey;
- BOOL targetIsTarget = YES;
-
- if ((! [connection isConnected]) || (! [classDescription isEqual:[iRelation origin]]) || (! [iRelation isToMany])) { // Checking the realtion object.
- return NSNotFound;
- }
- query = [[NSMutableString alloc] initWithString:@"SELECT "];
- joins = [iRelation joins];
-// keys = [[iRelation destination] attributeKeys];
- keys = [[iRelation destination] primaryKeyAttributes];
- ids = [[iRelation destination] identityAttributes];
- for (i=0; [keys count] != i; ++i) {
- if (i) {
- [query appendString:@", "];
- }
- [query appendString:[(MCPAttribute *)[keys objectAtIndex:i] externalName]];
- }
- [query appendFormat:@"FROM %@ WHERE ", [[iRelation destination] externalName]];
- for (i=0; [joins count] != i; ++i) {
- MCPJoin *join = (MCPJoin *)[joins objectAtIndex:i];
-
- targetIsTarget = targetIsTarget && [[iTarget valueForKey:[[join destination] name]] isEqual:[self valueForKey:[[join origin] name]]];
- if (i) {
- [query appendString:@" AND "];
- }
- [query appendFormat:@"( %@ = %@ )", [[join destination] externalName], [connection quoteObject:[self valueForKey:[[join origin] name]]]];
- }
- if (! targetIsTarget) { // Checking that iTarget belongs to the relation.
- [query release];
- return NSNotFound;
- }
- [query appendString:[self orderSQLForClassDescription:[iRelation destination]]];
-/*
- [query appendString:@" ORDER BY "];
- for (i=0; [ids count] != i; ++i) {
- if (i) {
- [query appendString:@", "];
- }
- [query appendString:[(MCPAttribute *)[ids objectAtIndex:i] externalName]];
- }
-*/
- targetKey = [[NSMutableDictionary alloc] init];
- for (i=0; [keys count] != i; ++i) { // Setting the targetKey to the row that should gives the target.
- MCPAttribute *attribute = (MCPAttribute *)[keys objectAtIndex:i];
-
- [targetKey setObject:[iTarget valueForKey:[attribute name]] forKey:[attribute externalName]];
- }
- result = [connection queryString:query];
- [query release];
- i = 0;
- while (row = [result fetchRowAsDictionary]) {
- if ([targetKey isEqualToDictionary:row]) { // We have found the proper object return i (after cleaning up);
- [targetKey release];
- return i;
- }
- ++i;
- }
- return NSNotFound;
-}
-
-- (NSUInteger) indexOfTarget:(MCPObject *) iTarget inRelationNamed:(NSString *) iRelationName
-/*" The equivalent of -[MCPObject indexOfTarget:inRelation:] but using relation name instead of a MCPRelation
-object. Indeed after getting the MCPRelation object corresponding to the name, this method will only return
-the result of the corresponding call to -[MCPObject indexOfTarget:inRelation:]."*/
-{
- MCPRelation *theRelation = [classDescription relationWithName:iRelationName];
- return (theRelation) ? [self indexOfTarget:iTarget inRelation:theRelation] : NSNotFound;
-}
-
-#pragma mark Utility methods
-- (id) defaultValueForKey:(NSString *) iKey
-/*" This method will return the default value (object) for the given key."*/
-{
- MCPAttribute *theAttribute = [classDescription attributeWithName:iKey];
-
- if ([theAttribute allowsNull]) {
-// return [NSNull null];
- return nil;
- }
- else {
- Class theAttrClass = [theAttribute valueClass];
- id theRet;
-
- if ([theAttrClass isSubclassOfClass:[NSNumber class]]) {
- return [NSNumber numberWithInteger:0];
- }
- theRet = [[[theAttrClass alloc] init] autorelease];
- if (nil == theRet) {
- NSLog(@"in MCPObject defaultValueForKey:%@ , for object of class %@, (attribute of class %@) the return value will be nil!!!", iKey, [self className], theAttrClass);
- }
- return theRet;
- }
-}
-
-
-- (NSDictionary *) primaryKey
-/*" Returns a dictionary with the values of the primary key. "*/
-{
- NSMutableDictionary *theRet = [NSMutableDictionary dictionary];
- NSArray *theIdAttr = [classDescription primaryKeyAttributes];
- NSUInteger i;
-
- for (i=0; [theIdAttr count] != i; ++i) {
- NSString *theKey = [(MCPAttribute *)[theIdAttr objectAtIndex:i] name];
-
- if ([self valueForKey:theKey]) {
- [theRet setObject:[self valueForKey:theKey] forKey:theKey];
- }
- else {
- [theRet setObject:[NSNull null] forKey:theKey];
- }
- }
- return [NSDictionary dictionaryWithDictionary:theRet];
-}
-
-#pragma mark Testing equality (VERY important for relation management)
-- (BOOL) isEqual:(id) iObject
-{
- NSArray *theIdAttr;
- NSUInteger i;
- BOOL theRet;
-
- if (self == iObject) {
- return YES;
- }
- if ([self class] != [iObject class]) {
- return NO;
- }
- theIdAttr = [classDescription identityAttributes];
- for (i = 0; [theIdAttr count] != i; ++i) {
- MCPAttribute *theAttr = [theIdAttr objectAtIndex:i];
-
- theRet = theRet && [[self valueForKey:[theAttr name]] isEqual:[iObject valueForKey:[theAttr name]]];
- }
- return theRet;
-}
-
-
-#pragma mark Output
-- (NSString *) description
-{
- return [self descriptionWithLocale:nil];
-}
-
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale
-{
- NSMutableString *theOutput = [NSMutableString string];
- NSUInteger i;
- NSArray *theAttributes = [classDescription attributes];
- BOOL trunc = [MCPConnection truncateLongField];
-
- [theOutput appendFormat:@"MCPObject subclass : %@\n", [self className]];
-
- for (i = 0; [theAttributes count] != i; ++i)
- {
- MCPAttribute *theAttribute = (MCPAttribute *) [theAttributes objectAtIndex:i];
- id theValue = [self valueForKey:[theAttribute name]];
-
- if (trunc) {
- if (([theValue isKindOfClass:[NSString class]]) && (kLengthOfTruncationForLog < [(NSString *)theValue length])) {
- theValue = [theValue substringToIndex:kLengthOfTruncationForLog];
- }
- else if (([theValue isKindOfClass:[NSData class]]) && (kLengthOfTruncationForLog < [(NSData *)theValue length])) {
- theValue = [NSData dataWithBytes:[theValue bytes] length:kLengthOfTruncationForLog];
- }
- }
-
- [theOutput appendFormat:@"\tAttribute %ld : name = %@, value = %@\n", i, [theAttribute name], theValue];
- }
-
- [theOutput appendString:@"\n"];
-
- return theOutput;
-}
-
-#pragma mark Ordering the array for relations
-- (NSString *) orderSQLForClassDescription:(MCPClassDescription *) iClassDescription
-{
- NSMutableArray *theAttributes = [[NSMutableArray alloc] initWithArray:[iClassDescription identityAttributes]];
- NSMutableString *theReturn = [NSMutableString string];
- NSUInteger i;
-
- for (i = 0; [[iClassDescription primaryKeyAttributes] count] != i; ++i) {
- [theAttributes insertObject:[[iClassDescription primaryKeyAttributes] objectAtIndex:i] atIndex:[theAttributes count]];
- }
- for (i = 0; [theAttributes count] != i; ++i) {
- if (i) {
- [theReturn appendString:@", "];
- }
- else {
- [theReturn appendString:@" ORDER BY "];
- }
- [theReturn appendString:[(MCPAttribute *)[theAttributes objectAtIndex:i] externalName]];
- }
- return theReturn;
-}
-
-#pragma mark Anti-crash method...
-- (void) setNilValueForKey:(NSString *) iKey
-{
- NSLog(@"Try to set %@ to nil .... not possible, will set it to zero instead...", iKey);
- [self setValue:[NSNumber numberWithInteger:0] forKey:iKey];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation+Private.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation+Private.h
deleted file mode 100644
index 2d3a7d8d..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation+Private.h
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// $Id$
-//
-// MCPRelation+Private.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 11/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPRelation.h"
-
-@interface MCPRelation (Private)
-
-#pragma mark Making some work
-- (void) invalidateJoins; // Check that the joins are realistics.
-
-#pragma mark Setters
-- (void) setOrigin:(MCPClassDescription *) iOrigin;
-//- (void) setJoins:(NSArray *) iJoins;
-
-#pragma mark Getters
-- (MCPModel *) model;
-
-#pragma mark Fro the controller layer and the UI
-- (void) addNewDefaultJoin;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.h b/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.h
deleted file mode 100644
index 118734eb..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.h
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// $Id$
-//
-// MCPRelation.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 11/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-@class MCPModel;
-@class MCPClassDescription;
-@class MCPAttribute;
-@class MCPJoin;
-
-typedef enum {
- OnDeleteNullify = 1,
- OnDeleteDeny = 2,
- OnDeleteCascade = 3,
- OnDeleteDefault = 4,
- OnDeleteNoAction = 5
-} MCPRelationDeleteRule;
-
-@interface MCPRelation : NSObject <NSCoding>
-{
-@protected
- NSString *name; // Name of the relation
- MCPRelationDeleteRule deleteRule; // Delete rule : what to do of the destination when origin is deleted
- MCPRelation *inverseRelation; // The inverse relation (or nil if no inverse present)
- MCPClassDescription *origin; // The class description from which the relation originate
- MCPClassDescription *destination; // The class description to which the relation arrives
- NSMutableArray *joins; // Joining attributes (array of MCPJoin)
- BOOL isToMany; // Is the relation to many (or to one)
- BOOL isMandatory; // Is the relation mandatory for the class description (origin)
- BOOL ownsDestination; // The origin class description owns the destination class description(ies)
-}
-
-#pragma mark Class methods
-+ (void) initialize;
-
-+ (NSArray *) existingDeleteRules;
-- (NSArray *) existingDeleteRules;
-
-#pragma mark Life cycle
-- (id) initWithName:(NSString *) iName from:(MCPClassDescription *) iFrom to:(MCPClassDescription *) iTo;
-- (void) invalidateRelation;
-- (void) dealloc;
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder;
-- (void) encodeWithCoder:(NSCoder *) encoder;
-
-#pragma mark Managing joins
-//- (MCPJoin *) addNewJoin;
-- (MCPJoin *) addJoinFrom:(MCPAttribute *) iFrom to:(MCPAttribute *) iTo;
-- (void) removeJoinFrom:(MCPAttribute *) iFrom to:(MCPAttribute *) iTo;
-//- (void) unjoinAttribute:(MCPAttribute *) iAttribute;
-
-#pragma mark Setters
-- (void) setDestination:(MCPClassDescription *) iDestination;
-- (void) setName:(NSString *) iName;
-- (void) setDeleteRule:(MCPRelationDeleteRule) iDeleteRule;
-- (void) setInverseRelation:(MCPRelation *) iInverseRelation;
-- (void) insertObject:(MCPJoin *) iJoin inJoinsAtIndex:(NSUInteger) index;
-- (void) removeObjectFromJoinsAtIndex:(NSUInteger) index;
-- (void) setIsToMany:(BOOL) iIsToMany;
-- (void) setIsMandatory:(BOOL) iIsMandatory;
-- (void) setOwnsDestintation:(BOOL) iOwnsDestination;
-
-#pragma mark Getters
-- (NSString *) name;
-- (MCPRelationDeleteRule) deleteRule;
-- (MCPRelation *) inverseRelation;
-- (MCPClassDescription *) origin;
-- (MCPClassDescription *) destination;
-- (NSArray *) joins;
-- (NSUInteger) countOfJoins;
-- (MCPJoin *) objectInJoinsAtIndex:(NSUInteger) index;
-- (NSUInteger) indexOfJoinIdenticalTo:(id) iJoin;
-- (BOOL) isToMany;
-- (BOOL) isMandatory;
-- (BOOL) ownsDestination;
-
-#pragma mark Some Usefull methods
-- (MCPAttribute *) destinationAttributeForOrigin:(MCPAttribute *) iFrom;
-- (MCPAttribute *) originAttributeForDestination:(MCPAttribute *) iTo;
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject;
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale;
-
-@end
diff --git a/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.m b/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.m
deleted file mode 100644
index 6d1e58f4..00000000
--- a/Frameworks/MCPKit/MCPEntrepriseKit/MCPRelation.m
+++ /dev/null
@@ -1,486 +0,0 @@
-//
-// $Id$
-//
-// MCPRelation.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 11/08/04.
-// Copyright (c) 2004 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPRelation.h"
-#import "MCPRelation+Private.h"
-
-#import "MCPEntrepriseNotifications.h"
-
-#import "MCPModel.h"
-#import "MCPClassDescription.h"
-#import "MCPClassDescription+Private.h"
-#import "MCPAttribute.h"
-
-#import "MCPJoin.h"
-
-static NSArray *MCPexistingDeleteRules;
-
-@implementation MCPRelation
-
-#pragma mark Class methods
-+ (void) initialize
-{
- if (self = [MCPRelation class]) {
- NSMutableArray *theExistingDeleteRules = [[NSMutableArray alloc] init];
-
- [self setVersion:010101]; // Ma.Mi.Re -> MaMiRe
-
- [theExistingDeleteRules addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInteger:OnDeleteNullify], @"tag", @"Nullify", @"name", nil]];
- [theExistingDeleteRules addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInteger:OnDeleteDeny], @"tag", @"Deny", @"name", nil]];
- [theExistingDeleteRules addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInteger:OnDeleteCascade], @"tag", @"Cascade", @"name", nil]];
- [theExistingDeleteRules addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInteger:OnDeleteDefault], @"tag", @"Default", @"name", nil]];
- [theExistingDeleteRules addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInteger:OnDeleteNoAction], @"tag", @"No Action", @"name", nil]];
- MCPexistingDeleteRules = [[NSArray alloc] initWithArray:theExistingDeleteRules];
- [theExistingDeleteRules release];
- }
- return;
-}
-
-+ (NSArray *) existingDeleteRules
-{
- return MCPexistingDeleteRules;
-}
-
-- (NSArray *) existingDeleteRules
-{
- return [MCPRelation existingDeleteRules];
-}
-
-
-#pragma mark Life cycle
-- (id) initWithName:(NSString *) iName from:(MCPClassDescription *) iFrom to:(MCPClassDescription *) iTo
-{
- self = [super init];
- if (self) {
- [self setName:iName];
- [self setOrigin:iFrom];
- [self setDestination:iTo];
- joins = [[NSMutableArray alloc] init];
- }
- return self;
-}
-
-- (void) invalidateRelation
-{
- [self retain]; // To be sure not to be released before the end of the method
- [self invalidateJoins]; // Remove each of the joins (so that attributes get notified)
-/*
- [origin removeObjectFromRelationsAtIndex:[[origin relations] indexOfObjectIdenticalTo:self]];
- origin = nil;
- [destination removeObjectFromIncomingsAtIndex:[[destination incomings] indexOfObjectIdenticalTo:self]];
- destination = nil;
-*/
- [self setOrigin:nil];
- [self setDestination:nil];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- [self release];
-}
-
-- (void) dealloc
-{
- [joins release]; // Should be empty by now...
- [name release];
-// The inverse relation don't have an inverse relation any more...
-// [inverseRelation setInverseRelation:nil];
- [self setInverseRelation:nil];
-// Other are weak references.
- [super dealloc];
-}
-
-#pragma mark NSCoding protocol
-- (id) initWithCoder:(NSCoder *) decoder
-{
- self = [super init];
- if ((self) && ([decoder allowsKeyedCoding])) {
- [self setName:[decoder decodeObjectForKey:@"MCPname"]];
- [self setDeleteRule:(MCPRelationDeleteRule)[decoder decodeInt32ForKey:@"MCPdeleteRule"]];
- if ([decoder containsValueForKey:@"MCPinverseRelation"]) {
- [self setInverseRelation:[decoder decodeObjectForKey:@"MCPinverseRelation"]];
- }
- else {
- [self setInverseRelation:nil];
- }
- [self setOrigin:[decoder decodeObjectForKey:@"MCPorigin"]];
- [self setDestination:[decoder decodeObjectForKey:@"MCPdestination"]];
-// [self setJoins:[decoder decodeObjectForKey:@"MCPjoins"]];
- joins = [[NSMutableArray alloc] initWithArray:[decoder decodeObjectForKey:@"MCPjoins"]];
- [self setIsToMany:[decoder decodeBoolForKey:@"MCPisToMany"]];
- [self setIsMandatory:[decoder decodeBoolForKey:@"MCPisMandatory"]];
- [self setOwnsDestintation:[decoder decodeBoolForKey:@"MCPownsDestination"]];
- }
-
- return self;
-}
-
-- (void) encodeWithCoder:(NSCoder *) encoder
-{
- if (! [encoder allowsKeyedCoding]) {
- NSLog(@"In MCPRelation -encodeWithCoder : Unable to encode to a non-keyed encoder!!, will not perform encoding!!");
- return;
- }
- [encoder encodeObject:[self name] forKey:@"MCPname"];
- [encoder encodeInt32:(int32_t)[self deleteRule] forKey:@"MCPdeleteRule"];
- if ([self inverseRelation]) {
- [encoder encodeObject:[self inverseRelation] forKey:@"MCPinverseRelation"];
- }
- [encoder encodeObject:[self origin] forKey:@"MCPorigin"];
- [encoder encodeObject:[self destination] forKey:@"MCPdestination"];
- [encoder encodeObject:[self joins] forKey:@"MCPjoins"];
- [encoder encodeBool:[self isToMany] forKey:@"MCPisToMany"];
- [encoder encodeBool:[self isMandatory] forKey:@"MCPisMandatory"];
- [encoder encodeBool:[self ownsDestination] forKey:@"MCPownsDestination"];
-}
-
-#pragma mark Making new joins
-/*
-- (MCPJoin *) addNewJoin // Usefull for the interface, to be able to create a new join by just using a binding.
-{
- [self addJoinFrom:[origin objectInAttributesAtIndex:0] to:[destination objectInAttributesAtIndex:0]];
-}
-*/
-
-- (MCPJoin *) addJoinFrom:(MCPAttribute *) iFrom to:(MCPAttribute *) iTo
-{
- MCPJoin *theJoin;
-
- if ([iFrom classDescription] != [self origin]) {
- NSLog(@"Tried to make a join starting from an attribute (%@) that does NOT belong to the origin class description (%@)! Will not perform the link", iFrom, [self origin]);
- return nil;
- }
- if ([iTo classDescription] != [self destination]) {
- NSLog(@"Tried to make a join arriving to an attribute (%@) that does NOT belong to the destination class description (%@)! Will not perform the link", iTo, [self destination]);
- return nil;
- }
- theJoin = [[MCPJoin alloc] initForRelation:self from:iFrom to:iTo];
-// theJoin = [[MCPJoin alloc] initFrom:iFrom to:iTo];
-// [joins addObject:theJoin];
- [joins insertObject:theJoin atIndex:[joins count]];
- [theJoin release];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- return theJoin;
-}
-
-- (void) removeJoinFrom:(MCPAttribute *) iFrom to:(MCPAttribute *) iTo
-{
- NSDictionary *theJoinDict = [[NSDictionary alloc] initWithObjectsAndKeys:self, @"relation", iFrom, @"origin", iTo, @"destination", nil];
- NSUInteger i = [joins indexOfObject:theJoinDict];
-
- if (NSNotFound != i) {
- [[self objectInJoinsAtIndex:i] invalidate];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
- [theJoinDict release];
-}
-
-/*
-- (void) unjoinAttribute:(MCPAttribute *) iAttribute
-{
- unsigned int i = 0;
-
-#warning HAVE to rewrite this code!!!
- if ([[iAttribute classDescription] isEqual:origin]) {
- for (i=0; ([joins count] != i) && ([iAttribute isEqual:[(MCPJoin *)[joins objectAtIndex:i] origin]]); ++i) {
- }
- }
- if ([[iAttribute classDescription] isEqual:destination]) {
- for (i=0; ([joins count] != i) && ([iAttribute isEqual:[(MCPJoin *)[joins objectAtIndex:i] destination]]); ++i) {
- }
- }
- if ((0 == i) || ([joins count] == i)) { // No joins found using this attribute.
- return;
- }
- [self removeJoinFrom:[(MCPJoin *)[joins objectAtIndex:i] origin] to:[(MCPJoin *)[joins objectAtIndex:i] destination]];
-}
-*/
-
-#pragma mark Setters
-- (void) setDestination:(MCPClassDescription *) iDestination
-{
- if (iDestination != destination) {
- [destination removeObjectFromIncomingsAtIndex:[[destination incomings] indexOfObjectIdenticalTo:self]];
- destination = iDestination;
- [destination insertObject:self inIncomingsAtIndex:0];
- [self invalidateJoins];
- }
-}
-
-
-- (void) setName:(NSString *) iName
-{
- if (iName != name) {
- [name release];
- name = [iName retain];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[origin model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:origin];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
-}
-
-- (void) setDeleteRule:(MCPRelationDeleteRule) iDeleteRule
-{
- if (iDeleteRule != deleteRule) { // Don't do the notification for nothing!!!
- deleteRule = iDeleteRule;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[origin model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:origin];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
-}
-
-- (void) setInverseRelation:(MCPRelation *) iInverseRelation
-{
- if (iInverseRelation != inverseRelation) {
- [inverseRelation release];
- inverseRelation = [iInverseRelation retain];
- [inverseRelation setInverseRelation:self];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[origin model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:origin];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
-}
-
-- (void) insertObject:(MCPJoin *) iJoin inJoinsAtIndex:(NSUInteger) index
-{
- [joins insertObject:iJoin atIndex:index];
-}
-
-- (void) removeObjectFromJoinsAtIndex:(NSUInteger) index
-{
- [joins removeObjectAtIndex:index];
-}
-
-- (void) setIsToMany:(BOOL) iIsToMany
-{
- if (iIsToMany != isToMany) { // Don't do the notification for nothing!!!
- isToMany = iIsToMany;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[origin model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:origin];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
-}
-
-- (void) setIsMandatory:(BOOL) iIsMandatory
-{
- if (iIsMandatory != isMandatory) { // Don't do the notification for nothing!!!
- isMandatory = iIsMandatory;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[origin model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:origin];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
-}
-
-- (void) setOwnsDestintation:(BOOL) iOwnsDestination
-{
- if (iOwnsDestination != ownsDestination) { // Don't do the notification for nothing!!!
- ownsDestination = iOwnsDestination;
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPModelChangedNotification object:[origin model]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPClassDescriptionChangedNotification object:origin];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
-}
-
-#pragma mark Getters
-- (NSString *) name
-{
- return name;
-}
-
-- (MCPRelationDeleteRule) deleteRule
-{
- return deleteRule;
-}
-
-- (MCPRelation *) inverseRelation
-{
- return inverseRelation;
-}
-
-- (MCPClassDescription *) origin
-{
- return origin;
-}
-
-- (MCPClassDescription *) destination
-{
- return destination;
-}
-
-- (NSArray *) joins
-{
- return [NSArray arrayWithArray:joins];
-}
-
-- (NSUInteger) countOfJoins
-{
- return [joins count];
-}
-
-- (MCPJoin *) objectInJoinsAtIndex:(NSUInteger) index
-{
- return (MCPJoin *)((NSNotFound != index) ? [joins objectAtIndex:index] : nil);
-}
-
-- (NSUInteger) indexOfJoinIdenticalTo:(id) iJoin
-{
- return [joins indexOfObjectIdenticalTo:iJoin];
-}
-
-- (BOOL) isToMany
-{
- return isToMany;
-}
-
-- (BOOL) isMandatory
-{
- return isMandatory;
-}
-
-- (BOOL) ownsDestination
-{
- return ownsDestination;
-}
-
-#pragma mark Some Usefull methods
-
-- (MCPAttribute *) destinationAttributeForOrigin:(MCPAttribute *) iFrom
-{
- NSUInteger i;
-
- for (i=0; ([joins count] != i) && ([[(MCPJoin *)[joins objectAtIndex:i] origin] isEqual:iFrom]); ++i) {
- }
- return ([joins count] == i) ? nil : [(MCPJoin *)[joins objectAtIndex:i] destination];
-}
-
-- (MCPAttribute *) originAttributeForDestination:(MCPAttribute *) iTo
-{
- NSUInteger i;
-
- for (i=0; ([joins count] != i) && ([[(MCPJoin *)[joins objectAtIndex:i] destination] isEqual:iTo]); ++i) {
- }
- return ([joins count] == i) ? nil : [(MCPJoin *)[joins objectAtIndex:i] origin];
-}
-
-
-#pragma mark Some general methods:
-- (BOOL) isEqual:(id) iObject
-// Equal to another relation, if they have the same name and same origin and destination class descriptions (they have the same names).
-// Equal to a string (NSString), if the name of the relation is equal to the string.
-{
- if ([iObject isKindOfClass:[MCPRelation class]]) {
- MCPRelation *theRelation = (MCPRelation *) iObject;
-
- return ([name isEqualToString:[theRelation name]]) && ([[self origin] isEqual:[theRelation origin]]) && ([[self destination] isEqual:[theRelation destination]]);
- }
- if ([iObject isKindOfClass:[NSString class]]) {
- return [name isEqualToString:(NSString *)iObject];
- }
- return NO;
-}
-
-- (NSString *) descriptionWithLocale:(NSDictionary *) locale
-{
- NSMutableString *theRet = [NSMutableString stringWithFormat:@"MCPRelation named %@, going from %@ to %@. Joins :\n", name, [origin name], [destination name]];
- NSUInteger i;
-
- for (i = 0; [joins count] != i; ++i) {
- MCPJoin *tmpJoin = (MCPJoin *)[joins objectAtIndex:i];
- [theRet appendFormat:@"\t\t%@ == %@\n", [[tmpJoin origin] name], [[tmpJoin destination] name]];
- }
- return theRet;
-}
-
-
-#pragma mark For debugging the retain counting
-- (id) retain
-{
- [super retain];
- return self;
-}
-
-- (void) release
-{
- [super release];
- return;
-}
-
-@end
-
-@implementation MCPRelation (Private)
-
-#pragma mark Making some work
-- (void) invalidateJoins
-{
- while ([joins count]) {
- [[self objectInJoinsAtIndex:0] invalidate];
- }
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
-}
-
-#pragma mark Setters
-- (void) setOrigin:(MCPClassDescription *) iOrigin
-{
- if (iOrigin != origin) {
- [origin removeObjectFromRelationsAtIndex:[[origin relations] indexOfObjectIdenticalTo:self]];
- origin = iOrigin;
- [origin insertObject:self inRelationsAtIndex:[origin countOfRelations]];
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- [self invalidateJoins];
- }
-}
-
-/*
-- (void) setJoins:(NSArray *) iJoins
-{
- if (iJoins != joins) {
- unsigned int i;
- if (joins) {
- [self invalidateJoins];
- }
- else {
- joins = [[NSMutableArray alloc] init];
- }
- for (i=0; [iJoins count] != i; ++i) {
- [self addJoinFrom:[(MCPJoin *)[iJoins objectAtIndex:i] origin] to:[(MCPJoin *)[iJoins objectAtIndex:i] destination]];
- }
- [[NSNotificationCenter defaultCenter] postNotificationName:MCPRelationChangedNotification object:self];
- }
-}
-*/
-
-#pragma mark Getters
-- (MCPModel *) model
-{
- return [origin model];
-}
-
-#pragma mark Fro the controller layer and the UI
-- (void) addNewDefaultJoin // Usefull for the interface, to be able to create a new join by just using a binding.
-{
- [self addJoinFrom:[origin objectInAttributesAtIndex:0] to:[destination objectInAttributesAtIndex:0]];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPConnection.h b/Frameworks/MCPKit/MCPFoundationKit/MCPConnection.h
deleted file mode 100644
index 0b3f932b..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPConnection.h
+++ /dev/null
@@ -1,282 +0,0 @@
-//
-// $Id$
-//
-// MCPConnection.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 08/12/2001.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-#import <pthread.h>
-
-#import "MCPConstants.h"
-#import "mysql.h"
-
-typedef struct {
- MYSQL *mySQLConnection;
- BOOL *pingActivePointer;
- BOOL *lastPingSuccessPointer;
-} MCPConnectionPingDetails;
-
-@class MCPResult, MCPStreamingResult;
-@protocol MCPConnectionProxy, MCPConnectionDelegate;
-
-@interface MCPConnection : NSObject
-{
- MYSQL *mConnection;
- BOOL mConnected;
- NSStringEncoding mEncoding;
- NSTimeZone *mTimeZone;
- NSUInteger mConnectionFlags;
-
- id <MCPConnectionDelegate> delegate;
-
- // Anything that performs a mysql_net_read is not thread-safe: mysql queries, pings
- // Always lock the connection first. Don't use this lock directly, use the lockConnection method!
- NSConditionLock *connectionLock;
-
- BOOL useKeepAlive;
- BOOL isDisconnecting;
- BOOL isReconnecting;
- BOOL userTriggeredDisconnect;
- NSInteger connectionTimeout;
- CGFloat keepAliveInterval;
-
- NSObject <MCPConnectionProxy> *connectionProxy;
- NSString *connectionLogin;
- NSString *connectionPassword;
- NSString *connectionHost;
- NSUInteger connectionPort;
- NSString *connectionSocket;
- NSUInteger maxAllowedPacketSize;
- unsigned long connectionThreadId;
-
- BOOL useSSL;
- NSString *sslKeyFilePath;
- NSString *sslCertificatePath;
- NSString *sslCACertificatePath;
-
- NSString *encoding, *previousEncoding;
- NSStringEncoding stringEncoding;
- BOOL encodingUsesLatin1Transport, previousEncodingUsesLatin1Transport;
-
- NSInteger currentProxyState;
-
- double lastQueryExecutionTime;
- double lastQueryExecutedAtTime;
- NSString *lastQueryErrorMessage;
- NSUInteger lastQueryErrorId;
- my_ulonglong lastQueryAffectedRows;
- MCPConnectionCheck lastDelegateDecisionForLostConnection;
-
- BOOL isMaxAllowedPacketEditable;
-
- NSString *serverVersionString;
- NSMutableDictionary *structure;
- NSMutableArray *allKeysofDbStructure;
-
- pthread_t pingThread;
- NSInteger pingFailureCount;
- BOOL pingThreadActive;
- BOOL lastPingSuccess;
- BOOL lastPingBlocked;
- NSTimer *keepAliveTimer;
- double lastKeepAliveTime;
- uint64_t connectionStartTime;
-
- BOOL retryAllowed;
- BOOL queryCancelled;
- BOOL queryCancelUsedReconnect;
- BOOL delegateQueryLogging;
- BOOL delegateResponseToWillQueryString;
- BOOL delegateSupportsConnectionLostDecisions;
- NSInteger isQueryingDbStructure;
- BOOL cancelQueryingDbStructure;
- BOOL lockQuerying;
- NSInteger automaticReconnectAttempts;
-
- // Pointers
- IMP cStringPtr;
- IMP willQueryStringPtr;
- IMP timeConnectedPtr;
-
- // Selectors
- SEL cStringSEL;
- SEL willQueryStringSEL;
- SEL timeConnectedSEL;
-}
-
-// Readonly properties
-@property (readonly) double lastQueryExecutionTime;
-
-// Read/write properties
-@property (readwrite, assign) BOOL useKeepAlive;
-@property (readwrite, assign) BOOL delegateQueryLogging;
-@property (readwrite, assign) NSInteger connectionTimeout;
-@property (readwrite, assign) CGFloat keepAliveInterval;
-
-// Initialisation
-- (id)initToHost:(NSString *)host withLogin:(NSString *)login usingPort:(NSUInteger)port;
-- (id)initToSocket:(NSString *)socket withLogin:(NSString *)login;
-
-// Delegate
-- (id)delegate;
-- (void)setDelegate:(id)connectionDelegate;
-- (MCPConnectionCheck)delegateDecisionForLostConnection;
-
-// Connection details
-- (BOOL)setPort:(NSUInteger)thePort;
-- (BOOL)setPassword:(NSString *)thePassword;
-- (void) setSSL:(BOOL)shouldUseSSL usingKeyFilePath:(NSString *)keyFilePath certificatePath:(NSString *)certificatePath certificateAuthorityCertificatePath:(NSString *)caCertificatePath;
-
-// Proxy
-- (BOOL)setConnectionProxy:(id <MCPConnectionProxy>)proxy;
-- (void)connectionProxyStateChange:(id <MCPConnectionProxy>)proxy;
-
-// Connection
-- (BOOL)connect;
-- (void)disconnect;
-- (BOOL)reconnect;
-- (BOOL)isConnected;
-- (BOOL)isConnectedViaSSL;
-- (BOOL)userTriggeredDisconnect;
-- (BOOL)checkConnection;
-- (void)restoreConnectionDetails;
-- (void)setAllowQueryRetries:(BOOL)allow;
-- (double)timeConnected;
-
-// Pinging and keepalive
-- (BOOL)pingConnectionUsingLoopDelay:(NSUInteger)loopDelay;
-void backgroundPingTask(void *ptr);
-void forceThreadExit(int signalNumber);
-void pingThreadCleanup(void *pingDetails);
-- (void)keepAlive:(NSTimer *)theTimer;
-- (void)threadedKeepAlive;
-
-// Server versions
-- (NSString *)serverVersionString;
-- (NSInteger)serverMajorVersion;
-- (NSInteger)serverMinorVersion;
-- (NSInteger)serverReleaseVersion;
-
-// MySQL defaults
-+ (NSDictionary *)getMySQLLocales;
-+ (NSStringEncoding)encodingForMySQLEncoding:(const char *)mysqlEncoding;
-+ (NSString *) mySQLEncodingForStringEncoding:(NSStringEncoding)stringEncoding;
-+ (NSStringEncoding)defaultMySQLEncoding;
-+ (BOOL)isErrorNumberConnectionError:(NSInteger)theErrorNumber;
-
-// Class maintenance
-+ (void)setTruncateLongFieldInLogs:(BOOL)iTruncFlag;
-+ (BOOL)truncateLongField;
-- (BOOL)setConnectionOption:(NSInteger)option toValue:(BOOL)value;
-- (BOOL)connectWithLogin:(NSString *)login password:(NSString *)pass host:(NSString *)host port:(NSUInteger)port socket:(NSString *)socket;
-
-- (BOOL)selectDB:(NSString *)dbName;
-
-// Error information
-- (BOOL)queryErrored;
-- (NSString *)getLastErrorMessage;
-- (void)setLastErrorMessage:(NSString *)theErrorMessage;
-- (NSUInteger)getLastErrorID;
-+ (BOOL)isErrorNumberConnectionError:(NSInteger)theErrorNumber;
-- (void)updateErrorStatuses;
-
-// Queries
-- (NSString *)prepareBinaryData:(NSData *)theData;
-- (NSString *)prepareString:(NSString *)theString;
-- (NSString *)quoteObject:(id)theObject;
-- (MCPResult *)queryString:(NSString *)query;
-- (MCPStreamingResult *)streamingQueryString:(NSString *)query;
-- (MCPStreamingResult *)streamingQueryString:(NSString *)query useLowMemoryBlockingStreaming:(BOOL)fullStream;
-- (id)queryString:(NSString *)query usingEncoding:(NSStringEncoding)encoding streamingResult:(NSInteger)streamResult;
-- (my_ulonglong)affectedRows;
-- (my_ulonglong)insertId;
-- (void)cancelCurrentQuery;
-- (BOOL)queryCancelled;
-- (BOOL)queryCancellationUsedReconnect;
-- (void)flushMultiResults;
-
-// Locking
-- (void)lockConnection;
-- (BOOL)tryLockConnection;
-- (void)unlockConnection;
-
-// Database structure
-- (MCPResult *)listDBs;
-- (MCPResult *)listDBsLike:(NSString *)dbsName;
-- (MCPResult *)listTables;
-- (MCPResult *)listTablesLike:(NSString *)tablesName;
-- (NSArray *)listTablesFromDB:(NSString *)dbName;
-- (NSArray *)listTablesFromDB:(NSString *)dbName like:(NSString *)tablesName;
-- (MCPResult *)listFieldsFromTable:(NSString *)tableName;
-- (MCPResult *)listFieldsFromTable:(NSString *)tableName like:(NSString *)fieldsName;
-
-// Structure querying
-- (void)queryDbStructureWithUserInfo:(NSDictionary*)userInfo;
-- (NSDictionary *)getDbStructure;
-- (NSArray *)getAllKeysOfDbStructure;
-- (BOOL)isQueryingDatabaseStructure;
-- (void)incrementQueryingDbStructure;
-- (void)decrementQueryingDbStructure;
-- (void)lockQuerying;
-- (void)unlockQuerying;
-- (void)updateGlobalVariablesWith:(NSDictionary*)object;
-
-// Server information
-- (NSString *)clientInfo;
-- (NSString *)hostInfo;
-- (NSString *)serverInfo;
-- (NSNumber *)protoInfo;
-- (MCPResult *)listProcesses;
-- (BOOL)killProcess:(unsigned long)pid;
-- (NSString *)findSocketPath;
-
-// Encoding
-- (BOOL)setEncoding:(NSString *)theEncoding;
-- (NSString *)encoding;
-- (NSStringEncoding)stringEncoding;
-- (BOOL)setEncodingUsesLatin1Transport:(BOOL)useLatin1;
-- (BOOL)encodingUsesLatin1Transport;
-- (void)storeEncodingForRestoration;
-- (void)restoreStoredEncoding;
-
-// Time zone
-- (void)setTimeZone:(NSTimeZone *)iTimeZone;
-- (NSTimeZone *)timeZone;
-
-// Packet size
-- (BOOL)fetchMaxAllowedPacket;
-- (NSUInteger)getMaxAllowedPacket;
-- (BOOL)isMaxAllowedPacketEditable;
-- (NSUInteger)setMaxAllowedPacketTo:(NSUInteger)newSize resetSize:(BOOL)reset;
-
-// Data conversion
-- (const char *)cStringFromString:(NSString *)theString;
-- (const char *)cStringFromString:(NSString *)theString usingEncoding:(NSStringEncoding)encoding;
-- (NSString *)stringWithCString:(const char *)theCString;
-- (NSString *)stringWithCString:(const char *)theCString usingEncoding:(NSStringEncoding)encoding;
-- (NSString *)stringWithText:(NSData *)theTextData;
-- (NSString *)stringWithUTF8CString:(const char *)theCString;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPConnection.m b/Frameworks/MCPKit/MCPFoundationKit/MCPConnection.m
deleted file mode 100644
index 04dcf50d..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPConnection.m
+++ /dev/null
@@ -1,3402 +0,0 @@
-//
-// $Id$
-//
-// MCPConnection.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 08/12/2001.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPConnection.h"
-#import "MCPResult.h"
-#import "MCPNumber.h"
-#import "MCPNull.h"
-#import "MCPStreamingResult.h"
-#import "MCPConnectionProxy.h"
-#import "MCPConnectionDelegate.h"
-#import "MCPStringAdditions.h"
-#import "RegexKitLite.h" // TODO: Remove along with queryDbStructureWithUserInfo
-#import "NSNotificationAdditions.h"
-
-#include <unistd.h>
-#include <mach/mach_time.h>
-#include <SystemConfiguration/SystemConfiguration.h>
-
-const NSUInteger kMCPConnectionDefaultOption = CLIENT_COMPRESS | CLIENT_REMEMBER_OPTIONS | CLIENT_MULTI_RESULTS | CLIENT_INTERACTIVE;
-const char *kMCPConnectionDefaultSocket = MYSQL_UNIX_ADDR;
-const char *kMCPSSLCipherList = "DHE-RSA-AES256-SHA:AES256-SHA:DHE-RSA-AES128-SHA:AES128-SHA:AES256-RMD:AES128-RMD:DES-CBC3-RMD:DHE-RSA-AES256-RMD:DHE-RSA-AES128-RMD:DHE-RSA-DES-CBC3-RMD:RC4-SHA:RC4-MD5:DES-CBC3-SHA:DES-CBC-SHA:EDH-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC-SHA";
-const NSUInteger kMCPConnection_Not_Inited = 1000;
-const NSUInteger kLengthOfTruncationForLog = 100;
-
-static BOOL sTruncateLongFieldInLogs = YES;
-
-/**
- * Privte API
- */
-@interface MCPConnection (PrivateAPI)
-
-- (void)_updateConnectionVariables;
-- (BOOL)_isCurrentHostReachable;
-- (void)_setupKeepalivePingTimer;
-
-@end
-
-/**
- * Note that these aren't actually delegate methods, but are defined because queryDbStructureWithUserInfo needs
- * them. We define them here to supress compiler warnings.
- *
- * TODO: Remove along with queryDbStructureWithUserInfo
- */
-@interface MCPConnection (MCPConnectionDelegate)
-
-- (NSString *)database;
-- (NSString *)connectionID;
-
-- (NSArray *)allDatabaseNames;
-- (NSArray *)allSystemDatabaseNames;
-- (NSArray *)allTableNames;
-- (NSArray *)allViewNames;
-- (NSArray *)allSchemaKeys;
-
-@end
-
-@implementation MCPConnection
-
-// Synthesize ivars
-@synthesize useKeepAlive;
-@synthesize delegateQueryLogging;
-@synthesize connectionTimeout;
-@synthesize keepAliveInterval;
-@synthesize lastQueryExecutionTime;
-
-#pragma mark -
-#pragma mark Initialisation
-
-/**
- * Initialise a MySQLConnection without making a connection, most likely useless, except with !{setConnectionOption:withArgument:}.
- *
- * Because this method is not making a connection to any MySQL server, it can not know already what the DB server encoding will be,
- * hence the encoding is set to some default (at present this is NSISOLatin1StringEncoding). Obviously this is reset to a proper
- * value as soon as a DB connection is performed.
- */
-- (id)init
-{
- if ((self = [super init])) {
- mConnection = mysql_init(NULL);
- mConnected = NO;
-
- if (mConnection == NULL) {
- [self autorelease];
-
- return nil;
- }
-
- encoding = [[NSString alloc] initWithString:@"utf8"];
- previousEncoding = nil;
- stringEncoding = NSUTF8StringEncoding;
- encodingUsesLatin1Transport = NO;
- previousEncodingUsesLatin1Transport = NO;
- mConnectionFlags = kMCPConnectionDefaultOption;
-
- // Anything that performs a mysql_net_read is not thread-safe: mysql queries, pings
- // Always lock the connection first. Don't use this lock directly, use the lockConnection method!
- connectionLock = [[NSConditionLock alloc] initWithCondition:MCPConnectionIdle];
- [connectionLock setName:@"MCPConnection connectionLock"];
-
- connectionHost = nil;
- connectionLogin = nil;
- connectionSocket = nil;
- connectionPassword = nil;
- useSSL = NO;
- sslKeyFilePath = nil;
- sslCertificatePath = nil;
- sslCACertificatePath = nil;
- lastKeepAliveTime = 0;
- pingThread = NULL;
- connectionProxy = nil;
- connectionStartTime = 0;
- lastQueryExecutedAtTime = CGFLOAT_MAX;
- lastDelegateDecisionForLostConnection = NSNotFound;
- queryCancelled = NO;
- queryCancelUsedReconnect = NO;
- serverVersionString = nil;
- mTimeZone = nil;
- isDisconnecting = NO;
- isReconnecting = NO;
- userTriggeredDisconnect = NO;
- automaticReconnectAttempts = 0;
- lastPingSuccess = NO;
- lastPingBlocked = NO;
- pingThreadActive = NO;
- pingFailureCount = 0;
-
- // Initialize ivar defaults
- connectionTimeout = 10;
- useKeepAlive = YES;
- keepAliveInterval = 60;
-
- structure = [[NSMutableDictionary alloc] initWithCapacity:1];
- allKeysofDbStructure = [[NSMutableArray alloc] initWithCapacity:20];
- isQueryingDbStructure = 0;
- lockQuerying = NO;
-
- connectionThreadId = 0;
- maxAllowedPacketSize = 1048576;
- lastQueryExecutionTime = 0;
- lastQueryErrorId = 0;
- lastQueryErrorMessage = nil;
- lastQueryAffectedRows = 0;
- lastPingSuccess = NO;
- delegate = nil;
- delegateSupportsConnectionLostDecisions = NO;
- delegateResponseToWillQueryString = NO;
-
- // Enable delegate query logging by default
- delegateQueryLogging = YES;
-
- // Default to allowing queries to be reattempted if they fail due to connection issues
- retryAllowed = YES;
-
- // Obtain SEL references
- willQueryStringSEL = @selector(willQueryString:connection:);
- cStringSEL = @selector(cStringFromString:);
-
- // Obtain pointers
- cStringPtr = [self methodForSelector:cStringSEL];
-
- // Start the keepalive timer
- if ([NSThread isMainThread])
- [self _setupKeepalivePingTimer];
- else
- [self performSelectorOnMainThread:@selector(_setupKeepalivePingTimer) withObject:nil waitUntilDone:YES];
- }
-
- return self;
-}
-
-/**
- * Inialize connection using the supplied host details.
- */
-- (id)initToHost:(NSString *)host withLogin:(NSString *)login usingPort:(NSUInteger)port
-{
- if ((self = [self init])) {
- if (!host) host = @"";
- if (!login) login = @"";
-
- connectionHost = [[NSString alloc] initWithString:host];
- connectionLogin = [[NSString alloc] initWithString:login];
- connectionPort = port;
- connectionSocket = nil;
- }
-
- return self;
-}
-
-/**
- * Inialize connection using the supplied socket details.
- */
-- (id)initToSocket:(NSString *)aSocket withLogin:(NSString *)login
-{
- if ((self = [self init])) {
- if (!aSocket || ![aSocket length]) {
- aSocket = [self findSocketPath];
- if (!aSocket) aSocket = @"";
- }
-
- if (!login) login = @"";
-
- connectionHost = nil;
- connectionLogin = [[NSString alloc] initWithString:login];
- connectionSocket = [[NSString alloc] initWithString:aSocket];
- connectionPort = 0;
- }
-
- return self;
-}
-
-#pragma mark -
-#pragma mark Delegate
-
-/**
- * Get the connection's current delegate.
- */
-- (id)delegate
-{
- return delegate;
-}
-
-/**
- * Set the connection's delegate to the supplied object.
- */
-- (void)setDelegate:(id)connectionDelegate
-{
- delegate = connectionDelegate;
-
- // Check that the delegate implements willQueryString:connection: and cache the result as its used very frequently.
- delegateResponseToWillQueryString = [delegate respondsToSelector:@selector(willQueryString:connection:)];
-
- // Check whether the delegate supports returning a connection lost action decision
- delegateSupportsConnectionLostDecisions = [delegate respondsToSelector:@selector(connectionLost:)];
-}
-
-/**
- * Ask the delegate for the connection lost decision. This can be called from
- * any thread, and will call itself on the main thread if necessary, updating a global
- * variable which is then returned on the child thread.
- */
-- (MCPConnectionCheck)delegateDecisionForLostConnection
-{
-
- // Return the "Disconnect" decision if the delegate doesn't support connectionLost: checks
- if (!delegateSupportsConnectionLostDecisions) return MCPConnectionCheckDisconnect;
-
- lastDelegateDecisionForLostConnection = NSNotFound;
-
- // If on the main thread, ask the delegate directly.
- // This is wrapped in a NSLock to ensure variables are completely committed for
- // thread-safe access, even though the lock is constrained to this code block.
- if ([NSThread isMainThread]) {
- NSLock *delegateDecisionLock = [[NSLock alloc] init];
- [delegateDecisionLock lock];
- lastDelegateDecisionForLostConnection = [delegate connectionLost:self];
- [delegateDecisionLock unlock];
- [delegateDecisionLock release];
-
- // Otherwise call ourself on the main thread, waiting until the reply is received.
- } else {
-
- // First check whether the application is in a modal state; if so, wait
- while ([NSApp modalWindow]) usleep(100000);
-
- [self performSelectorOnMainThread:@selector(delegateDecisionForLostConnection) withObject:nil waitUntilDone:YES];
- }
-
- return lastDelegateDecisionForLostConnection;
-}
-
-#pragma mark -
-#pragma mark Connection details
-
-/**
- * Sets or updates the connection port - for use with tunnels.
- */
-- (BOOL)setPort:(NSUInteger)thePort
-{
- connectionPort = thePort;
-
- return YES;
-}
-
-/**
- * Sets the password to be stored locally.
- * Providing a keychain name is much more secure.
- */
-- (BOOL)setPassword:(NSString *)thePassword
-{
- if (connectionPassword) [connectionPassword release], connectionPassword = nil;
-
- if (!thePassword) thePassword = @"";
-
- connectionPassword = [[NSString alloc] initWithString:thePassword];
-
- return YES;
-}
-
-/**
- * Set the connection to establish secure connections using SSL; must be
- * called before connect:.
- * This will always attempt to activate SSL if set, but depending on server
- * setup connection may sometimes proceed without SSL enabled even if requested;
- * it is suggested that after connection, -[MCPConnection isConnectedViaSSL]
- * is checked to determine whether SSL is actually active.
- */
-- (void) setSSL:(BOOL)shouldUseSSL usingKeyFilePath:(NSString *)keyFilePath certificatePath:(NSString *)certificatePath certificateAuthorityCertificatePath:(NSString *)caCertificatePath
-{
- useSSL = shouldUseSSL;
-
- // Reset the old SSL details
- if (sslKeyFilePath) [sslKeyFilePath release], sslKeyFilePath = nil;
- if (sslCertificatePath) [sslCertificatePath release], sslCertificatePath = nil;
- if (sslCACertificatePath) [sslCACertificatePath release], sslCACertificatePath = nil;
-
- // Set new details if provided
- if (keyFilePath) sslKeyFilePath = [[NSString alloc] initWithString:[keyFilePath stringByExpandingTildeInPath]];
- if (certificatePath) sslCertificatePath = [[NSString alloc] initWithString:[certificatePath stringByExpandingTildeInPath]];
- if (caCertificatePath) sslCACertificatePath = [[NSString alloc] initWithString:[caCertificatePath stringByExpandingTildeInPath]];
-}
-
-#pragma mark -
-#pragma mark Connection proxy
-
-/*
- * Set a connection proxy object to connect through. This object will be retained locally,
- * and will be automatically connected/connection checked/reconnected/disconnected
- * together with the main connection.
- */
-- (BOOL)setConnectionProxy:(id <MCPConnectionProxy>)proxy
-{
- connectionProxy = proxy;
- [connectionProxy retain];
-
- currentProxyState = [connectionProxy state];
- [connectionProxy setConnectionStateChangeSelector:@selector(connectionProxyStateChange:) delegate:self];
-
- return YES;
-}
-
-/**
- * Handle any state changes in the associated connection proxy.
- */
-- (void)connectionProxyStateChange:(id <MCPConnectionProxy>)proxy
-{
- NSInteger newState = [proxy state];
-
- // Restart the tunnel if it dies - use a new thread to allow the main thread to process
- // events as required.
- if (mConnected && newState == PROXY_STATE_IDLE && currentProxyState == PROXY_STATE_CONNECTED) {
- currentProxyState = newState;
- [connectionProxy setConnectionStateChangeSelector:nil delegate:nil];
-
- // Trigger a reconnect
- if (!isDisconnecting) [NSThread detachNewThreadSelector:@selector(reconnect) toTarget:self withObject:nil];
-
- return;
- }
-
- currentProxyState = newState;
-}
-
-#pragma mark -
-#pragma mark Connection
-
-/**
- * Add a new connection method, intended for use with the init methods above.
- * Uses the stored details to instantiate a connection to the specified server,
- * including custom timeouts - used for pings, not for long-running commands.
- */
-- (BOOL)connect
-{
- const char *theLogin = [self cStringFromString:connectionLogin];
- const char *theHost;
- const char *thePass = NULL;
- const char *theSocket;
- void *theRet;
-
- // Disconnect if a connection is already active
- if (mConnected) {
- [self disconnect];
- mConnection = mysql_init(NULL);
- if (mConnection == NULL) return NO;
- }
-
- [self lockConnection];
-
- if (mConnection != NULL) {
-
- // Ensure the custom timeout option is set
- mysql_options(mConnection, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&connectionTimeout);
-
- // ensure that automatic reconnection is explicitly disabled - now handled manually.
- my_bool falseBool = FALSE;
- mysql_options(mConnection, MYSQL_OPT_RECONNECT, &falseBool);
-
- // Set the connection encoding to utf8
- mysql_options(mConnection, MYSQL_SET_CHARSET_NAME, [encoding UTF8String]);
- }
-
- // Set the host as appropriate
- if (!connectionHost || ![connectionHost length]) {
- theHost = NULL;
- } else {
- theHost = [self cStringFromString:connectionHost];
- }
-
- // Use the default socket if none is set, or set appropriately
- if (connectionSocket == nil || ![connectionSocket length]) {
- theSocket = kMCPConnectionDefaultSocket;
- } else {
- theSocket = [self cStringFromString:connectionSocket];
- }
-
- // Apply SSL if appropriate
- if (useSSL) {
- mysql_ssl_set(mConnection,
- sslKeyFilePath ? [sslKeyFilePath UTF8String] : NULL,
- sslCertificatePath ? [sslCertificatePath UTF8String] : NULL,
- sslCACertificatePath ? [sslCACertificatePath UTF8String] : NULL,
- NULL,
- kMCPSSLCipherList);
- }
-
- // Select the password from the provided method
- if (!connectionPassword) {
- if (delegate && [delegate respondsToSelector:@selector(keychainPasswordForConnection:)]) {
- thePass = [self cStringFromString:[delegate keychainPasswordForConnection:self]];
- }
- } else {
- thePass = [self cStringFromString:connectionPassword];
- }
-
- // Connect
- theRet = mysql_real_connect(mConnection, theHost, theLogin, thePass, NULL, (unsigned int)connectionPort, theSocket, mConnectionFlags);
- thePass = NULL;
-
- // If the connection failed, record the error state and return
- if (theRet != mConnection) {
- [self unlockConnection];
- [self setLastErrorMessage:nil];
-
- lastQueryErrorId = mysql_errno(mConnection);
-
- return mConnected = NO;
- }
-
- // Set and reset connection flags
- mConnected = YES;
- userTriggeredDisconnect = NO;
- connectionStartTime = mach_absolute_time();
- lastKeepAliveTime = 0;
- automaticReconnectAttempts = 0;
- pingFailureCount = 0;
- connectionThreadId = mConnection->thread_id;
- [self setLastErrorMessage:nil];
-
- [self unlockConnection];
-
- // Update connection variables - server version, time zone, and connection encoding
- [self _updateConnectionVariables];
-
- // Only attempt to set the max allowed packet if we have a connection
- // The fetches may fail, in which case the class default (which should match
- // the MySQL default) will be used.
- if (mConnection != NULL) {
- isMaxAllowedPacketEditable = [self isMaxAllowedPacketEditable];
- [self fetchMaxAllowedPacket];
- }
- else {
- mConnected = NO;
- isMaxAllowedPacketEditable = NO;
- }
-
- return mConnected;
-}
-
-/**
- * Disconnect the current connection.
- */
-- (void)disconnect
-{
- if (isDisconnecting) return;
- isDisconnecting = YES;
-
- if (mConnected) {
- [self cancelCurrentQuery];
- mConnected = NO;
-
- // Allow any pings or query cleanups to complete - within a time limit.
- uint64_t startTime_t, currentTime_t;
- Nanoseconds elapsedNanoseconds;
- startTime_t = mach_absolute_time();
- do {
- usleep(100000);
-
- currentTime_t = mach_absolute_time() - startTime_t ;
- elapsedNanoseconds = AbsoluteToNanoseconds(*(AbsoluteTime *)&(currentTime_t));
- if (((double)UnsignedWideToUInt64(elapsedNanoseconds)) * 1e-9 > 10) break;
- } while (![self tryLockConnection]);
- [self unlockConnection];
-
- // Only close the connection if it appears to still be active, and not reading or
- // writing. This may result in a leak, but minimises crashes.
- if (!mConnection->net.reading_or_writing && mConnection->net.vio && mConnection->net.buff) mysql_close(mConnection);
- mConnection = NULL;
- }
-
- isDisconnecting = NO;
-
- if (connectionProxy) {
- [connectionProxy performSelectorOnMainThread:@selector(disconnect) withObject:nil waitUntilDone:YES];
- }
-
- if (serverVersionString) [serverVersionString release], serverVersionString = nil;
- if (structure) [structure release], structure = nil;
- if (allKeysofDbStructure) [allKeysofDbStructure release], allKeysofDbStructure = nil;
- if (pingThread != NULL) pthread_cancel(pingThread), pingThread = NULL;
-}
-
-/**
- * Reconnect to the currently "active" - but possibly disconnected - connection, using the
- * stored details.
- * Error checks extensively - if this method fails, it will ask how to proceed and loop depending
- * on the status, not returning control until either a connection has been established or
- * the connection and document have been closed.
- * Runs its own autorelease pool as sometimes called in a thread following proxy changes
- * (where the return code doesn't matter).
- */
-- (BOOL)reconnect
-{
- NSAutoreleasePool *reconnectionPool = [[NSAutoreleasePool alloc] init];
- NSString *currentEncoding = [NSString stringWithString:encoding];
- BOOL currentEncodingUsesLatin1Transport = encodingUsesLatin1Transport;
- NSString *currentDatabase = nil;
-
- // Check whether a reconnection attempt is already being made - if so, wait and return the status of that reconnection attempt.
- if (isReconnecting) {
- NSDate *eventLoopStartDate;
- while (isReconnecting) {
- eventLoopStartDate = [NSDate date];
- [[NSRunLoop currentRunLoop] runMode:NSModalPanelRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
- if ([[NSDate date] timeIntervalSinceDate:eventLoopStartDate] < 0.1) {
- usleep((useconds_t)(100000 - (1000000 * [[NSDate date] timeIntervalSinceDate:eventLoopStartDate])));
- }
- }
- [reconnectionPool drain];
- return mConnected;
- }
-
- isReconnecting = YES;
-
- // Store the currently selected database so it can be re-set if reconnection was successful
- if (delegate && [delegate respondsToSelector:@selector(onReconnectShouldSelectDatabase:)] && [delegate onReconnectShouldSelectDatabase:self]) {
- currentDatabase = [NSString stringWithString:[delegate onReconnectShouldSelectDatabase:self]];
- }
-
- // Close the connection if it exists.
- if (mConnected) {
- mConnected = NO;
-
- // Allow any pings or query cleanups to complete - within a time limit.
- uint64_t startTime_t, currentTime_t;
- Nanoseconds elapsedNanoseconds;
- startTime_t = mach_absolute_time();
- do {
- usleep(100000);
-
- currentTime_t = mach_absolute_time() - startTime_t ;
- elapsedNanoseconds = AbsoluteToNanoseconds(*(AbsoluteTime *)&(currentTime_t));
- if (((double)UnsignedWideToUInt64(elapsedNanoseconds)) * 1e-9 > 10) break;
- } while (![self tryLockConnection]);
- [self unlockConnection];
-
- // Only close the connection if it's not reading or writing - this may result
- // in leaks, but minimises crashes.
- if (!mConnection->net.reading_or_writing) mysql_close(mConnection);
- mConnection = NULL;
- }
-
- isDisconnecting = NO;
- [self lockConnection];
-
- // If no network is present, loop for a short period waiting for one to become available
- uint64_t elapsedTime_t, networkWaitStartTime_t = mach_absolute_time();
- Nanoseconds elapsedTime;
- while (![self _isCurrentHostReachable]) {
- elapsedTime_t = mach_absolute_time() - networkWaitStartTime_t;
- elapsedTime = AbsoluteToNanoseconds(*(AbsoluteTime *)&(elapsedTime_t));
- if (((double)UnsignedWideToUInt64(elapsedTime)) * 1e-9 > 5) break;
- usleep(250000);
- }
-
- // If there is a proxy, ensure it's disconnected and attempt to reconnect it in blocking fashion
- if (connectionProxy) {
- [connectionProxy setConnectionStateChangeSelector:nil delegate:nil];
- if ([connectionProxy state] != PROXY_STATE_IDLE) [connectionProxy disconnect];
-
- // Loop until the proxy has disconnected or the connection timeout has passed
- NSDate *proxyDisconnectStartDate = [NSDate date], *eventLoopStartDate;
- while ([connectionProxy state] != PROXY_STATE_IDLE
- && [[NSDate date] timeIntervalSinceDate:proxyDisconnectStartDate] < connectionTimeout)
- {
- eventLoopStartDate = [NSDate date];
- [[NSRunLoop currentRunLoop] runMode:NSModalPanelRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.25]];
- if ([[NSDate date] timeIntervalSinceDate:eventLoopStartDate] < 0.25) {
- usleep((useconds_t)(250000 - (1000000 * [[NSDate date] timeIntervalSinceDate:eventLoopStartDate])));
- }
- }
-
- // Reconnect the proxy, looping up to the connection timeout
- [connectionProxy connect];
-
- NSDate *proxyStartDate = [NSDate date], *interfaceInteractionTimer;
- while (1) {
-
- // If the proxy has connected, break out of the loop
- if ([connectionProxy state] == PROXY_STATE_CONNECTED) {
- connectionPort = [connectionProxy localPort];
- break;
- }
-
- // If the proxy connection attempt time has exceeded the timeout, abort.
- if ([[NSDate date] timeIntervalSinceDate:proxyStartDate] > (connectionTimeout + 1)) {
- [connectionProxy disconnect];
- break;
- }
-
- // Process events for a short time, allowing dialogs to be shown but waiting for
- // the proxy. Capture how long this interface action took, standardising the
- // overall time and extending the connection timeout by any interface time.
- interfaceInteractionTimer = [NSDate date];
- [[NSRunLoop mainRunLoop] runMode:NSModalPanelRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.25]];
- //[[NSRunLoop currentRunLoop] runMode:NSModalPanelRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.25]];
- if ([[NSDate date] timeIntervalSinceDate:interfaceInteractionTimer] < 0.25) {
- usleep((useconds_t)(250000 - (1000000 * [[NSDate date] timeIntervalSinceDate:interfaceInteractionTimer])));
- }
- if ([connectionProxy state] == PROXY_STATE_WAITING_FOR_AUTH) {
- proxyStartDate = [proxyStartDate addTimeInterval:[[NSDate date] timeIntervalSinceDate:interfaceInteractionTimer]];
- }
- }
-
- currentProxyState = [connectionProxy state];
- [connectionProxy setConnectionStateChangeSelector:@selector(connectionProxyStateChange:) delegate:self];
- }
-
- [self unlockConnection];
- if (!connectionProxy || [connectionProxy state] == PROXY_STATE_CONNECTED) {
-
- // Attempt to reinitialise the connection - if this fails, it will still be set to NULL.
- if (mConnection == NULL) {
- mConnection = mysql_init(NULL);
- }
-
- if (mConnection != NULL) {
-
- // Attempt to reestablish the connection
- [self connect];
- }
- }
-
- // If the connection was successfully established, reselect the old database and encoding if appropriate.
- if (mConnected) {
- if (currentDatabase) {
- [self selectDB:currentDatabase];
- }
-
- if (currentEncoding) {
- [self setEncoding:currentEncoding];
- [self setEncodingUsesLatin1Transport:currentEncodingUsesLatin1Transport];
- }
- }
- else {
- [self setLastErrorMessage:nil];
-
- // Default to retry
- MCPConnectionCheck failureDecision = MCPConnectionCheckReconnect;
-
- // Ask delegate what to do
- if (delegateSupportsConnectionLostDecisions) {
- failureDecision = [self delegateDecisionForLostConnection];
- }
-
- switch (failureDecision) {
- case MCPConnectionCheckDisconnect:
- [self setLastErrorMessage:NSLocalizedString(@"User triggered disconnection", @"User triggered disconnection")];
- userTriggeredDisconnect = YES;
- [reconnectionPool release];
- isReconnecting = NO;
- return NO;
- default:
- [reconnectionPool release];
- isReconnecting = NO;
- return [self reconnect];
- }
- }
-
- [reconnectionPool release];
- isReconnecting = NO;
- return mConnected;
-}
-
-/**
- * Returns YES if the MCPConnection is connected to a DB, NO otherwise.
- */
-- (BOOL)isConnected
-{
- return mConnected;
-}
-
-/**
- * Returns YES if the MCPConnection is connected to a server via SSL, NO otherwise.
- */
-- (BOOL)isConnectedViaSSL
-{
- if (![self isConnected]) return NO;
- return (mysql_get_ssl_cipher(mConnection))?YES:NO;
-}
-
-/**
- * Returns YES if the user chose to disconnect at the last "connection failure"
- * prompt, NO otherwise.
- */
-- (BOOL)userTriggeredDisconnect
-{
- return userTriggeredDisconnect;
-}
-
-/**
- * Checks if the connection to the server is still on.
- * If not, tries to reconnect (changing no parameters from the MYSQL pointer).
- * This method just uses mysql_ping().
- */
-- (BOOL)checkConnection
-{
- if (!mConnected) return NO;
-
- BOOL connectionVerified = FALSE;
-
- // If the connection is currently locked, it's probably in use - no need to check
- // the connection.
- if ([connectionLock condition] == MCPConnectionBusy) {
-
- // However if a ping thread is active, might be a background ping - wait for it
- // to complete, then check the connection.
- if (pingThreadActive) {
- while (pingThreadActive) {
- usleep(10000);
- }
- return [self checkConnection];
- }
-
- return YES;
- }
-
- // Check whether the connection is still operational via a wrapped version of MySQL ping.
- connectionVerified = [self pingConnectionUsingLoopDelay:400];
-
- // If the connection doesn't appear to be responding, and we can still attempt an automatic
- // reconnect (only once each connection - eg an automatic reconnect failure prevents loops,
- // but an automatic reconnect success resets the flag for another attempt in future)
- if (!connectionVerified && automaticReconnectAttempts < 1) {
- automaticReconnectAttempts++;
-
- // Note that a return of "NO" here has already asked the user, so if reconnect fails,
- // return failure.
- if ([self reconnect]) {
- return YES;
- }
- return NO;
- }
-
- // If automatic reconnect cannot be used, show a dialog asking how to proceed
- if (!connectionVerified) {
-
- // Ask delegate what to do, defaulting to "disconnect".
- MCPConnectionCheck failureDecision = MCPConnectionCheckDisconnect;
- if (delegateSupportsConnectionLostDecisions) {
- failureDecision = [self delegateDecisionForLostConnection];
- }
-
- switch (failureDecision) {
-
- // 'Reconnect' has been selected. Request a reconnect, and retry.
- case MCPConnectionCheckReconnect:
- [self reconnect];
-
- return [self checkConnection];
-
- // 'Disconnect' has been selected. The parent window should already have
- // triggered UI-specific actions, and may have disconnected already; if
- // not, disconnect, and clean up.
- case MCPConnectionCheckDisconnect:
- if (mConnected) [self disconnect];
- [self setLastErrorMessage:NSLocalizedString(@"User triggered disconnection", @"User triggered disconnection")];
- userTriggeredDisconnect = YES;
- return NO;
-
- // 'Retry' has been selected - return a recursive call.
- case MCPConnectionCheckRetry:
- return [self checkConnection];
- }
-
- // If a connection exists, check whether the thread id differs; if so, the connection has
- // probably been reestablished and we need to reset the connection encoding
- } else if (connectionThreadId != mConnection->thread_id) [self restoreConnectionDetails];
-
- return connectionVerified;
-}
-
-/**
- * Restore the connection encoding details as necessary based on the delegate-provided
- * details.
- */
-- (void)restoreConnectionDetails
-{
- connectionThreadId = mConnection->thread_id;
- connectionStartTime = mach_absolute_time();
- [self fetchMaxAllowedPacket];
-
- [self setEncoding:encoding];
- [self setEncodingUsesLatin1Transport:encodingUsesLatin1Transport];
-}
-
-/**
- * Allow controlling over whether queries are allowed to retry after a connection failure.
- * This defaults to YES on init, and is intended to allow temporary disabling in situations
- * where the query result is checked and displayed to the user without any repurcussions on
- * failure.
- */
-- (void)setAllowQueryRetries:(BOOL)allow
-{
- retryAllowed = allow;
-}
-
-/**
- * Retrieve the time elapsed since the connection was established, in seconds.
- * This time is retrieved in a monotonically increasing fashion and is high
- * precision; it is used internally for query timing, and is reset on reconnections.
- */
-- (double)timeConnected
-{
- if (connectionStartTime == 0) return -1;
-
- uint64_t currentTime_t = mach_absolute_time() - connectionStartTime;
- Nanoseconds elapsedTime = AbsoluteToNanoseconds(*(AbsoluteTime *)&(currentTime_t));
-
- return (((double)UnsignedWideToUInt64(elapsedTime)) * 1e-9);
-}
-
-#pragma mark -
-#pragma mark Pinging and keepalive
-
-/**
- * This function provides a method of pinging the remote server while also enforcing
- * the specified connection time. This is required because low-level net reads can
- * block indefinitely if the remote server disappears or on network issues - setting
- * the MYSQL_OPT_READ_TIMEOUT (and the WRITE equivalent) would "fix" ping, but cause
- * long queries to be terminated.
- * The supplied loop delay number controls how tight the thread checking loop is, in
- * microseconds, to allow differentiating foreground and background pings.
- * Unlike mysql_ping, this function returns FALSE on failure and TRUE on success.
- */
-- (BOOL)pingConnectionUsingLoopDelay:(NSUInteger)loopDelay
-{
- if (!mConnected) return NO;
-
- uint64_t pingStartTime_t, currentTime_t;
- Nanoseconds elapsedNanoseconds;
- BOOL threadCancelled = NO;
-
- // Set up a query lock
- [self lockConnection];
-
- lastPingSuccess = NO;
- lastPingBlocked = NO;
- pingThreadActive = YES;
-
- // Use a ping timeout defaulting to thirty seconds, but using the connection timeout if set
- NSInteger pingTimeout = 30;
- if (connectionTimeout > 0) pingTimeout = connectionTimeout;
-
- // Set up a struct containing details the ping task will need
- MCPConnectionPingDetails pingDetails;
- pingDetails.mySQLConnection = mConnection;
- pingDetails.lastPingSuccessPointer = &lastPingSuccess;
- pingDetails.pingActivePointer = &pingThreadActive;
-
- // Create a pthread for the ping
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
- pthread_create(&pingThread, &attr, (void *)&backgroundPingTask, &pingDetails);
-
- // Record the ping start time
- pingStartTime_t = mach_absolute_time();
-
- // Loop until the ping completes
- do {
- usleep((useconds_t)loopDelay);
-
- // If the ping timeout has been exceeded, force a timeout; double-check that the
- // thread is still active.
- currentTime_t = mach_absolute_time() - pingStartTime_t ;
- elapsedNanoseconds = AbsoluteToNanoseconds(*(AbsoluteTime *)&(currentTime_t));
- if (((double)UnsignedWideToUInt64(elapsedNanoseconds)) * 1e-9 > pingTimeout && pingThreadActive && !threadCancelled) {
- pthread_cancel(pingThread);
- threadCancelled = YES;
-
- // If the timeout has been exceeded by an additional two seconds, and the thread is
- // still active, kill the thread. This can occur in certain network conditions causing
- // a blocking read.
- } else if (((double)UnsignedWideToUInt64(elapsedNanoseconds)) * 1e-9 > (pingTimeout + 2) && pingThreadActive) {
- pthread_kill(pingThread, SIGUSR1);
- pingThreadActive = NO;
- lastPingBlocked = YES;
- }
- } while (pingThreadActive);
-
- // Clean up
- pingThread = NULL;
- pthread_attr_destroy(&attr);
-
- // Unlock the connection
- [self unlockConnection];
-
- return lastPingSuccess;
-}
-
-/**
- * Actually perform a keepalive ping - intended for use within a pthread.
- */
-void backgroundPingTask(void *ptr)
-{
- MCPConnectionPingDetails *pingDetails = (MCPConnectionPingDetails *)ptr;
-
- // Set up a cleanup routine
- pthread_cleanup_push(pingThreadCleanup, pingDetails);
-
- // Set up a signal handler for SIGUSR1, to handle forced timeouts.
- signal(SIGUSR1, forceThreadExit);
-
- // Perform a ping
- *(pingDetails->lastPingSuccessPointer) = (BOOL)(!mysql_ping(pingDetails->mySQLConnection));
-
- // Call the cleanup routine
- pthread_cleanup_pop(1);
-}
-
-/**
- * Support forcing a thread to exit as a result of a signal.
- */
-void forceThreadExit(int signalNumber)
-{
- pthread_exit(NULL);
-}
-
-void pingThreadCleanup(void *pingDetails)
-{
- MCPConnectionPingDetails *pingDetailsStruct = pingDetails;
- *(pingDetailsStruct->pingActivePointer) = NO;
-}
-
-/**
- * Keeps a connection alive by running a ping.
- * This method is called every ten seconds and spawns a thread which determines
- * whether or not it should perform a ping.
- */
-- (void)keepAlive:(NSTimer *)theTimer
-{
-
- // Do nothing if not connected or if keepalive is disabled
- if (!mConnected || !useKeepAlive) return;
-
- // Check to see whether a ping is required. First, compare the last query
- // and keepalive times against the keepalive interval.
- // Compare against interval-1 to allow default keepalive intervals to repeat
- // at the correct intervals (eg no timer interval delay).
- double timeConnected = [self timeConnected];
- if (timeConnected - lastQueryExecutedAtTime < keepAliveInterval - 1
- || timeConnected - lastKeepAliveTime < keepAliveInterval - 1)
- {
- return;
- }
-
- // Attempt to lock the connection. If the connection is currently busy,
- // we don't need a ping.
- if (![self tryLockConnection]) return;
- [self unlockConnection];
-
- // Store the ping time
- lastKeepAliveTime = timeConnected;
-
- [NSThread detachNewThreadSelector:@selector(threadedKeepAlive) toTarget:self withObject:nil];
-}
-
-/**
- * A threaded keepalive to avoid blocking the interface. Performs safety
- * checks, and then creates a child pthread to actually ping the connection,
- * forcing the thread to close after the timeout if it hasn't closed already.
- */
-- (void)threadedKeepAlive
-{
-
- // If the maximum number of ping failures has been reached, trigger a reconnect
- if (lastPingBlocked || pingFailureCount >= 3) {
- NSAutoreleasePool *connectionPool = [[NSAutoreleasePool alloc] init];
- [self reconnect];
- [connectionPool drain];
- return;
- }
-
- // Otherwise, perform a background ping.
- BOOL pingResult = [self pingConnectionUsingLoopDelay:10000];
- if (pingResult) {
- pingFailureCount = 0;
- } else {
- pingFailureCount++;
- }
-}
-
-#pragma mark -
-#pragma mark Server versions
-
-/**
- * Return the server version string, or nil on failure.
- */
-- (NSString *)serverVersionString
-{
- if (serverVersionString) {
- return [NSString stringWithString:serverVersionString];
- }
-
- return nil;
-}
-
-/**
- * rReturn the server major version or -1 on fail
- */
-- (NSInteger)serverMajorVersion
-{
-
- if (serverVersionString != nil) {
- return [[[serverVersionString componentsSeparatedByString:@"."] objectAtIndex:0] integerValue];
- }
-
- return -1;
-}
-
-/**
- * Return the server minor version or -1 on fail
- */
-- (NSInteger)serverMinorVersion
-{
- if (serverVersionString != nil) {
- return [[[serverVersionString componentsSeparatedByString:@"."] objectAtIndex:1] integerValue];
- }
-
- return -1;
-}
-
-/**
- * Return the server release version or -1 on fail
- */
-- (NSInteger)serverReleaseVersion
-{
- if (serverVersionString != nil) {
- NSString *s = [[serverVersionString componentsSeparatedByString:@"."] objectAtIndex:2];
- return [[[s componentsSeparatedByString:@"-"] objectAtIndex:0] integerValue];
- }
-
- return -1;
-}
-
-#pragma mark -
-#pragma mark MySQL defaults
-
-/**
- * This class is used to keep a connection with a MySQL server, it correspond to the MYSQL structure of the C API, or the database handle of the PERL DBI/DBD interface.
- *
- * You have to start any work on a MySQL server by getting a working MCPConnection object.
- *
- * Most likely you will use this kind of code:
- *
- *
- * MCPConnection *theConnec = [MCPConnection alloc];
- * MCPResult *theRes;
- *
- * theConnec = [theConnec initToHost:@"albert.com" withLogin:@"toto" password:@"albert" usingPort:0];
- * [theConnec selectDB:@"db1"];
- * theRes = [theConnec queryString:@"select * from table1"];
- * ...
- *
- * Failing to properly release your MCPConnection(s) object might cause a MySQL crash!!! (recovered if the server was started using mysqld_safe).
- *
- * Gets a proper Locale dictionary to use formater to parse strings from MySQL.
- * For example strings representing dates should give a proper Locales for use with methods such as NSDate::dateWithNaturalLanguageString: locales:
- */
-+ (NSDictionary *)getMySQLLocales
-{
- NSMutableDictionary *theLocalDict = [NSMutableDictionary dictionaryWithCapacity:12];
-
- [theLocalDict setObject:@"." forKey:@"NSDecimalSeparator"];
-
- return [NSDictionary dictionaryWithDictionary:theLocalDict];
-}
-
-/**
- * Gets a proper NSStringEncoding according to the given MySQL charset.
- */
-+ (NSStringEncoding) encodingForMySQLEncoding:(const char *)mysqlEncoding
-{
- // Unicode encodings:
- if (!strncmp(mysqlEncoding, "utf8", 4)) {
- return NSUTF8StringEncoding;
- }
- if (!strncmp(mysqlEncoding, "ucs2", 4)) {
- return NSUnicodeStringEncoding;
- }
-
- // Roman alphabet encodings:
- if (!strncmp(mysqlEncoding, "ascii", 5)) {
- return NSASCIIStringEncoding;
- }
- if (!strncmp(mysqlEncoding, "latin1", 6)) {
- return NSISOLatin1StringEncoding;
- }
- if (!strncmp(mysqlEncoding, "macroman", 8)) {
- return NSMacOSRomanStringEncoding;
- }
-
- // Roman alphabet with central/east european additions:
- if (!strncmp(mysqlEncoding, "latin2", 6)) {
- return NSISOLatin2StringEncoding;
- }
- if (!strncmp(mysqlEncoding, "cp1250", 6)) {
- return NSWindowsCP1250StringEncoding;
- }
- if (!strncmp(mysqlEncoding, "win1250", 7)) {
- return NSWindowsCP1250StringEncoding;
- }
- if (!strncmp(mysqlEncoding, "cp1257", 6)) {
- return CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsBalticRim);
- }
-
- // Additions for Turkish:
- if (!strncmp(mysqlEncoding, "latin5", 6)) {
- return NSWindowsCP1254StringEncoding;
- }
-
- // Greek:
- if (!strncmp(mysqlEncoding, "greek", 5)) {
- return NSWindowsCP1253StringEncoding;
- }
-
- // Cyrillic:
- if (!strncmp(mysqlEncoding, "win1251ukr", 6)) {
- return NSWindowsCP1251StringEncoding;
- }
- if (!strncmp(mysqlEncoding, "cp1251", 6)) {
- return NSWindowsCP1251StringEncoding;
- }
- if (!strncmp(mysqlEncoding, "koi8_ru", 6)) {
- return CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingKOI8_R);
- }
- if (!strncmp(mysqlEncoding, "koi8_ukr", 6)) {
- return CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingKOI8_R);
- }
-
- // Arabic:
- if (!strncmp(mysqlEncoding, "cp1256", 6)) {
- return CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsArabic);
- }
-
- // Hebrew:
- if (!strncmp(mysqlEncoding, "hebrew", 6)) {
- CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatinHebrew);
- }
-
- // Asian:
- if (!strncmp(mysqlEncoding, "ujis", 4)) {
- return NSJapaneseEUCStringEncoding;
- }
- if (!strncmp(mysqlEncoding, "sjis", 4)) {
- return NSShiftJISStringEncoding;
- }
- if (!strncmp(mysqlEncoding, "big5", 4)) {
- return CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingBig5);
- }
- if (!strncmp(mysqlEncoding, "euc_kr", 6)) {
- return CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingEUC_KR);
- }
- if (!strncmp(mysqlEncoding, "euckr", 5)) {
- return CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingEUC_KR);
- }
-
- // Default to iso latin 1, even if it is not exact (throw an exception?)
- NSLog(@"WARNING: unknown name for MySQL encoding '%s'!\n\t\tFalling back to iso-latin1.", mysqlEncoding);
-
- return NSISOLatin1StringEncoding;
-}
-
-/**
- * Gets a MySQL charset for the given NSStringEncoding.
- * If the NSStringEncoding was not matched, nil is returned.
- */
-+ (NSString *) mySQLEncodingForStringEncoding:(NSStringEncoding)stringEncoding
-{
- switch (stringEncoding) {
-
- // Unicode encodings:
- case NSUTF8StringEncoding:
- return @"utf8";
- case NSUnicodeStringEncoding:
- return @"ucs2";
-
- // Roman alphabet encodings:
- case NSASCIIStringEncoding:
- return @"ascii";
- case NSISOLatin1StringEncoding:
- case NSWindowsCP1252StringEncoding:
- return @"latin1";
- case NSMacOSRomanStringEncoding:
- return @"macroman";
-
- // Roman alphabet with central/east european additions:
- case NSISOLatin2StringEncoding:
- return @"latin2";
- case NSWindowsCP1250StringEncoding:
- return @"cp1250";
-
- // Turkish
- case NSWindowsCP1254StringEncoding:
- return @"latin5";
-
- // Greek:
- case NSWindowsCP1253StringEncoding:
- return @"greek";
-
- // Cyrillic:
- case NSWindowsCP1251StringEncoding:
- return @"cp1251";
-
- // Asian:
- case NSJapaneseEUCStringEncoding:
- return @"ujis";
- case NSShiftJISStringEncoding:
- return @"sjis";
-
- default:
- return nil;
- }
-}
-
-/**
- * Returns the default charset of the library mysqlclient used.
- */
-+ (NSStringEncoding)defaultMySQLEncoding
-{
- return [MCPConnection encodingForMySQLEncoding:"utf8_general_ci"];
-}
-
-#pragma mark -
-#pragma mark Class maintenance
-
-/**
- *
- */
-+ (void)setTruncateLongFieldInLogs:(BOOL)iTruncFlag
-{
- sTruncateLongFieldInLogs = iTruncFlag;
-}
-
-/**
- *
- */
-+ (BOOL)truncateLongField
-{
- return sTruncateLongFieldInLogs;
-}
-
-/**
- * This method is to be used for getting special option for a connection, in which case the MCPConnection
- * has to be inited with the init method, then option are selected, finally connection is done using one
- * of the connect methods:
- *
- * MCPConnection *theConnect = [[MCPConnection alloc] init];
- *
- * [theConnect setConnectionOption: option toValue: value];
- * [theConnect connectToHost:albert.com withLogin:@"toto" password:@"albert" port:0];
- *
- */
-- (BOOL)setConnectionOption:(NSInteger)option toValue:(BOOL)value
-{
- // So far do nothing except for testing if it's proper time for setting option
- // What about if some option where setted and a connection is made again with connectTo...
- if ((mConnected) || (! mConnection)) {
- return FALSE;
- }
-
- if (value) { //Set this option to true
- mConnectionFlags |= option;
- }
- else { //Set this option to false
- mConnectionFlags &= (! option);
- }
-
- return YES;
-}
-
-/**
- * Trigger a connection to a server using the supplied details. Any details supplied are
- * stored for automatic reconnection attempts.
- *
- * - login is the user name
- * - pass is the password corresponding to the user name
- * - host is the hostname or IP adress
- * - port is the TCP port to use to connect. If port = 0, uses the default port from mysql.h
- * - socket is the path to the socket (for the localhost)
- *
- * The socket is used if the host is set to !{@"localhost"}, to an empty or a !{nil} string
- */
-- (BOOL)connectWithLogin:(NSString *)login password:(NSString *)pass host:(NSString *)host port:(NSUInteger)port socket:(NSString *)aSocket
-{
-
- // Reset any stored connection settings
- if (connectionHost) [connectionHost release], connectionHost = nil;
- if (connectionLogin) [connectionLogin release], connectionLogin = nil;
- if (connectionPassword) [connectionPassword release], connectionPassword = nil;
- if (connectionSocket) [connectionSocket release], connectionSocket = nil;
-
- // Determine whether a socket connection should be made
- if (!host || ![host length] || [host isEqualToString:@"localhost"]) {
- if (!aSocket || ![aSocket length]) {
- aSocket = [self findSocketPath];
- if (!aSocket) aSocket = @"";
- }
- connectionSocket = [[NSString alloc] initWithString:aSocket];
- connectionPort = 0;
-
- // Otherwise, use host and port details
- } else {
- connectionHost = [[NSString alloc] initWithString:host];
- connectionPort = port;
- }
-
- // Store the username
- connectionLogin = [[NSString alloc] initWithString:(login?login:@"")];
-
- // Store the password if supplied. It is more secure to allow MCPConnection to ask the
- // delegate to retrieve details - see delegate method keychainPasswordForConnection:)
- if (pass) connectionPassword = [[NSString alloc] initWithString:pass];
-
- // Trigger a connection and return the resulting status
- return [self connect];
-}
-
-/**
- * Selects a database to work with.
- *
- * The MCPConnection object needs to be properly inited and connected to a server.
- * If a connection is not yet set or the selection of the database didn't work, returns NO. Returns YES in normal cases where the database is properly selected.
- *
- * So far, if dbName is a nil pointer it will return NO (as if it cannot connect), most likely this will throw an exception in the future.
- */
-- (BOOL)selectDB:(NSString *) dbName
-{
- if (!mConnected) return NO;
-
- if (![self checkConnection]) return NO;
-
- // Here we should throw an exception, impossible to select a databse if the string is indeed a nil pointer
- if (dbName == nil) return NO;
-
- if (mConnected) {
-
- // Ensure the change is made in UTF8 to avoid encoding problems
- BOOL changeEncoding = ![[self encoding] isEqualToString:@"utf8"];
- if (changeEncoding) {
- [self storeEncodingForRestoration];
- [self setEncoding:@"utf8"];
- }
-
- const char *theDBName = [self cStringFromString:dbName];
- [self lockConnection];
- if (0 == mysql_select_db(mConnection, theDBName)) {
- [self unlockConnection];
- return YES;
- }
- [self unlockConnection];
-
- if (changeEncoding) [self restoreStoredEncoding];
- }
-
- [self setLastErrorMessage:nil];
-
- lastQueryErrorId = mysql_errno(mConnection);
-
- if (connectionProxy) {
- [connectionProxy disconnect];
- }
-
- return NO;
-}
-
-#pragma mark -
-#pragma mark Error information
-
-/**
- * Returns whether the last query errored or not.
- */
-- (BOOL)queryErrored
-{
- return (lastQueryErrorMessage)?YES:NO;
-}
-
-/**
- * Returns a string with the last MySQL error message on the connection.
- */
-- (NSString *)getLastErrorMessage
-{
- return lastQueryErrorMessage;
-}
-
-/**
- * Sets the string for the last MySQL error message on the connection,
- * managing memory as appropriate. Supply a nil string to store the
- * last error on the connection.
- */
-- (void)setLastErrorMessage:(NSString *)theErrorMessage
-{
- if (!theErrorMessage) theErrorMessage = [self stringWithCString:mysql_error(mConnection)];
-
- if (lastQueryErrorMessage) [lastQueryErrorMessage release], lastQueryErrorMessage = nil;
- if (theErrorMessage && [theErrorMessage length]) lastQueryErrorMessage = [[NSString alloc] initWithString:theErrorMessage];
-}
-
-/**
- * Returns the ErrorID of the last MySQL error on the connection.
- */
-- (NSUInteger)getLastErrorID
-{
- return lastQueryErrorId;
-}
-
-/**
- * Determines whether a supplied error number can be classed as a connection error.
- */
-+ (BOOL)isErrorNumberConnectionError:(NSInteger)theErrorNumber
-{
- switch (theErrorNumber) {
- case 2001: // CR_SOCKET_CREATE_ERROR
- case 2002: // CR_CONNECTION_ERROR
- case 2003: // CR_CONN_HOST_ERROR
- case 2004: // CR_IPSOCK_ERROR
- case 2005: // CR_UNKNOWN_HOST
- case 2006: // CR_SERVER_GONE_ERROR
- case 2007: // CR_VERSION_ERROR
- case 2009: // CR_WRONG_HOST_INFO
- case 2012: // CR_SERVER_HANDSHAKE_ERR
- case 2013: // CR_SERVER_LOST
- case 2027: // CR_MALFORMED_PACKET
- case 2032: // CR_DATA_TRUNCATED
- case 2047: // CR_CONN_UNKNOW_PROTOCOL
- case 2048: // CR_INVALID_CONN_HANDLE
- case 2050: // CR_FETCH_CANCELED
- case 2055: // CR_SERVER_LOST_EXTENDED
- return YES;
- }
-
- return NO;
-}
-
-/**
- * Update error messages - for example after a streaming result has finished processing.
- */
-- (void)updateErrorStatuses
-{
- [self setLastErrorMessage:nil];
- lastQueryErrorId = mysql_errno(mConnection);
-}
-
-#pragma mark -
-#pragma mark Queries
-
-/**
- * Takes a NSData object and transform it in a proper string for sending to the server in between quotes.
- */
-- (NSString *)prepareBinaryData:(NSData *)theData
-{
- const char *theCDataBuffer = [theData bytes];
- unsigned long theLength = [theData length];
- char *theCEscBuffer = (char *)calloc(sizeof(char),(theLength*2) + 1);
- NSString *theReturn;
-
- // mysql_hex_string requires an active connection.
- // If no connection is present, and no automatic reconnections can be made, return nil.
- if (!mConnected && ![self checkConnection]) {
-
- // Inform the delegate that there is no connection available
- if (delegate && [delegate respondsToSelector:@selector(noConnectionAvailable:)]) {
- [delegate noConnectionAvailable:self];
- }
-
- return nil;
- }
-
- // If thirty seconds have elapsed since the last query, check the connection.
- // This minimises the impact of continuous additional connection checks, but handles
- // most network issues and keeps high read/write timeouts for long queries.
- if ([self timeConnected] - lastQueryExecutedAtTime > 30) {
- if (![self checkConnection]) return nil;
- lastQueryExecutedAtTime = [self timeConnected];
- }
-
- // Using the mysql_hex_string function : (NO other solution found to be able to support blobs while using UTF-8 charset).
- mysql_hex_string(theCEscBuffer, theCDataBuffer, theLength);
- theReturn = [NSString stringWithFormat:@"%s", theCEscBuffer];
- free (theCEscBuffer);
- return theReturn;
-}
-
-/**
- * Takes a string and escape any special character (like single quote : ') so that the string can be used directly in a query.
- */
-- (NSString *)prepareString:(NSString *)theString
-{
- NSData *theCData = [theString dataUsingEncoding:stringEncoding allowLossyConversion:YES];
- unsigned long theLength = [theCData length];
- char *theCEscBuffer;
- NSString *theReturn;
- unsigned long theEscapedLength;
-
- if (theString == nil) {
- // In the mean time, no one should call this method on a nil string, the test should be done before by the user of this method.
- return @"";
- }
-
- // mysql_real_escape_string requires an active connection.
- // If no connection is present, and no automatic reconnections can be made, return nil.
- if (!mConnected && ![self checkConnection]) {
-
- // Inform the delegate that there is no connection available
- if (delegate && [delegate respondsToSelector:@selector(noConnectionAvailable:)]) {
- [delegate noConnectionAvailable:self];
- }
-
- return nil;
- }
-
- // If thirty seconds have elapsed since the last query, check the connection.
- // This minimises the impact of continuous additional connection checks, but handles
- // most network issues and keeps high read/write timeouts for long queries.
- if ([self timeConnected] - lastQueryExecutedAtTime > 30) {
- if (![self checkConnection]) return nil;
- lastQueryExecutedAtTime = [self timeConnected];
- }
-
- theCEscBuffer = (char *)calloc(sizeof(char),(theLength * 2) + 1);
- theEscapedLength = mysql_real_escape_string(mConnection, theCEscBuffer, [theCData bytes], theLength);
- theReturn = [[NSString alloc] initWithData:[NSData dataWithBytes:theCEscBuffer length:theEscapedLength] encoding:stringEncoding];
- free(theCEscBuffer);
-
- return [theReturn autorelease];
-}
-
-/**
- * Use the class of the theObject to know how it should be prepared for usage with the database.
- * If theObject is a string, this method will put single quotes to both its side and escape any necessary
- * character using prepareString: method. If theObject is NSData, the prepareBinaryData: method will be
- * used instead.
- *
- * For NSNumber object, the number is just quoted, for calendar dates, the calendar date is formatted in
- * the preferred format for the database.
- */
-- (NSString *)quoteObject:(id)theObject
-{
- if ((! theObject) || ([theObject isNSNull])) {
- return @"NULL";
- }
-
- if ([theObject isKindOfClass:[NSData class]]) {
- return [NSString stringWithFormat:@"X'%@'", [self prepareBinaryData:(NSData *) theObject]];
- }
-
- if ([theObject isKindOfClass:[NSString class]]) {
- return [NSString stringWithFormat:@"'%@'", [self prepareString:(NSString *) theObject]];
- }
-
- if ([theObject isKindOfClass:[NSNumber class]]) {
- return [NSString stringWithFormat:@"%@", theObject];
- }
-
- if ([theObject isKindOfClass:[NSCalendarDate class]]) {
- return [NSString stringWithFormat:@"'%@'", [(NSCalendarDate *)theObject descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S"]];
- }
-
- return [NSString stringWithFormat:@"'%@'", [self prepareString:[theObject description]]];
-}
-
-/**
- * Takes a query string and return an MCPResult object holding the result of the query.
- * The returned MCPResult is not retained, the client is responsible for that (it's autoreleased before being returned). If no field are present in the result (like in an insert query), will return nil (#{difference from previous version implementation}). Though, if their is at least one field the result will be non nil (even if no row are selected).
- *
- * Note that if you want to use this method with binary data (in the query), you should use !{prepareBinaryData:} to include the binary data in the query string. Also if you want to include in your query a string containing any special character (\, ', " ...) then you should use !{prepareString}.
- */
-- (MCPResult *)queryString:(NSString *)query
-{
- return [self queryString:query usingEncoding:stringEncoding streamingResult:MCPStreamingNone];
-}
-
-/**
- * Takes a query string and returns an MCPStreamingResult representing the result of the query.
- * If no fields are present in the result, nil will be returned.
- * Uses safe/fast mode, which may use more memory as results are downloaded.
- */
-- (MCPStreamingResult *)streamingQueryString:(NSString *)query
-{
- return [self queryString:query usingEncoding:stringEncoding streamingResult:MCPStreamingFast];
-}
-
-/**
- * Takes a query string and returns an MCPStreamingResult representing the result of the query.
- * If no fields are present in the result, nil will be returned.
- * Can be used in either fast/safe mode, where data is downloaded as fast as possible to avoid
- * blocking the server, or in full streaming mode for lowest memory usage but potentially blocking
- * the table.
- */
-- (MCPStreamingResult *)streamingQueryString:(NSString *)query useLowMemoryBlockingStreaming:(BOOL)fullStream
-{
- return [self queryString:query usingEncoding:stringEncoding streamingResult:(fullStream?MCPStreamingLowMem:MCPStreamingFast)];
-}
-
-/**
- * Error checks connection extensively - if this method fails due to a connection error, it will ask how to
- * proceed and loop depending on the status, not returning control until either the query has been executed
- * and the result can be returned or the connection and document have been closed.
- */
-- (id)queryString:(NSString *) query usingEncoding:(NSStringEncoding)aStringEncoding streamingResult:(NSInteger) streamResultType
-{
- MCPResult *theResult = nil;
- double queryStartTime, queryExecutionTime;
- const char *theCQuery;
- unsigned long theCQueryLength;
- NSInteger queryResultCode;
- NSInteger queryErrorId = 0;
- my_ulonglong queryAffectedRows = 0;
- NSInteger currentMaxAllowedPacket = -1;
- BOOL isQueryRetry = NO;
- NSString *queryErrorMessage = nil;
-
- // Reset the query cancelled boolean
- queryCancelled = NO;
-
- // If no connection is present, and no automatic reconnections can be made, return nil.
- if (!mConnected && ![self checkConnection]) {
- // Write a log entry
- if ([delegate respondsToSelector:@selector(queryGaveError:connection:)]) [delegate queryGaveError:@"No connection available!" connection:self];
-
- // Notify that the query has been performed
- [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:delegate];
-
- // Inform the delegate that there is no connection available
- if (delegate && [delegate respondsToSelector:@selector(noConnectionAvailable:)]) {
- [delegate noConnectionAvailable:self];
- }
-
- return nil;
- }
-
- // Inform the delegate about the query if logging is enabled and delegate responds to willQueryString:connection:
- if (delegateQueryLogging && delegateResponseToWillQueryString) {
- [delegate willQueryString:query connection:self];
- }
-
- // If thirty seconds have elapsed since the last query, check the connection.
- // This minimises the impact of continuous additional connection checks, but handles
- // most network issues and keeps high read/write timeouts for long queries.
- if ([self timeConnected] - lastQueryExecutedAtTime > 30
- && ![self checkConnection])
- {
- return nil;
- }
-
- // Derive the query string in the correct encoding
- NSData *d = NSStringDataUsingLossyEncoding(query, aStringEncoding, 1);
- theCQuery = [d bytes];
- // Set the length of the current query
- theCQueryLength = [d length];
-
- // Check query length against max_allowed_packet; if it is larger, the
- // query would error, so if max_allowed_packet is editable for the user
- // increase it for the current session and reconnect.
- if (maxAllowedPacketSize < theCQueryLength) {
-
- if (isMaxAllowedPacketEditable) {
-
- currentMaxAllowedPacket = maxAllowedPacketSize;
- [self setMaxAllowedPacketTo:strlen(theCQuery)+1024 resetSize:NO];
- [self reconnect];
-
- }
- else {
- NSString *errorMessage = [NSString stringWithFormat:NSLocalizedString(@"The query length of %lu bytes is larger than max_allowed_packet size (%lu).",
- @"error message if max_allowed_packet < query size"),
- (unsigned long)theCQueryLength, maxAllowedPacketSize];
-
- // Write a log entry and update the connection error messages for those uses that check it
- if ([delegate respondsToSelector:@selector(queryGaveError:connection:)]) [delegate queryGaveError:errorMessage connection:self];
- [self setLastErrorMessage:errorMessage];
-
- // Notify that the query has been performed
- [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:delegate];
-
- // Show an error alert while resetting
- if ([delegate respondsToSelector:@selector(showErrorWithTitle:message:)])
- [delegate showErrorWithTitle:NSLocalizedString(@"Error", @"error") message:errorMessage];
- else
- NSRunAlertPanel(NSLocalizedString(@"Error", @"error"), errorMessage, @"OK", nil, nil);
-
- return nil;
- }
- }
-
- // In a loop to allow one reattempt, perform the query.
- while (1) {
-
- // If this query has failed once already, check the connection
- if (isQueryRetry) {
- if (![self checkConnection]) {
- if (queryErrorMessage) [queryErrorMessage release], queryErrorMessage = nil;
-
- // Notify that the query has been performed
- [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:@"SMySQLQueryHasBeenPerformed" object:delegate];
- return nil;
- }
- }
-
- [self lockConnection];
-
- // Run (or re-run) the query, timing the execution time of the query - note
- // that this time will include network lag.
- queryStartTime = [self timeConnected];
- queryResultCode = mysql_real_query(mConnection, theCQuery, theCQueryLength);
- lastQueryExecutedAtTime = [self timeConnected];
- queryExecutionTime = lastQueryExecutedAtTime - queryStartTime;
-
- // On success, capture the results
- if (0 == queryResultCode) {
-
- queryAffectedRows = mysql_affected_rows(mConnection);
-
- if (mysql_field_count(mConnection) != 0) {
-
- // For normal result sets, fetch the results and unlock the connection
- if (streamResultType == MCPStreamingNone) {
- theResult = [[MCPResult alloc] initWithMySQLPtr:mConnection encoding:stringEncoding timeZone:mTimeZone];
- if (!queryCancelled || !queryCancelUsedReconnect) {
- [self unlockConnection];
- }
-
- // For streaming result sets, fetch the result pointer and leave the connection locked
- } else if (streamResultType == MCPStreamingFast) {
- theResult = [[MCPStreamingResult alloc] initWithMySQLPtr:mConnection encoding:stringEncoding timeZone:mTimeZone connection:self withFullStreaming:NO];
- } else if (streamResultType == MCPStreamingLowMem) {
- theResult = [[MCPStreamingResult alloc] initWithMySQLPtr:mConnection encoding:stringEncoding timeZone:mTimeZone connection:self withFullStreaming:YES];
- }
-
- // Ensure no problem occurred during the result fetch
- if (mysql_errno(mConnection) != 0) {
- queryErrorMessage = [self stringWithCString:mysql_error(mConnection)];
- if (queryErrorMessage) [queryErrorMessage retain];
- queryErrorId = mysql_errno(mConnection);
- break;
- }
- } else {
- [self unlockConnection];
- }
-
- queryErrorMessage = [[NSString alloc] initWithString:@""];
- queryErrorId = 0;
- if (streamResultType == MCPStreamingNone && queryAffectedRows == (my_ulonglong)~0) {
- queryAffectedRows = mysql_affected_rows(mConnection);
- }
-
- // On failure, set the error messages and IDs
- } else {
- if (!queryCancelled || !queryCancelUsedReconnect) {
- [self unlockConnection];
- }
-
- if (queryCancelled) {
- if (queryErrorMessage) [queryErrorMessage release], queryErrorMessage = nil;
- queryErrorMessage = [[NSString alloc] initWithString:NSLocalizedString(@"Query cancelled.", @"Query cancelled error")];
- queryErrorId = 1317;
- } else {
- if (queryErrorMessage) [queryErrorMessage release], queryErrorMessage = nil;
- queryErrorMessage = [self stringWithCString:mysql_error(mConnection)];
- if (queryErrorMessage) [queryErrorMessage retain];
- queryErrorId = mysql_errno(mConnection);
-
- // If the error was a connection error, retry once
- if (!isQueryRetry && retryAllowed && [MCPConnection isErrorNumberConnectionError:queryErrorId]) {
- isQueryRetry = YES;
- continue;
- }
- }
- }
-
- break;
- }
-
- if (streamResultType == MCPStreamingNone) {
-
- // If the mysql thread id has changed as a result of a connection error,
- // ensure connection details are still correct
- if (connectionThreadId != mConnection->thread_id) [self restoreConnectionDetails];
-
- // If max_allowed_packet was changed, reset it to default
- if(currentMaxAllowedPacket > -1)
- [self setMaxAllowedPacketTo:currentMaxAllowedPacket resetSize:YES];
- }
-
- // Update error strings and IDs
- lastQueryErrorId = queryErrorId;
-
- if (queryErrorMessage) {
- [self setLastErrorMessage:queryErrorMessage];
-
- [queryErrorMessage release];
- }
-
- lastQueryAffectedRows = queryAffectedRows;
- lastQueryExecutionTime = queryExecutionTime;
-
- // If an error occurred, inform the delegate
- if (queryResultCode & delegateResponseToWillQueryString)
- [delegate queryGaveError:lastQueryErrorMessage connection:self];
-
- if (!theResult) return nil;
- return [theResult autorelease];
-}
-
-/**
- * Returns the number of affected rows by the last query. Only actual queries
- * supplied via queryString:, streamingQueryString:, streamingQueryString:useLowMemoryBlockingStreaming:
- * or queryString:usingEncoding:streamingResult: will have their affected rows
- * returned, not any "meta" type queries.
- */
-- (my_ulonglong)affectedRows
-{
- if (mConnected) return lastQueryAffectedRows;
-
- return 0;
-}
-
-/**
- * If the last query was an insert in a table having a autoindex column, returns the ID
- * (autoindexed field) of the last row inserted.
- */
-- (my_ulonglong)insertId
-{
- if (mConnected) {
- return mysql_insert_id(mConnection);
- }
-
- return 0;
-}
-
-/**
- * Cancel the currently running query. This tries to kill the current query, and if that
- * isn't possible, resets the connection.
- */
-- (void) cancelCurrentQuery
-{
-
- // If not connected, return.
- if (![self isConnected]) return;
-
- // Check whether a query is actually being performed - if not, also return.
- if ([self tryLockConnection]) {
- [self unlockConnection];
- return;
- }
-
- // Set queryCancelled to prevent query retries
- queryCancelled = YES;
-
- // Set up a new connection, and running a KILL QUERY via it.
- MYSQL *killerConnection = mysql_init(NULL);
- if (killerConnection) {
- const char *theLogin = [self cStringFromString:connectionLogin];
- const char *theHost;
- const char *thePass = NULL;
- const char *theSocket;
- void *connectionSetupStatus;
-
- mysql_options(killerConnection, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&connectionTimeout);
- mysql_options(killerConnection, MYSQL_SET_CHARSET_NAME, "utf8");
-
- // Set up the host, socket and password as per the connect method
- if (!connectionHost || ![connectionHost length]) {
- theHost = NULL;
- } else {
- theHost = [connectionHost UTF8String];
- }
- if (connectionSocket == nil || ![connectionSocket length]) {
- theSocket = kMCPConnectionDefaultSocket;
- } else {
- theSocket = [connectionSocket UTF8String];
- }
- if (!connectionPassword) {
- if (delegate && [delegate respondsToSelector:@selector(keychainPasswordForConnection:)]) {
- thePass = [[delegate keychainPasswordForConnection:self] UTF8String];
- }
- } else {
- thePass = [connectionPassword UTF8String];
- }
- if (useSSL) {
- mysql_ssl_set(mConnection,
- sslKeyFilePath ? [sslKeyFilePath UTF8String] : NULL,
- sslCertificatePath ? [sslCertificatePath UTF8String] : NULL,
- sslCACertificatePath ? [sslCACertificatePath UTF8String] : NULL,
- NULL,
- kMCPSSLCipherList);
- }
-
- // Connect
- connectionSetupStatus = mysql_real_connect(killerConnection, theHost, theLogin, thePass, NULL, (unsigned int)connectionPort, theSocket, mConnectionFlags);
- thePass = NULL;
- if (connectionSetupStatus) {
-
- // Set up a KILL query. For MySQL 5+, kill just the query; otherwise, kill the thread.
- NSStringEncoding killerConnectionEncoding = [MCPConnection encodingForMySQLEncoding:mysql_character_set_name(killerConnection)];
- NSString *killQueryString;
- if ([self serverMajorVersion] >= 5) {
- killQueryString = [NSString stringWithFormat:@"KILL QUERY %lu", mConnection->thread_id];
- } else {
- killQueryString = [NSString stringWithFormat:@"KILL %lu", mConnection->thread_id];
- }
- NSData *encodedKillQueryData = NSStringDataUsingLossyEncoding(killQueryString, killerConnectionEncoding, 1);
- const char *killQueryCString = [encodedKillQueryData bytes];
- unsigned long killQueryCStringLength = [encodedKillQueryData length];
- int killerReturnError = mysql_real_query(killerConnection, killQueryCString, killQueryCStringLength);
- mysql_close(killerConnection);
- if (killerReturnError == 0) {
- queryCancelUsedReconnect = NO;
- return;
- }
- NSLog(@"Task cancellation: kill query failed (Returned status %d)", killerReturnError);
- } else {
- NSLog(@"Task cancellation connection failed (error %u)", mysql_errno(killerConnection));
- }
- } else {
- NSLog(@"Task cancelletion MySQL init failed.");
- }
-
- // As the attempt may have taken up to the connection timeout, check lock status
- // again, returning if nothing is required.
- if ([self tryLockConnection]) {
- [self unlockConnection];
- return;
- }
-
- // Reset the connection
- [self unlockConnection];
- if (!isDisconnecting) [self reconnect];
-
- // Set queryCancelled again to handle requery cleanups, and return.
- queryCancelled = YES;
- queryCancelUsedReconnect = YES;
-}
-
-/**
- * Return whether the last query was cancelled
- */
-- (BOOL)queryCancelled
-{
- return queryCancelled;
-}
-
-/**
- * If the last query was cancelled, returns whether that cancellation
- * required a connection reset. If the last query was not cancelled
- * the behaviour is undefined.
- */
-- (BOOL)queryCancellationUsedReconnect
-{
- return queryCancelUsedReconnect;
-}
-
-/**
- * Retrieves all remaining results and discards them.
- * Necessary if we only retrieve one result, and want to discard all the others.
- */
-- (void)flushMultiResults
-{
- // repeat as long as there are results
- while(!mysql_next_result(mConnection))
- {
- MYSQL_RES *result = mysql_use_result(mConnection);
- // check if the result is really a result
- if (result) {
- // retrieve all rows
- while (mysql_fetch_row(result));
- mysql_free_result(result);
- }
- }
-}
-
-#pragma mark -
-#pragma mark Connection locking
-
-/**
- * Lock the connection. This must be done before performing any operation
- * that is not thread safe, eg. performing queries or pinging.
- */
-- (void)lockConnection
-{
- // We can only start a query as soon as the condition is MCPConnectionIdle
- [connectionLock lockWhenCondition:MCPConnectionIdle];
-
- // We now set the condition to MCPConnectionBusy
- [connectionLock unlockWithCondition:MCPConnectionBusy];
-}
-
-/**
- * Try locking the connection. If the connection is idle (unlocked), this method
- * locks the connection and returns YES. The connection must afterwards be unlocked
- * using unlockConnection. If the connection is currently busy (locked), this
- * method immediately returns NO and doesn't lock the connection.
- */
-- (BOOL)tryLockConnection
-{
- // check if the condition is MCPConnectionIdle
- if ([connectionLock tryLockWhenCondition:MCPConnectionIdle]) {
- // We're allowed to use the connection!
- [connectionLock unlockWithCondition:MCPConnectionBusy];
- return YES;
- } else {
- // Someone else is using the connection right now
- return NO;
- }
-}
-
-
-/**
- * Unlock the connection.
- */
-- (void)unlockConnection
-{
- // We don't care if the connection is busy or not
- [connectionLock lock];
-
- // We check if the connection actually was busy. If it wasn't busy,
- // it means we probably tried to unlock the connection twice. This is
- // potentially dangerous, therefore we log this to the console
- if ([connectionLock condition] != MCPConnectionBusy) {
- NSLog(@"Tried to unlock the connection, but it wasn't locked.");
- }
-
- // Since we connected with CLIENT_MULTI_RESULT, we must make sure there are nor more results!
- // This is still a bit of a dirty hack
- if (mConnected && mConnection && mConnection->net.vio && mConnection->net.buff && mysql_more_results(mConnection)) {
- NSLog(@"Discarding unretrieved results. This is currently normal when using CALL.");
- [self flushMultiResults];
- }
-
- // We tell everyone that the connection is available again!
- [connectionLock unlockWithCondition:MCPConnectionIdle];
-}
-
-#pragma mark -
-#pragma mark Database structure
-
-/**
- * Just a fast wrapper for the more complex !{listDBsWithPattern:} method.
- */
-- (MCPResult *)listDBs
-{
- return [self listDBsLike:nil];
-}
-
-/**
- * Returns a list of database which name correspond to the SQL regular expression in 'pattern'.
- * The comparison is done with wild card extension : % and _.
- * The result should correspond to the queryString:@"SHOW databases [LIKE wild]"; but implemented with mysql_list_dbs.
- * If an empty string or nil is passed as pattern, all databases will be shown.
- */
-- (MCPResult *)listDBsLike:(NSString *)dbsName
-{
- if (!mConnected) return NO;
-
- MCPResult *theResult = nil;
- MYSQL_RES *theResPtr;
-
- if (![self checkConnection]) return [[[MCPResult alloc] init] autorelease];
-
- // Ensure UTF8 - where supported - when getting database list.
- NSString *currentEncoding = [NSString stringWithString:encoding];
- BOOL currentEncodingUsesLatin1Transport = encodingUsesLatin1Transport;
- [self setEncoding:@"utf8"];
-
- [self lockConnection];
- if ((dbsName == nil) || ([dbsName isEqualToString:@""])) {
- if ((theResPtr = mysql_list_dbs(mConnection, NULL))) {
- theResult = [[MCPResult alloc] initWithResPtr: theResPtr encoding:stringEncoding timeZone:mTimeZone];
- }
- else {
- theResult = [[MCPResult alloc] init];
- }
- }
- else {
- const char *theCDBsName = (const char *)[self cStringFromString:dbsName];
-
- if ((theResPtr = mysql_list_dbs(mConnection, theCDBsName))) {
- theResult = [[MCPResult alloc] initWithResPtr:theResPtr encoding:stringEncoding timeZone:mTimeZone];
- }
- else {
- theResult = [[MCPResult alloc] init];
- }
- }
- [self unlockConnection];
-
- // Restore the connection encoding if necessary
- [self setEncoding:currentEncoding];
- [self setEncodingUsesLatin1Transport:currentEncodingUsesLatin1Transport];
-
- if (theResult) {
- [theResult autorelease];
- }
-
- return theResult;
-}
-
-/**
- * Make sure a DB is selected (with !{selectDB:} method) first.
- */
-- (MCPResult *)listTables
-{
- return [self listTablesLike:nil];
-}
-
-/**
- * From within a database, give back the list of table which name correspond to tablesName
- * (with wild card %, _ extension). Correspond to queryString:@"SHOW tables [LIKE wild]"; uses mysql_list_tables function.
- *
- * If an empty string or nil is passed as tablesName, all tables will be shown.
- *
- * WARNING: #{produce an error if no databases are selected} (with !{selectDB:} for example).
- */
-- (MCPResult *)listTablesLike:(NSString *)tablesName
-{
- if (!mConnected) return NO;
-
- MCPResult *theResult = nil;
- MYSQL_RES *theResPtr;
-
- if (![self checkConnection]) return [[[MCPResult alloc] init] autorelease];
-
- [self lockConnection];
- if ((tablesName == nil) || ([tablesName isEqualToString:@""])) {
- if ((theResPtr = mysql_list_tables(mConnection, NULL))) {
- theResult = [[MCPResult alloc] initWithResPtr: theResPtr encoding:stringEncoding timeZone:mTimeZone];
- }
- else {
- theResult = [[MCPResult alloc] init];
- }
- }
- else {
- const char *theCTablesName = (const char *)[self cStringFromString:tablesName];
- if ((theResPtr = mysql_list_tables(mConnection, theCTablesName))) {
- theResult = [[MCPResult alloc] initWithResPtr: theResPtr encoding:stringEncoding timeZone:mTimeZone];
- }
- else {
- theResult = [[MCPResult alloc] init];
- }
- }
-
- [self unlockConnection];
-
- if (theResult) {
- [theResult autorelease];
- }
-
- return theResult;
-}
-
-- (NSArray *)listTablesFromDB:(NSString *)dbName {
- return [self listTablesFromDB:dbName like:nil];
-}
-
-/**
- * List tables in DB specified by dbName and corresponding to pattern.
- * This method indeed issues a !{SHOW TABLES FROM dbName LIKE ...} query to the server.
- * This is done this way to make sure the selected DB is not changed by this method.
- */
-- (NSArray *)listTablesFromDB:(NSString *)dbName like:(NSString *)tablesName {
- MCPResult *theResult;
- if ((tablesName == nil) || ([tablesName isEqualToString:@""])) {
- NSString *theQuery = [NSString stringWithFormat:@"SHOW TABLES FROM %@",
- [dbName backtickQuotedString]];
- theResult = [self queryString:theQuery];
- } else {
- NSString *theQuery = [NSString stringWithFormat:@"SHOW TABLES FROM %@ LIKE '%@'",
- [dbName backtickQuotedString],
- [tablesName backtickQuotedString]];
- theResult = [self queryString:theQuery];
- }
- [theResult setReturnDataAsStrings:YES];
- NSString *theTableName;
- NSMutableArray *theDBTables = [NSMutableArray array];
-
- // NSLog(@"num of fields: %@; num of rows: %@", [theResult numOfFields], [theResult numOfRows]);
- if ([theResult numOfRows] > 0) {
- my_ulonglong i;
- for ( i = 0 ; i < [theResult numOfRows] ; i++ ) {
- theTableName = [[theResult fetchRowAsArray] objectAtIndex:0];
- [theDBTables addObject:theTableName];
- }
- }
-
- return theDBTables;
-}
-
-/**
- * Just a fast wrapper for the more complex list !{listFieldsWithPattern:forTable:} method.
- */
-- (MCPResult *)listFieldsFromTable:(NSString *)tableName
-{
- return [self listFieldsFromTable:tableName like:nil];
-}
-
-/**
- * Show all the fields of the table tableName which name correspond to pattern (with wild card expansion : %,_).
- * Indeed, and as recommanded from mysql reference, this method is NOT using mysql_list_fields but the !{queryString:} method.
- * If an empty string or nil is passed as fieldsName, all fields (of tableName) will be returned.
- */
-- (MCPResult *)listFieldsFromTable:(NSString *)tableName like:(NSString *)fieldsName
-{
- MCPResult *theResult;
-
- if ((fieldsName == nil) || ([fieldsName isEqualToString:@""])) {
- NSString *theQuery = [NSString stringWithFormat:@"SHOW COLUMNS FROM %@",
- [tableName backtickQuotedString]];
- theResult = [self queryString:theQuery];
- }
- else {
- NSString *theQuery = [NSString stringWithFormat:@"SHOW COLUMNS FROM %@ LIKE '%@'",
- [tableName backtickQuotedString],
- [fieldsName backtickQuotedString]];
- theResult = [self queryString:theQuery];
- }
- [theResult setReturnDataAsStrings:YES];
-
- return theResult;
-}
-
-/**
- * Updates the dict containing the structure of all available databases (mainly for completion/navigator)
- * executed on a new connection.
- *
- * TODO: Split this entire method out of MCPKit if possible
- */
-- (void)queryDbStructureWithUserInfo:(NSDictionary*)userInfo
-{
- NSAutoreleasePool *queryPool = [[NSAutoreleasePool alloc] init];
- BOOL structureWasUpdated = NO;
-
- // if 'cancelQuerying' is set try to interrupt any current querying
- if(userInfo && [userInfo objectForKey:@"cancelQuerying"])
- cancelQueryingDbStructure = YES;
-
- // Requests are queued
- while(isQueryingDbStructure > 0) { usleep(1000000); }
-
- cancelQueryingDbStructure = NO;
-
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SPDBStructureIsUpdating" object:delegate];
-
- NSString *SPUniqueSchemaDelimiter = @"￸";
-
- NSString *connectionID;
- if([delegate respondsToSelector:@selector(connectionID)])
- connectionID = [NSString stringWithString:[[self delegate] connectionID]];
- else
- connectionID = @"_";
-
- // Re-init with already cached data from navigator controller
- NSMutableDictionary *queriedStructure = [NSMutableDictionary dictionary];
- NSDictionary *dbstructure = [[self delegate] getDbStructure];
- if (dbstructure) [queriedStructure setDictionary:[NSMutableDictionary dictionaryWithDictionary:dbstructure]];
-
- NSMutableArray *queriedStructureKeys = [NSMutableArray array];
- NSArray *dbStructureKeys = [[self delegate] allSchemaKeys];
- if (dbStructureKeys) [queriedStructureKeys setArray:dbStructureKeys];
-
- // Retrieve all the databases known of by the delegate
- NSMutableArray *connectionDatabases = [NSMutableArray array];
- [connectionDatabases addObjectsFromArray:[[self delegate] allSystemDatabaseNames]];
- [connectionDatabases addObjectsFromArray:[[self delegate] allDatabaseNames]];
-
- // Add all known databases coming from connection if they aren't parsed yet
- for (id db in connectionDatabases) {
- NSString *dbid = [NSString stringWithFormat:@"%@%@%@", connectionID, SPUniqueSchemaDelimiter, db];
- if(![queriedStructure objectForKey:dbid]) {
- structureWasUpdated = YES;
- [queriedStructure setObject:db forKey:dbid];
- [queriedStructureKeys addObject:dbid];
- }
- }
-
- // Check the existing databases in the 'structure' and 'allKeysOfDbStructure' stores,
- // and remove any that are no longer found in the connectionDatabases list (indicating deletion).
- // Iterate through extracted keys to avoid <NSCFDictionary> mutation while being enumerated.
- NSArray *keys = [queriedStructure allKeys];
- for(id key in keys) {
- NSString *db = [[key componentsSeparatedByString:SPUniqueSchemaDelimiter] objectAtIndex:1];
- if(![connectionDatabases containsObject:db]) {
- structureWasUpdated = YES;
- [queriedStructure removeObjectForKey:key];
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT SELF BEGINSWITH %@", [NSString stringWithFormat:@"%@%@", key, SPUniqueSchemaDelimiter]];
- [queriedStructureKeys filterUsingPredicate:predicate];
- [queriedStructureKeys removeObject:key];
- }
- }
-
- NSString *currentDatabase = nil;
- if([delegate respondsToSelector:@selector(database)])
- currentDatabase = [[self delegate] database];
-
- // Determine whether the database details need to be queried.
- BOOL shouldQueryStructure = YES;
- NSString *db_id = nil;
-
- // If no database is selected, no need to check further
- if(!currentDatabase || (currentDatabase && ![currentDatabase length])) {
- shouldQueryStructure = NO;
-
- // Otherwise, build up the schema key for the database to be retrieved.
- } else {
- db_id = [NSString stringWithFormat:@"%@%@%@", connectionID, SPUniqueSchemaDelimiter, currentDatabase];
-
- // Check to see if a cache already exists for the database.
- if ([queriedStructure objectForKey:db_id] && [[queriedStructure objectForKey:db_id] isKindOfClass:[NSDictionary class]]) {
-
- // The cache is available. If the `mysql` or `information_schema` databases are being queried,
- // never requery as their structure will never change.
- // 5.5.3+ also has performance_schema meta database
- if ([currentDatabase isEqualToString:@"mysql"] || [currentDatabase isEqualToString:@"information_schema"] || [currentDatabase isEqualToString:@"performance_schema"]) {
- shouldQueryStructure = NO;
-
- // Otherwise, if the forceUpdate flag wasn't supplied or evaluates to false, also don't update.
- } else if (userInfo == nil || ![userInfo objectForKey:@"forceUpdate"] || ![[userInfo objectForKey:@"forceUpdate"] boolValue]) {
- shouldQueryStructure = NO;
- }
- }
- }
-
- // If it has been determined that no new structure needs to be retrieved, clean up and return.
- if (!shouldQueryStructure) {
-
- // Update the global variables and make sure that no request reads these global variables
- // while updating
- [self performSelectorOnMainThread:@selector(lockQuerying) withObject:nil waitUntilDone:YES];
- [self performSelectorOnMainThread:@selector(updateGlobalVariablesWith:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:queriedStructure, @"structure", queriedStructureKeys, @"keys", nil] waitUntilDone:YES];
- [self performSelectorOnMainThread:@selector(unlockQuerying) withObject:nil waitUntilDone:YES];
- if (structureWasUpdated)
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SPDBStructureWasUpdated" object:delegate];
- [queryPool release];
- return;
- }
-
- // Retrieve the tables and views for this database from SPTablesList
- NSMutableArray *tablesAndViews = [NSMutableArray array];
- for (id aTable in [[[self delegate] valueForKeyPath:@"tablesListInstance"] allTableNames]) {
- NSDictionary *aTableDict = [NSDictionary dictionaryWithObjectsAndKeys:
- aTable, @"name",
- @"0", @"type",
- nil];
- [tablesAndViews addObject:aTableDict];
- }
- for (id aView in [[[self delegate] valueForKeyPath:@"tablesListInstance"] allViewNames]) {
- NSDictionary *aViewDict = [NSDictionary dictionaryWithObjectsAndKeys:
- aView, @"name",
- @"1", @"type",
- nil];
- [tablesAndViews addObject:aViewDict];
- }
-
- // Do not parse more than 2000 tables/views per db
- if([tablesAndViews count] > 2000) {
- NSLog(@"%lu items in database %@. Only 2000 items can be parsed. Stopped parsing.", (unsigned long)[tablesAndViews count], currentDatabase);
- [queryPool release];
- return;
- }
-
- // For future usage - currently unused
- // If the affected item name and type - for example, table type and table name - were supplied, extract it.
- NSString *affectedItem = nil;
- NSInteger affectedItemType = -1;
- if(userInfo && [userInfo objectForKey:@"affectedItem"]) {
- affectedItem = [userInfo objectForKey:@"affectedItem"];
- if([userInfo objectForKey:@"affectedItemType"])
- affectedItemType = [[userInfo objectForKey:@"affectedItemType"] intValue];
- else
- affectedItem = nil;
- }
-
- // Delete all stored data for the database to be updated, leaving the structure key
- [queriedStructure removeObjectForKey:db_id];
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT SELF BEGINSWITH %@", [NSString stringWithFormat:@"%@%@", db_id, SPUniqueSchemaDelimiter]];
- [queriedStructureKeys filterUsingPredicate:predicate];
-
- // Set up the database as an empty mutable dictionary ready for tables, and store a reference
- [queriedStructure setObject:[NSMutableDictionary dictionary] forKey:db_id];
- NSMutableDictionary *databaseStructure = [queriedStructure objectForKey:db_id];
-
- NSString *currentDatabaseEscaped = [currentDatabase stringByReplacingOccurrencesOfString:@"`" withString:@"``"];
-
- MYSQL *structConnection = mysql_init(NULL);
- if (structConnection) {
- const char *theLogin = [connectionLogin UTF8String];
- const char *theHost;
- const char *thePass = NULL;
- const char *theSocket;
- void *connectionSetupStatus;
-
- mysql_options(structConnection, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&connectionTimeout);
- mysql_options(structConnection, MYSQL_SET_CHARSET_NAME, "utf8");
-
- // Set up the host, socket and password as per the connect method
- if (!connectionHost || ![connectionHost length]) {
- theHost = NULL;
- } else {
- theHost = [connectionHost UTF8String];
- }
- if (connectionSocket == nil || ![connectionSocket length]) {
- theSocket = kMCPConnectionDefaultSocket;
- } else {
- theSocket = [connectionSocket UTF8String];
- }
- if (useSSL) {
- mysql_ssl_set(mConnection,
- sslKeyFilePath ? [sslKeyFilePath UTF8String] : NULL,
- sslCertificatePath ? [sslCertificatePath UTF8String] : NULL,
- sslCACertificatePath ? [sslCACertificatePath UTF8String] : NULL,
- NULL,
- kMCPSSLCipherList);
- }
- if (!connectionPassword) {
- if (delegate && [delegate respondsToSelector:@selector(keychainPasswordForConnection:)]) {
- thePass = [[delegate keychainPasswordForConnection:self] UTF8String];
- }
- } else {
- thePass = [connectionPassword UTF8String];
- }
-
- // Connect
- connectionSetupStatus = mysql_real_connect(structConnection, theHost, theLogin, thePass, NULL, (unsigned int)connectionPort, theSocket, mConnectionFlags);
- thePass = NULL;
- if (connectionSetupStatus) {
- MYSQL_RES *theResult;
- MYSQL_ROW row;
- NSString *charset;
- NSUInteger uniqueCounter = 0; // used to make field data unique
- NSString *query;
- NSData *encodedQueryData;
- const char *queryCString;
- unsigned long queryCStringLength;
-
- // Get the doc encoding due to pref settings etc, defaulting to UTF8
- NSString *docEncoding = [self encoding];
- if (!docEncoding) docEncoding = @"utf8";
- NSStringEncoding theConnectionEncoding = [MCPConnection encodingForMySQLEncoding:[self cStringFromString:docEncoding]];
-
- // Try to set connection encoding for MySQL >= 4.1
- if ([self serverMajorVersion] > 4 || ([self serverMajorVersion] >= 4 && [self serverMinorVersion] >= 1)) {
- query = [NSString stringWithFormat:@"SET NAMES '%@'", docEncoding];
- encodedQueryData = NSStringDataUsingLossyEncoding(query, theConnectionEncoding, 1);
- queryCString = [encodedQueryData bytes];
- queryCStringLength = [encodedQueryData length];
- if (mysql_real_query(structConnection, queryCString, queryCStringLength) != 0) {
- NSLog(@"Error while querying the database structure. Could not set encoding to %@", docEncoding);
- [queryPool release];
- return;
- }
- }
-
- // Increase global query-db-counter
- [self performSelectorOnMainThread:@selector(incrementQueryingDbStructure) withObject:nil waitUntilDone:YES];
-
- // Loop through the known tables and views, retrieving details for each
- for (NSDictionary *aTableDict in tablesAndViews) {
-
- // If cancelled, abort without saving
- if (cancelQueryingDbStructure) {
- [self performSelectorOnMainThread:@selector(decrementQueryingDbStructure) withObject:nil waitUntilDone:YES];
- [queryPool release];
- return;
- }
-
- if(![aTableDict objectForKey:@"name"]) continue;
- // Extract the name
- NSString *aTableName = [aTableDict objectForKey:@"name"];
-
- if(!aTableName) continue;
- if(![aTableName isKindOfClass:[NSString class]]) continue;
- if(![aTableName length]) continue;
- // Retrieve the column details
- query = [NSString stringWithFormat:@"SHOW FULL COLUMNS FROM `%@` FROM `%@`",
- [aTableName stringByReplacingOccurrencesOfString:@"`" withString:@"``"],
- currentDatabaseEscaped];
- encodedQueryData = NSStringDataUsingLossyEncoding(query, theConnectionEncoding, 1);
- queryCString = [encodedQueryData bytes];
- queryCStringLength = [encodedQueryData length];
- if (mysql_real_query(structConnection, queryCString, queryCStringLength) != 0) {
- // NSLog(@"error %@", aTableName);
- continue;
- }
- theResult = mysql_use_result(structConnection);
-
- // Add a structure key for this table
- NSString *table_id = [NSString stringWithFormat:@"%@%@%@", db_id, SPUniqueSchemaDelimiter, aTableName];
- [queriedStructureKeys addObject:table_id];
-
- // Add a mutable dictionary to the structure and store a reference
- [databaseStructure setObject:[NSMutableDictionary dictionary] forKey:table_id];
- NSMutableDictionary *tableStructure = [databaseStructure objectForKey:table_id];
-
- // Loop through the fields, extracting details for each
- while ((row = mysql_fetch_row(theResult))) {
- NSString *field = [self stringWithCString:row[0] usingEncoding:theConnectionEncoding] ;
- NSString *type = [self stringWithCString:row[1] usingEncoding:theConnectionEncoding] ;
- NSString *type_display = [type stringByReplacingOccurrencesOfRegex:@"\\(.*?,.*?\\)" withString:@"(…)"];
- NSString *coll = [self stringWithCString:row[2] usingEncoding:theConnectionEncoding] ;
- NSString *isnull = [self stringWithCString:row[3] usingEncoding:theConnectionEncoding] ;
- NSString *key = [self stringWithCString:row[4] usingEncoding:theConnectionEncoding] ;
- NSString *def = [self stringWithCString:row[5] usingEncoding:theConnectionEncoding] ;
- NSString *extra = [self stringWithCString:row[6] usingEncoding:theConnectionEncoding] ;
- NSString *priv = [self stringWithCString:row[7] usingEncoding:theConnectionEncoding] ;
- NSString *comment;
- if (sizeof(row) > 8) {
- comment = [self stringWithCString:row[8] usingEncoding:theConnectionEncoding] ;
- } else {
- comment = @"";
- }
- NSArray *a = [coll componentsSeparatedByString:@"_"];
- charset = ([a count]) ? [a objectAtIndex:0] : @"";
-
- // Add a structure key for this field
- NSString *field_id = [NSString stringWithFormat:@"%@%@%@", table_id, SPUniqueSchemaDelimiter, field];
- [queriedStructureKeys addObject:field_id];
-
- [tableStructure setObject:[NSArray arrayWithObjects:type, def, isnull, charset, coll, key, extra, priv, comment, type_display, [NSNumber numberWithUnsignedLongLong:uniqueCounter], nil] forKey:field_id];
- [tableStructure setObject:[aTableDict objectForKey:@"type"] forKey:@" struct_type "];
- uniqueCounter++;
- }
- mysql_free_result(theResult);
- usleep(10);
- }
-
- // If the MySQL version is higher than 5, also retrieve function/procedure details via the information_schema table
- if([self serverMajorVersion] >= 5) {
-
- // The information_schema table is UTF-8 encoded - alter the connection
- query = @"SET NAMES 'utf8'";
- encodedQueryData = NSStringDataUsingLossyEncoding(query, theConnectionEncoding, 1);
- queryCString = [encodedQueryData bytes];
- queryCStringLength = [encodedQueryData length];
- if (mysql_real_query(structConnection, queryCString, queryCStringLength) == 0) {
-
- // Query for procedures and functions
- query = [NSString stringWithFormat:@"SELECT * FROM `information_schema`.`ROUTINES` WHERE `information_schema`.`ROUTINES`.`ROUTINE_SCHEMA` = '%@'", [currentDatabase stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"]];
- encodedQueryData = NSStringDataUsingLossyEncoding(query, theConnectionEncoding, 1);
- queryCString = [encodedQueryData bytes];
- queryCStringLength = [encodedQueryData length];
- if (mysql_real_query(structConnection, queryCString, queryCStringLength) == 0) {
- theResult = mysql_use_result(structConnection);
-
- // Loop through the rows and extract the function details
- while ((row = mysql_fetch_row(theResult))) {
-
- // If cancelled, abort without saving the new structure
- if(cancelQueryingDbStructure) {
- [self performSelectorOnMainThread:@selector(decrementQueryingDbStructure) withObject:nil waitUntilDone:YES];
- [queryPool release];
- return;
- }
-
- NSString *fname = [self stringWithUTF8CString:row[0]];
- NSString *type = ([[self stringWithUTF8CString:row[4]] isEqualToString:@"FUNCTION"]) ? @"3" : @"2";
- NSString *dtd = [self stringWithUTF8CString:row[5]];
- NSString *det = [self stringWithUTF8CString:row[11]];
- NSString *dataaccess = [self stringWithUTF8CString:row[12]];
- NSString *security_type = [self stringWithUTF8CString:row[14]];
- NSString *definer = [self stringWithUTF8CString:row[19]];
-
- // Generate "table" and "field" names and add to structure key store
- NSString *table_id = [NSString stringWithFormat:@"%@%@%@", db_id, SPUniqueSchemaDelimiter, fname];
- NSString *field_id = [NSString stringWithFormat:@"%@%@%@", table_id, SPUniqueSchemaDelimiter, fname];
- [queriedStructureKeys addObject:table_id];
- [queriedStructureKeys addObject:field_id];
-
- // Ensure that a dictionary exists for this "table" name
- if(![[queriedStructure valueForKey:db_id] valueForKey:table_id])
- [[queriedStructure valueForKey:db_id] setObject:[NSMutableDictionary dictionary] forKey:table_id];
-
- // Add the "field" details
- [[[queriedStructure valueForKey:db_id] valueForKey:table_id] setObject:
- [NSArray arrayWithObjects:dtd, dataaccess, det, security_type, definer, [NSNumber numberWithUnsignedLongLong:uniqueCounter], nil] forKey:field_id];
- [[[queriedStructure valueForKey:db_id] valueForKey:table_id] setObject:type forKey:@" struct_type "];
- uniqueCounter++;
- }
- mysql_free_result(theResult);
- } else {
- NSLog(@"Error while querying the database structure for procedures and functions. Could not set encoding to utf8");
- }
- }
- }
-
- // Update the global variables and make sure that no request reads these global variables
- // while updating
- [self performSelectorOnMainThread:@selector(lockQuerying) withObject:nil waitUntilDone:YES];
- [self performSelectorOnMainThread:@selector(updateGlobalVariablesWith:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:queriedStructure, @"structure", queriedStructureKeys, @"keys", nil] waitUntilDone:YES];
- [self performSelectorOnMainThread:@selector(unlockQuerying) withObject:nil waitUntilDone:YES];
-
-
- mysql_close(structConnection);
-
- // Notify that the structure querying has been performed
- [[NSNotificationCenter defaultCenter] postNotificationName:@"SPDBStructureWasUpdated" object:delegate];
-
- [self performSelectorOnMainThread:@selector(decrementQueryingDbStructure) withObject:nil waitUntilDone:YES];
- }
- }
-
- [queryPool release];
-}
-
-/*
- * Update global variables on main thread to avoid accessing from different threads
- */
-- (void)updateGlobalVariablesWith:(NSDictionary*)object
-{
- NSString *connectionID = [[self delegate] connectionID];
-
- // Return if the delegate indicates disconnection
- if([connectionID length] < 2) return;
-
- if(![structure valueForKey:connectionID])
- [structure setObject:[NSMutableDictionary dictionary] forKey:connectionID];
- [structure setObject:[object objectForKey:@"structure"] forKey:connectionID];
- [allKeysofDbStructure setArray:[object objectForKey:@"keys"]];
- usleep(100);
-}
-
-- (void)incrementQueryingDbStructure
-{
- isQueryingDbStructure++;
-}
-
-- (void)decrementQueryingDbStructure
-{
- isQueryingDbStructure--;
- if(isQueryingDbStructure < 0) isQueryingDbStructure = 0;
-}
-
-- (BOOL)isQueryingDatabaseStructure
-{
- return (isQueryingDbStructure > 0) ? YES : NO;
-}
-
-- (void)lockQuerying
-{
- lockQuerying = YES;
-}
-
-- (void)unlockQuerying
-{
- lockQuerying = NO;
- usleep(50000);
-}
-/**
- * Returns a dict containing the structure of all available databases
- */
-- (NSDictionary *)getDbStructure
-{
- if(lockQuerying) return nil;
- NSDictionary *d = [NSDictionary dictionaryWithDictionary:structure];
- return d;
-}
-
-/**
- * Returns all keys of the db structure
- */
-- (NSArray *)getAllKeysOfDbStructure
-{
- if(lockQuerying) return nil;
- NSArray *r = [NSArray arrayWithArray:allKeysofDbStructure];
- return r;
-}
-
-#pragma mark -
-#pragma mark Server information
-
-/**
- * Returns a string giving the client library version.
- */
-- (NSString *)clientInfo
-{
- return [self stringWithCString:mysql_get_client_info()];
-}
-
-/**
- * Returns a string giving information on the host of the DB server.
- */
-- (NSString *)hostInfo
-{
- return [self stringWithCString:mysql_get_host_info(mConnection)];
-}
-
-/**
- * Returns a string giving the server version.
- */
-- (NSString *)serverInfo
-{
- if (mConnected) {
- return [self stringWithCString: mysql_get_server_info(mConnection)];
- }
-
- return @"";
-}
-
-/**
- * Returns the number of the protocole used to transfer info from server to client
- */
-- (NSNumber *)protoInfo
-{
- return [MCPNumber numberWithUnsignedInteger:mysql_get_proto_info(mConnection)];
-}
-
-/**
- * Lists active process
- */
-- (MCPResult *)listProcesses
-{
- MCPResult *result = nil;
- MYSQL_RES *theResPtr;
-
- [self lockConnection];
-
- if (mConnected && (mConnection != NULL)) {
- if ((theResPtr = mysql_list_processes(mConnection))) {
- result = [[MCPResult alloc] initWithResPtr:theResPtr encoding:stringEncoding timeZone:mTimeZone];
- }
- else {
- result = [[MCPResult alloc] init];
- }
- }
-
- [self unlockConnection];
-
- if (result) [result autorelease];
-
- return result;
-}
-
-/**
- * Kills the process with the given pid.
- * The users needs the !{Process_priv} privilege.
- */
-- (BOOL)killProcess:(unsigned long)pid
-{
- NSInteger theErrorCode = mysql_kill(mConnection, pid);
-
- return (theErrorCode) ? NO : YES;
-}
-
-/*
- * Check some common locations for the presence of a MySQL socket file, returning
- * it if successful.
- */
-- (NSString *)findSocketPath
-{
- NSFileManager *fileManager = [NSFileManager defaultManager];
-
- NSArray *possibleSocketLocations = [NSArray arrayWithObjects:
- @"/tmp/mysql.sock", // Default
- @"/Applications/MAMP/tmp/mysql/mysql.sock", // MAMP default location
- @"/Applications/xampp/xamppfiles/var/mysql/mysql.sock", // XAMPP default location
- @"/var/mysql/mysql.sock", // Mac OS X Server default
- @"/opt/local/var/run/mysqld/mysqld.sock", // Darwinports MySQL
- @"/opt/local/var/run/mysql4/mysqld.sock", // Darwinports MySQL 4
- @"/opt/local/var/run/mysql5/mysqld.sock", // Darwinports MySQL 5
- @"/usr/local/zend/mysql/tmp/mysql.sock", // Zend Server CE (see Issue #1251)
- @"/var/run/mysqld/mysqld.sock", // As used on Debian/Gentoo
- @"/var/tmp/mysql.sock", // As used on FreeBSD
- @"/var/lib/mysql/mysql.sock", // As used by Fedora
- @"/opt/local/lib/mysql/mysql.sock", // Alternate fedora
- nil];
-
- for (NSUInteger i = 0; i < [possibleSocketLocations count]; i++)
- {
- if ([fileManager fileExistsAtPath:[possibleSocketLocations objectAtIndex:i]])
- return [possibleSocketLocations objectAtIndex:i];
- }
-
- return nil;
-}
-
-#pragma mark -
-#pragma mark Encoding
-
-/**
- * Sets the encoding for the database connection.
- * This sends a "SET NAMES" command to the server, as appropriate, and
- * also updates the class to decode the returned strings correctly.
- * If an encoding name unsupported by MySQL is encountered, a FALSE
- * status will be returned, and errors will be updated.
- * If an encoding name not supported by this class is encountered, a
- * warning will be logged to console but the MySQL connection will still
- * be updated.
- * This resets any setting to use Latin1 transport for the connection.
- */
-- (BOOL)setEncoding:(NSString *)theEncoding
-{
- if ([theEncoding isEqualToString:encoding] && !encodingUsesLatin1Transport) return YES;
-
- // MySQL < 4.1 will fail
- if ([self serverMajorVersion] < 4
- || ([self serverMinorVersion] == 4 && [self serverMinorVersion] < 1))
- {
- return NO;
- }
-
- // Attempt to set the encoding of the connection, restoring the connection on failure
- [self queryString:[NSString stringWithFormat:@"SET NAMES %@", [theEncoding tickQuotedString]]];
- if ([self queryErrored]) {
- [self queryString:[NSString stringWithFormat:@"SET NAMES %@", [encoding tickQuotedString]]];
- if (encodingUsesLatin1Transport) [self queryString:@"SET CHARACTER_SET_RESULTS=latin1"];
- return NO;
- }
-
- // The connection set was successful - update stored details
- [encoding release];
- encoding = [[NSString alloc] initWithString:theEncoding];
- stringEncoding = [MCPConnection encodingForMySQLEncoding:[encoding UTF8String]];
- encodingUsesLatin1Transport = NO;
- return YES;
-}
-
-/**
- * Returns the currently active encoding.
- */
-- (NSString *)encoding
-{
- return [NSString stringWithString:encoding];
-}
-
-/**
- * Gets the string encoding for the connection
- */
-- (NSStringEncoding)stringEncoding
-{
- return stringEncoding;
-}
-
-/**
- * Sets whether the connection encoding should be transmitted via Latin1.
- * This is a method purely for backwards compatibility: old codebases or
- * applications often believed they stored UTF8 data in UTF8 tables, but
- * for the purposes of storing and reading the data, the MySQL connecttion
- * was never changed from the default Latin1. UTF8 data was therefore
- * altered during transit and stored as UTF8 encoding Latin1 pairs which
- * together make up extended UTF8 characters. Reading these characters back
- * over Latin1 makes the data editable in a compatible fashion.
- */
-- (BOOL)setEncodingUsesLatin1Transport:(BOOL)useLatin1
-{
- if (encodingUsesLatin1Transport == useLatin1) return YES;
-
- // If disabling Latin1 transport, restore the connection encoding
- if (!useLatin1) return [self setEncoding:encoding];
-
- // Otherwise attempt to set Latin1 transport
- [self queryString:@"SET CHARACTER_SET_RESULTS=latin1"];
- if ([self queryErrored]) return NO;
- [self queryString:@"SET CHARACTER_SET_CLIENT=latin1"];
- if ([self queryErrored]) {
- [self setEncoding:encoding];
- return NO;
- }
- encodingUsesLatin1Transport = YES;
- return YES;
-}
-
-/**
- * Return whether the current connection is set to use Latin1 tranport.
- */
-- (BOOL)encodingUsesLatin1Transport
-{
- return encodingUsesLatin1Transport;
-}
-
-/**
- * Store a previous encoding setting. This allows easy restoration
- * later - useful if certain tasks require the encoding to be
- * temporarily changed.
- */
-- (void)storeEncodingForRestoration
-{
- if (previousEncoding) [previousEncoding release];
- previousEncoding = [[NSString alloc] initWithString:encoding];
- previousEncodingUsesLatin1Transport = encodingUsesLatin1Transport;
-}
-
-/**
- * Restore a previously stored encoding setting, if one is stored.
- * Useful if certain tasks required the encoding to be temporarily changed.
- */
-- (void)restoreStoredEncoding
-{
- if (!previousEncoding || !mConnected) return;
-
- [self setEncoding:previousEncoding];
- [self setEncodingUsesLatin1Transport:previousEncodingUsesLatin1Transport];
-}
-
-#pragma mark -
-#pragma mark Time Zone
-
-/**
- * Setting the time zone to be used with the server.
- */
-- (void)setTimeZone:(NSTimeZone *)iTimeZone
-{
- if (iTimeZone != mTimeZone) {
- [mTimeZone release];
- mTimeZone = [iTimeZone retain];
- }
-
- if ([self checkConnection]) {
- if (mTimeZone) {
- [self queryString:[NSString stringWithFormat:@"SET time_zone = '%@'", [mTimeZone name]]];
- }
- else {
- [self queryString:@"SET time_zone = 'SYSTEM'"];
- }
- }
-}
-
-/**
- * Getting the currently used time zone (in communication with the DB server).
- */
-- (NSTimeZone *)timeZone
-{
- if ([self checkConnection]) {
- MCPResult *theSessionTZ = [self queryString:@"SHOW VARIABLES LIKE '%time_zone'"];
- NSArray *theRow;
- id theTZName;
- NSTimeZone *theTZ;
-
- [theSessionTZ setReturnDataAsStrings:YES];
- [theSessionTZ dataSeek:1ULL];
- theRow = [theSessionTZ fetchRowAsArray];
- theTZName = [theRow objectAtIndex:1];
-
- if ([theTZName isEqualToString:@"SYSTEM"]) {
- [theSessionTZ dataSeek:0ULL];
- theRow = [theSessionTZ fetchRowAsArray];
- theTZName = [theRow objectAtIndex:1];
- }
-
- if (theTZName) { // Old versions of the server does not support there own time zone ?
- theTZ = [NSTimeZone timeZoneWithName:theTZName];
- if (!theTZ) theTZ = [NSTimeZone timeZoneWithAbbreviation:theTZName];
- if (!theTZ) theTZ = [NSTimeZone defaultTimeZone];
- } else {
- // By default set the time zone to the local one..
- // Try to get the name using the previously available variable:
- theSessionTZ = [self queryString:@"SHOW VARIABLES LIKE 'timezone'"];
- [theSessionTZ setReturnDataAsStrings:YES];
- [theSessionTZ dataSeek:0ULL];
- theRow = [theSessionTZ fetchRowAsArray];
- theTZName = [theRow objectAtIndex:1];
- if (theTZName) {
- // Finally we found one ...
- theTZ = [NSTimeZone timeZoneWithName:theTZName];
- if (!theTZ) theTZ = [NSTimeZone timeZoneWithAbbreviation:theTZName];
- if (!theTZ) theTZ = [NSTimeZone defaultTimeZone];
- } else {
- theTZ = [NSTimeZone defaultTimeZone];
- //theTZ = [NSTimeZone systemTimeZone];
- NSLog(@"The time zone is not defined on the server, set it to the default one : %@", theTZ);
- }
- }
-
- if (theTZ != mTimeZone) {
- [mTimeZone release];
- mTimeZone = [theTZ retain];
- }
- }
-
- return mTimeZone;
-}
-
-#pragma mark -
-#pragma mark Packet size
-
-/**
- * Retrieve the max_allowed_packet size from the server; returns
- * false if the query fails.
- */
-- (BOOL)fetchMaxAllowedPacket
-{
- char *queryString;
-
- if ([self serverMajorVersion] == 3) queryString = "SHOW VARIABLES LIKE 'max_allowed_packet'";
- else queryString = "SELECT @@global.max_allowed_packet";
-
- [self lockConnection];
- if (0 == mysql_query(mConnection, queryString)) {
- if (mysql_field_count(mConnection) != 0) {
- MCPResult *r = [[MCPResult alloc] initWithMySQLPtr:mConnection encoding:stringEncoding timeZone:mTimeZone];
- [r setReturnDataAsStrings:YES];
- NSArray *a = [r fetchRowAsArray];
- [r autorelease];
- if([a count]) {
- [self unlockConnection];
- maxAllowedPacketSize = [[a objectAtIndex:([self serverMajorVersion] == 3)?1:0] integerValue];
- return true;
- }
- }
- }
- [self unlockConnection];
-
- return false;
-}
-
-/**
- * Retrieves max_allowed_packet size set as global variable.
- * It returns NSNotFound if it fails.
- */
-- (NSUInteger)getMaxAllowedPacket
-{
- MCPResult *r;
- r = [self queryString:@"SELECT @@global.max_allowed_packet" usingEncoding:stringEncoding streamingResult:NO];
- if (![[self getLastErrorMessage] isEqualToString:@""]) {
- if ([self isConnected]) {
- NSString *errorMessage = [NSString stringWithFormat:@"An error occured while retrieving max_allowed_packet size:\n\n%@", [self getLastErrorMessage]];
- if ([delegate respondsToSelector:@selector(showErrorWithTitle:message:)])
- [delegate showErrorWithTitle:NSLocalizedString(@"Error", @"error") message:errorMessage];
- else
- NSRunAlertPanel(@"Error", errorMessage, @"OK", nil, nil);
- }
- return NSNotFound;
- }
- NSArray *a = [r fetchRowAsArray];
- if([a count])
- return [[a objectAtIndex:0] integerValue];
-
- return NSNotFound;
-}
-
-/*
- * It sets max_allowed_packet size to newSize and it returns
- * max_allowed_packet after setting it to newSize for cross-checking
- * if the maximal size was reached (e.g. set it to 4GB it'll return 1GB up to now).
- * If something failed it return -1;
- */
-- (NSUInteger)setMaxAllowedPacketTo:(NSUInteger)newSize resetSize:(BOOL)reset
-{
- if(![self isMaxAllowedPacketEditable] || newSize < 1024) return maxAllowedPacketSize;
-
- [self lockConnection];
- mysql_query(mConnection, [[NSString stringWithFormat:@"SET GLOBAL max_allowed_packet = %lu", newSize] UTF8String]);
- [self unlockConnection];
-
- // Inform the user via a log entry about that change according to reset value
- if(delegate && [delegate respondsToSelector:@selector(queryGaveError:connection:)]) {
- if(reset)
- [delegate queryGaveError:[NSString stringWithFormat:@"max_allowed_packet was reset to %lu for new session", newSize] connection:self];
- else
- [delegate queryGaveError:[NSString stringWithFormat:@"Query too large; max_allowed_packet temporarily set to %lu for the current session to allow query to succeed", newSize] connection:self];
- }
-
- return maxAllowedPacketSize;
-}
-
-/**
- * It returns whether max_allowed_packet is setable for the user.
- */
-- (BOOL)isMaxAllowedPacketEditable
-{
- BOOL isEditable;
-
- [self lockConnection];
- isEditable = !mysql_query(mConnection, "SET GLOBAL max_allowed_packet = @@global.max_allowed_packet");
- [self unlockConnection];
-
- return isEditable;
-}
-
-#pragma mark -
-#pragma mark Data conversion
-
-/**
- * For internal use only. Transforms a NSString to a C type string (ending with \0) using the character set from the MCPConnection.
- * Lossy conversions are enabled.
- */
-- (const char *)cStringFromString:(NSString *)theString
-{
- NSMutableData *theData;
-
- if (! theString) {
- return (const char *)NULL;
- }
-
- theData = [NSMutableData dataWithData:[theString dataUsingEncoding:stringEncoding allowLossyConversion:YES]];
- [theData increaseLengthBy:1];
-
- return (const char *)[theData bytes];
-}
-
-/**
- * Modified version of the original to support a supplied encoding.
- * For internal use only. Transforms a NSString to a C type string (ending with \0).
- * Lossy conversions are enabled.
- */
-- (const char *)cStringFromString:(NSString *)theString usingEncoding:(NSStringEncoding)aStringEncoding
-{
- NSMutableData *theData;
-
- if (! theString) {
- return (const char *)NULL;
- }
-
- theData = [NSMutableData dataWithData:[theString dataUsingEncoding:aStringEncoding allowLossyConversion:YES]];
- [theData increaseLengthBy:1];
-
- return (const char *)[theData bytes];
-}
-
-/**
- * Returns a NSString from a C style string encoded with the character set of theMCPConnection.
- */
-- (NSString *)stringWithCString:(const char *)theCString
-{
- NSData *theData;
- NSString *theString;
-
- if (theCString == NULL) return @"";
-
- theData = [NSData dataWithBytes:theCString length:(strlen(theCString))];
- theString = [[NSString alloc] initWithData:theData encoding:stringEncoding];
-
- if (theString) {
- [theString autorelease];
- }
-
- return theString;
-}
-
-/**
- * Returns a NSString from a C style string.
- */
-- (NSString *)stringWithCString:(const char *)theCString usingEncoding:(NSStringEncoding)aStringEncoding
-{
- NSData *theData;
- NSString *theString;
-
- if (theCString == NULL) return @"";
-
- theData = [NSData dataWithBytes:theCString length:(strlen(theCString))];
- theString = [[NSString alloc] initWithData:theData encoding:aStringEncoding];
-
- if (theString) {
- [theString autorelease];
- }
-
- return theString;
-}
-
-/**
- * Returns a NSString from a C style string encoded with the character set of theMCPConnection.
- */
-- (NSString *)stringWithUTF8CString:(const char *)theCString
-{
- NSData *theData;
- NSString *theString;
-
- if (theCString == NULL) return @"";
-
- theData = [NSData dataWithBytes:theCString length:(strlen(theCString))];
- theString = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
-
- if (theString) {
- [theString autorelease];
- }
-
- return theString;
-}
-
-/**
- * Use the string encoding to convert the returned NSData to a string (for a Text field).
- */
-- (NSString *)stringWithText:(NSData *)theTextData
-{
- NSString *theString;
-
- if (theTextData == nil) return nil;
-
- theString = [[NSString alloc] initWithData:theTextData encoding:stringEncoding];
-
- if (theString) {
- [theString autorelease];
- }
-
- return theString;
-}
-
-#pragma mark -
-
-/**
- * Object deallocation.
- */
-- (void) dealloc
-{
- delegate = nil;
-
- // Ensure the query lock is unlocked, thereafter setting to nil in case of pending calls
- if ([connectionLock condition] != MCPConnectionIdle) [self unlockConnection];
- [connectionLock release], connectionLock = nil;
-
- // Clean up connections if necessary
- if (mConnected) [self disconnect];
- if (connectionProxy) {
- [connectionProxy setConnectionStateChangeSelector:NULL delegate:nil];
- [connectionProxy disconnect];
- }
-
- [encoding release];
- if (previousEncoding) [previousEncoding release];
- [keepAliveTimer invalidate];
- [keepAliveTimer release];
- [NSObject cancelPreviousPerformRequestsWithTarget:self];
- if (lastQueryErrorMessage) [lastQueryErrorMessage release];
- if (connectionHost) [connectionHost release];
- if (connectionLogin) [connectionLogin release];
- if (connectionSocket) [connectionSocket release];
- if (connectionPassword) [connectionPassword release];
- if (sslKeyFilePath) [sslKeyFilePath release];
- if (sslCertificatePath) [sslCertificatePath release];
- if (sslCACertificatePath) [sslCACertificatePath release];
- if (serverVersionString) [serverVersionString release], serverVersionString = nil;
- if (structure) [structure release], structure = nil;
- if (allKeysofDbStructure) [allKeysofDbStructure release], allKeysofDbStructure = nil;
-
- [super dealloc];
-}
-
-@end
-
-@implementation MCPConnection (PrivateAPI)
-
-/**
- * Retrieve connection variables and use them to update local variables - incuding
- * server version string, server time zone, and the current connection encoding.
- */
-- (void)_updateConnectionVariables
-{
- if (!mConnected) return;
-
- // Retrieve all the variables from the server
- MCPResult *theResult = [self queryString:@"SHOW VARIABLES"];
- [theResult setReturnDataAsStrings:YES];
- if (![theResult numOfRows]) return;
-
- // Step through the rows, converting into an NSDictionary
- NSMutableDictionary *variables = [NSMutableDictionary new];
- NSArray *variableRow = nil;
- while ((variableRow = [theResult fetchRowAsArray])) {
- [variables setObject:[variableRow objectAtIndex:1] forKey:[variableRow objectAtIndex:0]];
- }
-
- // Get the version string
- if (serverVersionString) [serverVersionString release], serverVersionString = nil;
- if ([variables objectForKey:@"version"]) {
- serverVersionString = [[NSString alloc] initWithString:[variables objectForKey:@"version"]];
- }
-
- // Get the timezone
- NSString *serverTimeZoneName = nil;
- NSTimeZone *serverTimeZone = nil;
- if ([variables objectForKey:@"time_zone"] && ![[variables objectForKey:@"time_zone"] isNSNull]) {
- if ([[variables objectForKey:@"time_zone"] isEqualToString:@"SYSTEM"]) {
- if ([variables objectForKey:@"system_time_zone"]) {
- serverTimeZoneName = [variables objectForKey:@"system_time_zone"];
- }
- } else {
- serverTimeZoneName = [variables objectForKey:@"time_zone"];
- }
- } else if ([variables objectForKey:@"timezone"] && ![[variables objectForKey:@"timezone"] isNSNull]) {
- serverTimeZoneName = [variables objectForKey:@"timezone"];
- }
- if (!serverTimeZoneName) {
- serverTimeZone = [NSTimeZone defaultTimeZone];
- NSLog(@"The time zone was not defined on the server, fallen back to default time zone: %@", serverTimeZone);
- } else {
- serverTimeZone = [NSTimeZone timeZoneWithName:serverTimeZoneName];
- if (!serverTimeZone)
- serverTimeZone = [NSTimeZone timeZoneWithAbbreviation:serverTimeZoneName];
- if (!serverTimeZone) {
- serverTimeZone = [NSTimeZone defaultTimeZone];
- NSLog(@"The time zone defined on the server (%@) was not recognised, fallen back to default time zone: %@", serverTimeZoneName, serverTimeZone);
- }
- }
-
- if (mTimeZone) [mTimeZone release], mTimeZone = nil;
- mTimeZone = [serverTimeZone retain];
-
- // Get the connection encoding
- NSString *serverEncoding = @"latin1";
- if ([variables objectForKey:@"character_set_results"]) {
- serverEncoding = [variables objectForKey:@"character_set_results"];
- } else if ([variables objectForKey:@"character_set"]) {
- serverEncoding = [variables objectForKey:@"character_set"];
- }
- if (encoding) [encoding release];
- encoding = [[NSString alloc] initWithString:serverEncoding];
- stringEncoding = [MCPConnection encodingForMySQLEncoding:[self cStringFromString:encoding]];
- encodingUsesLatin1Transport = NO;
-
- // Check the interactive timeout - if it's below five minutes, increase it to ten to imprive timeout/keepalive behaviour
- if ([variables objectForKey:@"interactive_timeout"]) {
- if ([[variables objectForKey:@"interactive_timeout"] integerValue] < 300) {
- [self queryString:@"SET interactive_timeout=600"];
- }
- }
-
- [variables release];
-}
-
-/**
- * Determine whether the current host is reachable; essentially
- * whether a connection is available (no packets should be sent)
- */
-- (BOOL)_isCurrentHostReachable
-{
- BOOL hostReachable;
- SCNetworkConnectionFlags reachabilityStatus;
- hostReachable = SCNetworkCheckReachabilityByName("dev.mysql.com", &reachabilityStatus);
-
- // If the function returned failure, also return failure.
- if (!hostReachable) return NO;
-
- // Ensure that the network is reachable
- if (!(reachabilityStatus & kSCNetworkFlagsReachable)) return NO;
-
- // Ensure that Airport is up/connected if present
- if (reachabilityStatus & kSCNetworkFlagsConnectionRequired) return NO;
-
- // Return success
- return YES;
-}
-
-/**
- * Set up the keepalive timer; this should be called on the main
- * thread, to ensure the timer isn't descheduled when child threads
- * terminate.
- */
-- (void)_setupKeepalivePingTimer
-{
- keepAliveTimer = [[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(keepAlive:) userInfo:nil repeats:YES] retain];
-}
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPConnectionDelegate.h b/Frameworks/MCPKit/MCPFoundationKit/MCPConnectionDelegate.h
deleted file mode 100644
index 0e162875..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPConnectionDelegate.h
+++ /dev/null
@@ -1,81 +0,0 @@
-//
-// $Id$
-//
-// MCPConnectionDelegate.h
-// MCPKit
-//
-// Created by Stuart Connolly (stuconnolly.com) on October 20, 2010.
-// Copyright (c) 2010 Stuart Connolly. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-@protocol MCPConnectionDelegate <NSObject>
-
-/**
- *
- * @param query
- * @param connection
- */
-- (void)willQueryString:(NSString *)query connection:(id)connection;
-
-/**
- *
- * @param error
- * @param connection
- */
-- (void)queryGaveError:(NSString *)error connection:(id)connection;
-
-/**
- *
- *
- * @param error
- * @param message
- */
-- (void)showErrorWithTitle:(NSString *)error message:(NSString *)message;
-
-/**
- *
- *
- * @param connection
- */
-- (NSString *)keychainPasswordForConnection:(id)connection;
-
-/**
- *
- *
- * @param connection
- */
-- (NSString *)onReconnectShouldSelectDatabase:(id)connection;
-
-/**
- *
- *
- * @param connection
- */
-- (void)noConnectionAvailable:(id)connection;
-
-/**
- *
- *
- * @param connection
- */
-- (MCPConnectionCheck)connectionLost:(id)connection;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPConnectionProxy.h b/Frameworks/MCPKit/MCPFoundationKit/MCPConnectionProxy.h
deleted file mode 100644
index f4edbfd8..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPConnectionProxy.h
+++ /dev/null
@@ -1,70 +0,0 @@
-//
-// $Id$
-//
-// MCPConnectionProxy.h
-// MCPKit
-//
-// Created by Stuart Connolly (stuconnolly.com) on July 2, 2009.
-// Copyright (c) 2009 Stuart Connolly. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-/**
- * Connection proxy state constants.
- */
-enum PROXY_TUNNEL_STATES
-{
- PROXY_STATE_IDLE = 0,
- PROXY_STATE_CONNECTING = 1,
- PROXY_STATE_WAITING_FOR_AUTH = 2,
- PROXY_STATE_CONNECTED = 3,
- PROXY_STATE_FORWARDING_FAILED = 4
-};
-
-@protocol MCPConnectionProxy <NSObject>
-
-/**
- * Connect the proxy.
- */
-- (void)connect;
-
-/**
- * Disconnect the proxy.
- */
-- (void)disconnect;
-
-/**
- * Get the current state of the proxy.
- */
-- (NSInteger)state;
-
-/**
- * Get the local port being used by the proxy.
- */
-- (NSUInteger)localPort;
-
-/**
- * Sets the method the proxy should call whenever the state of the connection changes.
- */
-- (BOOL)setConnectionStateChangeSelector:(SEL)theStateChangeSelector delegate:(id)theDelegate;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPConstants.h b/Frameworks/MCPKit/MCPFoundationKit/MCPConstants.h
deleted file mode 100644
index fba7d651..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPConstants.h
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// $Id$
-//
-// MCPConstants.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 03/06/2001.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-// Result type constants
-enum {
- MCPTypeArray = 1,
- MCPTypeDictionary = 2,
- MCPTypeFlippedArray = 3,
- MCPTypeFlippedDictionary = 4
-};
-typedef NSUInteger MCPReturnType;
-
-// Connection check constants
-enum {
- MCPConnectionCheckRetry = 0,
- MCPConnectionCheckReconnect = 1,
- MCPConnectionCheckDisconnect = 2
-};
-typedef NSUInteger MCPConnectionCheck;
-
-// Streaming result set constants
-enum
-{
- MCPStreamingNone = 0,
- MCPStreamingFast = 1,
- MCPStreamingLowMem = 2
-};
-typedef NSUInteger MCPQueryStreamingType;
-
-// Connection state
-// This is used internally by MCPConnection to prevent simultaneous execution of different queries
-enum {
- MCPConnectionIdle = 0,
- MCPConnectionBusy = 1
-};
-
-// Charcater set mapping constants
-typedef struct _OUR_CHARSET
-{
- NSUInteger nr;
- const char *name;
- const char *collation;
- NSUInteger char_minlen;
- NSUInteger char_maxlen;
-} OUR_CHARSET;
-
-// Deafult connection option
-extern const NSUInteger kMCPConnectionDefaultOption;
-
-// Default socket (from the mysql.h used at compile time)
-extern const char *kMCPConnectionDefaultSocket;
-
-// Added to MySQL error code
-extern const NSUInteger kMCPConnectionNotInited;
-
-// The length of the truncation if required
-extern const NSUInteger kLengthOfTruncationForLog;
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.h b/Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.h
deleted file mode 100644
index e9ced5a0..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.h
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// $Id$
-//
-// MCPFastQueries.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 03/06/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-#import "MCPConnection.h"
-
-@interface MCPConnection (MCPFastQueries)
-
-// For insert queries, get directly the Id of the newly inserted row.
-- (my_ulonglong)insertQuery:(NSString *)query;
-- (my_ulonglong)updateQuery:(NSString *)query;
-
-// Returns directly a proper NS object, or a collection (NSArray, NSDictionary...).
-- (id)getFirstFieldFromQuery:(NSString *)query;
-- (id)getFirstRowFromQuery:(NSString *)query asType:(MCPReturnType)type;
-- (id)getAllRowsFromQuery:(NSString *)query asType:(MCPReturnType)type;
-- (NSArray *)getQuery:(NSString *)query colWithIndex:(NSUInteger)col;
-- (NSArray *)getQuery:(NSString *)query colWithName:(NSString *)colName;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.m b/Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.m
deleted file mode 100644
index c5f4d361..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPFastQueries.m
+++ /dev/null
@@ -1,113 +0,0 @@
-//
-// $Id$
-//
-// MCPFastQueries.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 03/06/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPFastQueries.h"
-#import "MCPResultPlus.h"
-
-/**
- * This actegory is made up to keep the extra methods out or the core of the framework.
- *
- * Basicly this is the place to add methods which are useful, but are just wrappers to the methods of the
- * core (MCPConnection, MCPResult). The purpous being to have a single line call available for current tasks
- * which otherwise would need a couple of lines and object defined.
- */
-@implementation MCPConnection (MCPFastQueries)
-
-/**
- * Send the query aQuery to the server and retrieve the row id if the table have a autoincrement column.
- * Returns 0 if nothing have been inserted.
- */
-- (my_ulonglong)insertQuery:(NSString *)query
-{
- [self queryString:query];
-
- return [self insertId];
-}
-
-/**
- * Send the query aQuery to the server and retrieve the number of affected rows (should work with !{update},
- * !{delete}, !{insert} and !{select} type of queries).
- *
- * NB: This can also be used with a !{select} query if you are only interested in the number of row complying
- * with the query; you'll get no chance to get the result from the query, except by sending the query
- * again (with !{queryString:})
- */
-- (my_ulonglong)updateQuery:(NSString *)query
-{
- [self queryString:query];
-
- return [self affectedRows];
-}
-
-/**
- * Get the first field of the first row of the result from the query (aQuery). Should return nil if no object
- * at all are selected.
- */
-- (id)getFirstFieldFromQuery:(NSString *)query
-{
- return [[[self queryString:query] fetchRowAsType:MCPTypeArray] objectAtIndex:0];
-}
-
-/**
- * Get the firdst row of the result from the query aQuery, in a collection of type determined by aType
- * (MCPTypeArray or MCPTypeDictionary)
- */
-- (id) getFirstRowFromQuery:(NSString *)query asType:(MCPReturnType)type
-{
- return [[self queryString:query] fetchRowAsType:type];
-}
-
-/**
- * Get a bidimensional table of the whole rows of the result from the query aQuery. The type of the result is
- * choosen by aType, it can be (MCPTypeArray, MCPTypeDictionary, MCPTypeFlippedArray & MCPTypeFlippedDictionary).
- * Description of the types can be found in method !{fetch2DResultAsType:}.
- */
-- (id)getAllRowsFromQuery:(NSString *)query asType:(MCPReturnType)type
-
-{
- return [[self queryString:query] fetch2DResultAsType:type];
-}
-
-/**
- * Get a column (as an NSArray) of the result from the query aQuery. The column is choosen from it's index,
- * starting from 0.
- */
-- (NSArray *)getQuery:(NSString *)query colWithIndex:(NSUInteger)col
-{
- return [[self queryString:query] fetchColAtIndex:col];
-}
-
-/**
- * Get a column (as an NSArray) of the result from the query aQuery. The column is choosen from it's name.
- */
-- (NSArray *)getQuery:(NSString *)query colWithName:(NSString *)colName
-{
- return [[self queryString:query] fetchColWithName:colName];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.h b/Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.h
deleted file mode 100644
index 9af3fcfe..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.h
+++ /dev/null
@@ -1,65 +0,0 @@
-//
-// $Id$
-//
-// MCPGeometryData.h
-// sequel-pro
-//
-// Created by Hans-Jörg Bibiko on October 07, 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 <Cocoa/Cocoa.h>
-#import <Foundation/Foundation.h>
-
-enum wkbType
-{
- wkb_point = 1,
- wkb_linestring = 2,
- wkb_polygon = 3,
- wkb_multipoint = 4,
- wkb_multilinestring = 5,
- wkb_multipolygon = 6,
- wkb_geometrycollection = 7
-};
-
-typedef struct st_point_2d_
-{
- double x;
- double y;
-} st_point_2d;
-
-@interface MCPGeometryData : NSObject
-{
- // Holds the WKB bytes coming from SQL server
- Byte *geoBuffer;
-
- // Holds the buffer length
- NSUInteger bufferLength;
-
-}
-
-- (id)initWithBytes:(const void *)geoData length:(NSUInteger)length;
-+ (id)dataWithBytes:(const void *)geoData length:(NSUInteger)length;
-- (NSString*)description;
-- (NSUInteger)length;
-- (NSData*)data;
-- (NSString*)wktString;
-- (NSDictionary*)coordinates;
-- (NSInteger)wkbType;
-- (NSString*)wktType;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.m b/Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.m
deleted file mode 100644
index b7a3fd09..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPGeometryData.m
+++ /dev/null
@@ -1,785 +0,0 @@
-//
-// $Id$
-//
-// MCPGeometryData.m
-// sequel-pro
-//
-// Created by Hans-Jörg Bibiko on October 07, 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 "MCPGeometryData.h"
-
-#define SIZEOF_STORED_UINT32 4
-#define SIZEOF_STORED_DOUBLE 8
-#define POINT_DATA_SIZE (SIZEOF_STORED_DOUBLE*2)
-#define WKB_HEADER_SIZE (1+SIZEOF_STORED_UINT32)
-#define BUFFER_START 0
-
-@implementation MCPGeometryData
-
-/**
- * Initialize the MCPGeometryData object
- */
-- (id)init
-{
- if ((self = [super init])) {
- geoBuffer = nil;
- bufferLength = 0;
- }
- return self;
-}
-
-/**
- * Initialize the MCPGeometryData object with the WKB data
- */
-- (id)initWithBytes:(const void *)geoData length:(NSUInteger)length
-{
- if ((self = [self init])) {
- bufferLength = length;
- geoBuffer = malloc(bufferLength);
- memcpy(geoBuffer, geoData, bufferLength);
- }
- return self;
-}
-
-/**
- * Return an autorelease MCPGeometryData object
- */
-+ (id)dataWithBytes:(const void *)geoData length:(NSUInteger)length
-{
- return [[[MCPGeometryData alloc] initWithBytes:geoData length:length] autorelease];
-}
-
-/**
- * copyWithZone
- */
-- (id)copyWithZone:(NSZone *)zone
-{
- return [self retain];
-}
-
-/**
- * Return the hex representation of the WKB buffer (only for convenience)
- */
-- (NSString*)description
-{
- return [[NSData dataWithBytes:geoBuffer length:bufferLength] description];
-}
-
-/**
- * Return the length of the WKB buffer
- */
-- (NSUInteger)length
-{
- return bufferLength;
-}
-
-/**
- * Return NSData pointer of the WKB buffer
- */
-- (NSData*)data
-{
- return [NSData dataWithBytes:geoBuffer length:bufferLength];
-}
-
-/**
- * Return a human readable WKT string of the internal format (it imitate the SQL function AsText()).
- */
-- (NSString*)wktString
-{
- char byteOrder;
- uint32_t geoType, numberOfItems, numberOfSubItems, numberOfSubSubItems, numberOfCollectionItems;
- int32_t srid;
- st_point_2d aPoint;
-
- uint32_t i, j, k, n; // Loop counter for numberOf...Items
- uint32_t ptr = BUFFER_START; // pointer to geoBuffer while parsing
-
- NSMutableString *wkt = [NSMutableString string];
-
- if (bufferLength < WKB_HEADER_SIZE)
- return @"";
-
- memcpy(&srid, &geoBuffer[0], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
-
- byteOrder = geoBuffer[ptr];
-
- if(byteOrder != 0x1)
- return @"Byte order not yet supported";
-
- ptr++;
- geoType = geoBuffer[ptr];
- ptr += SIZEOF_STORED_UINT32;
-
- switch(geoType) {
-
- case wkb_point:
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- return [NSString stringWithFormat:@"POINT(%.16g %.16g)%@", aPoint.x, aPoint.y, (srid) ? [NSString stringWithFormat:@",%d",srid]: @""];
- break;
-
- case wkb_linestring:
- [wkt setString:@"LINESTRING("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (i < numberOfItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- [wkt appendFormat:@")%@", (srid) ? [NSString stringWithFormat:@",%d",srid]: @""];
- return wkt;
- break;
-
- case wkb_polygon:
- [wkt setString:@"POLYGON("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (j < numberOfSubItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- [wkt appendFormat:@")%@", (i < numberOfItems-1) ? @"," : @""];
- }
- [wkt appendFormat:@")%@", (srid) ? [NSString stringWithFormat:@",%d",srid]: @""];
- return wkt;
- break;
-
- case wkb_multipoint:
- [wkt setString:@"MULTIPOINT("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (i < numberOfItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE+WKB_HEADER_SIZE;
- }
- [wkt appendFormat:@")%@", (srid) ? [NSString stringWithFormat:@",%d",srid]: @""];
- return wkt;
- break;
-
- case wkb_multilinestring:
- [wkt setString:@"MULTILINESTRING("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (j < numberOfSubItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- ptr += WKB_HEADER_SIZE;
- [wkt appendFormat:@")%@", (i < numberOfItems-1) ? @"," : @""];
- }
- [wkt appendFormat:@")%@", (srid) ? [NSString stringWithFormat:@",%d",srid]: @""];
- return wkt;
- break;
-
- case wkb_multipolygon:
- [wkt setString:@"MULTIPOLYGON("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&numberOfSubSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(k=0; k < numberOfSubSubItems; k++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (k < numberOfSubSubItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- [wkt appendFormat:@")%@", (j < numberOfSubItems-1) ? @"," : @""];
- }
- ptr += WKB_HEADER_SIZE;
- [wkt appendFormat:@")%@", (i < numberOfItems-1) ? @"," : @""];
- }
- [wkt appendFormat:@")%@", (srid) ? [NSString stringWithFormat:@",%d",srid]: @""];
- return wkt;
- break;
-
- case wkb_geometrycollection:
- [wkt setString:@"GEOMETRYCOLLECTION("];
- numberOfCollectionItems = geoBuffer[ptr];
- ptr += SIZEOF_STORED_UINT32;
-
- for(n=0; n < numberOfCollectionItems; n++) {
-
- byteOrder = geoBuffer[ptr];
-
- if(byteOrder != 0x1)
- return @"Byte order not yet supported";
-
- ptr++;
- geoType = geoBuffer[ptr];
- ptr += SIZEOF_STORED_UINT32;
-
- switch(geoType) {
-
- case wkb_point:
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"POINT(%.16g %.16g)", aPoint.x, aPoint.y];
- ptr += POINT_DATA_SIZE;
- break;
-
- case wkb_linestring:
- [wkt appendString:@"LINESTRING("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (i < numberOfItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- [wkt appendString:@")"];
- break;
-
- case wkb_polygon:
- [wkt appendString:@"POLYGON("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (j < numberOfSubItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- [wkt appendFormat:@")%@", (i < numberOfItems-1) ? @"," : @""];
- }
- [wkt appendString:@")"];
- break;
-
- case wkb_multipoint:
- [wkt appendString:@"MULTIPOINT("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (i < numberOfItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE+WKB_HEADER_SIZE;
- }
- ptr -= WKB_HEADER_SIZE;
- [wkt appendString:@")"];
- break;
-
- case wkb_multilinestring:
- [wkt appendString:@"MULTILINESTRING("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (j < numberOfSubItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- ptr += WKB_HEADER_SIZE;
- [wkt appendFormat:@")%@", (i < numberOfItems-1) ? @"," : @""];
- }
- ptr -= WKB_HEADER_SIZE;
- [wkt appendString:@")"];
- break;
-
- case wkb_multipolygon:
- [wkt appendString:@"MULTIPOLYGON("];
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&numberOfSubSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- [wkt appendString:@"("];
- for(k=0; k < numberOfSubSubItems; k++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- [wkt appendFormat:@"%.16g %.16g%@", aPoint.x, aPoint.y, (k < numberOfSubSubItems-1) ? @"," : @""];
- ptr += POINT_DATA_SIZE;
- }
- [wkt appendFormat:@")%@", (j < numberOfSubItems-1) ? @"," : @""];
- }
- ptr += WKB_HEADER_SIZE;
- [wkt appendFormat:@")%@", (i < numberOfItems-1) ? @"," : @""];
- }
- ptr -= WKB_HEADER_SIZE;
- [wkt appendString:@")"];
- break;
-
- default:
- return @"Error geometrycollection type parsing";
- }
- [wkt appendString:(n < numberOfCollectionItems-1) ? @"," : @""];
- }
- [wkt appendFormat:@")%@", (srid) ? [NSString stringWithFormat:@",%d",srid]: @""];
- return wkt;
- break;
-
- default:
- return @"Error geometry type parsing";
- }
- return @"Error while parsing";
-}
-
-/**
- * Return a dictionary of coordinates, bbox, etc. to be able to draw the given geometry.
- *
- * @return A dictionary having the following keys: "bbox" as NSArray of NSNumbers of x_min x_max y_min y_max, "coordinates" as NSArray containing the
- * the to be drawn points as NSPoint strings, "type" as NSString
- */
-- (NSDictionary*)coordinates
-{
-
- char byteOrder;
- uint32_t geoType, numberOfItems, numberOfSubItems, numberOfSubSubItems, numberOfCollectionItems;
- int32_t srid;
- st_point_2d aPoint;
-
- uint32_t i, j, k, n; // Loop counter for numberOf...Items
- uint32_t ptr = BUFFER_START; // pointer to geoBuffer while parsing
-
- double x_min = DBL_MAX;
- double x_max = -DBL_MAX;
- double y_min = DBL_MAX;
- double y_max = -DBL_MAX;
-
- NSMutableArray *coordinates = [NSMutableArray array];
- NSMutableArray *subcoordinates = [NSMutableArray array];
- NSMutableArray *pointcoordinates = [NSMutableArray array];
- NSMutableArray *linecoordinates = [NSMutableArray array];
- NSMutableArray *linesubcoordinates = [NSMutableArray array];
- NSMutableArray *polygoncoordinates = [NSMutableArray array];
- NSMutableArray *polygonsubcoordinates = [NSMutableArray array];
-
- if (bufferLength < WKB_HEADER_SIZE)
- return nil;
-
- memcpy(&srid, &geoBuffer[0], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
-
- byteOrder = geoBuffer[ptr];
-
- if(byteOrder != 0x1)
- return nil;
-
- ptr++;
- geoType = geoBuffer[ptr];
- ptr += SIZEOF_STORED_UINT32;
-
- switch(geoType) {
-
- case wkb_point:
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = aPoint.x;
- x_max = aPoint.x;
- y_min = aPoint.y;
- y_max = aPoint.y;
- [coordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- return [NSDictionary dictionaryWithObjectsAndKeys:
- [NSArray arrayWithObjects:
- [NSNumber numberWithDouble:x_min],
- [NSNumber numberWithDouble:x_max],
- [NSNumber numberWithDouble:y_min],
- [NSNumber numberWithDouble:y_max],
- nil], @"bbox",
- coordinates, @"coordinates",
- [NSNumber numberWithInt:srid], @"srid",
- @"POINT", @"type",
- nil];
- break;
-
- case wkb_linestring:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [coordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- return [NSDictionary dictionaryWithObjectsAndKeys:
- [NSArray arrayWithObjects:
- [NSNumber numberWithDouble:x_min],
- [NSNumber numberWithDouble:x_max],
- [NSNumber numberWithDouble:y_min],
- [NSNumber numberWithDouble:y_max],
- nil], @"bbox",
- [NSArray arrayWithObjects:coordinates,nil], @"coordinates",
- @"LINESTRING", @"type",
- nil];
- break;
-
- case wkb_polygon:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [subcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- [coordinates addObject:[[subcoordinates copy] autorelease]];
- [subcoordinates removeAllObjects];
- }
- return [NSDictionary dictionaryWithObjectsAndKeys:
- [NSArray arrayWithObjects:
- [NSNumber numberWithDouble:x_min],
- [NSNumber numberWithDouble:x_max],
- [NSNumber numberWithDouble:y_min],
- [NSNumber numberWithDouble:y_max],
- nil], @"bbox",
- coordinates, @"coordinates",
- [NSNumber numberWithInt:srid], @"srid",
- @"POLYGON", @"type",
- nil];
- break;
-
- case wkb_multipoint:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [coordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE+WKB_HEADER_SIZE;
- }
- return [NSDictionary dictionaryWithObjectsAndKeys:
- [NSArray arrayWithObjects:
- [NSNumber numberWithDouble:x_min],
- [NSNumber numberWithDouble:x_max],
- [NSNumber numberWithDouble:y_min],
- [NSNumber numberWithDouble:y_max],
- nil], @"bbox",
- coordinates, @"coordinates",
- [NSNumber numberWithInt:srid], @"srid",
- @"MULTIPOINT", @"type",
- nil];
- break;
-
- case wkb_multilinestring:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [subcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- ptr += WKB_HEADER_SIZE;
- [coordinates addObject:[[subcoordinates copy] autorelease]];
- [subcoordinates removeAllObjects];
- }
- return [NSDictionary dictionaryWithObjectsAndKeys:
- [NSArray arrayWithObjects:
- [NSNumber numberWithDouble:x_min],
- [NSNumber numberWithDouble:x_max],
- [NSNumber numberWithDouble:y_min],
- [NSNumber numberWithDouble:y_max],
- nil], @"bbox",
- coordinates, @"coordinates",
- [NSNumber numberWithInt:srid], @"srid",
- @"MULTILINESTRING", @"type",
- nil];
- break;
-
- case wkb_multipolygon:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&numberOfSubSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(k=0; k < numberOfSubSubItems; k++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [subcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- [coordinates addObject:[[subcoordinates copy] autorelease]];
- [subcoordinates removeAllObjects];
- }
- ptr += WKB_HEADER_SIZE;
- }
- return [NSDictionary dictionaryWithObjectsAndKeys:
- [NSArray arrayWithObjects:
- [NSNumber numberWithDouble:x_min],
- [NSNumber numberWithDouble:x_max],
- [NSNumber numberWithDouble:y_min],
- [NSNumber numberWithDouble:y_max],
- nil], @"bbox",
- coordinates, @"coordinates",
- [NSNumber numberWithInt:srid], @"srid",
- @"MULTIPOLYGON", @"type",
- nil];
- break;
-
- case wkb_geometrycollection:
- numberOfCollectionItems = geoBuffer[ptr];
- ptr += SIZEOF_STORED_UINT32;
-
- for(n=0; n < numberOfCollectionItems; n++) {
-
- byteOrder = geoBuffer[ptr];
-
- if(byteOrder != 0x1)
- return nil;
-
- ptr++;
- geoType = geoBuffer[ptr];
- ptr += SIZEOF_STORED_UINT32;
-
- switch(geoType) {
-
- case wkb_point:
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [pointcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- break;
-
- case wkb_linestring:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [linesubcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- [linecoordinates addObject:[[linesubcoordinates copy] autorelease]];
- [linesubcoordinates removeAllObjects];
- break;
-
- case wkb_polygon:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [polygonsubcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- [polygoncoordinates addObject:[[polygonsubcoordinates copy] autorelease]];
- [polygonsubcoordinates removeAllObjects];
- }
- break;
-
- case wkb_multipoint:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [pointcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE+WKB_HEADER_SIZE;
- }
- ptr -= WKB_HEADER_SIZE;
- break;
-
- case wkb_multilinestring:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [linesubcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- [linecoordinates addObject:[[linesubcoordinates copy] autorelease]];
- [linesubcoordinates removeAllObjects];
- ptr += WKB_HEADER_SIZE;
- }
- ptr -= WKB_HEADER_SIZE;
- break;
-
- case wkb_multipolygon:
- memcpy(&numberOfItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32+WKB_HEADER_SIZE;
- for(i=0; i < numberOfItems; i++) {
- memcpy(&numberOfSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(j=0; j < numberOfSubItems; j++) {
- memcpy(&numberOfSubSubItems, &geoBuffer[ptr], SIZEOF_STORED_UINT32);
- ptr += SIZEOF_STORED_UINT32;
- for(k=0; k < numberOfSubSubItems; k++) {
- memcpy(&aPoint, &geoBuffer[ptr], POINT_DATA_SIZE);
- x_min = (aPoint.x < x_min) ? aPoint.x : x_min;
- x_max = (aPoint.x > x_max) ? aPoint.x : x_max;
- y_min = (aPoint.y < y_min) ? aPoint.y : y_min;
- y_max = (aPoint.y > y_max) ? aPoint.y : y_max;
- [polygonsubcoordinates addObject:NSStringFromPoint(NSMakePoint((CGFloat)aPoint.x, (CGFloat)aPoint.y))];
- ptr += POINT_DATA_SIZE;
- }
- [polygoncoordinates addObject:[[polygonsubcoordinates copy] autorelease]];
- [polygonsubcoordinates removeAllObjects];
- }
- ptr += WKB_HEADER_SIZE;
- }
- ptr -= WKB_HEADER_SIZE;
- break;
-
- default:
- return nil;
- }
- }
- return [NSDictionary dictionaryWithObjectsAndKeys:
- [NSArray arrayWithObjects:
- [NSNumber numberWithDouble:x_min],
- [NSNumber numberWithDouble:x_max],
- [NSNumber numberWithDouble:y_min],
- [NSNumber numberWithDouble:y_max],
- nil], @"bbox",
- [NSArray arrayWithObjects:pointcoordinates, linecoordinates, polygoncoordinates, nil], @"coordinates",
- @"GEOMETRYCOLLECTION", @"type",
- nil];
- break;
-
- default:
- return nil;
- }
- return nil;
-}
-
-/**
- * Return the WKB type of the geoBuffer ie if buffer represents a POINT, LINESTRING, etc.
- * according to stored wkbType in header file. It returns -1 if an error occurred.
- */
-- (NSInteger)wkbType
-{
- char byteOrder;
- UInt32 geoType;
-
- NSUInteger ptr = BUFFER_START; // pointer to geoBuffer while parsing
-
- if (bufferLength < WKB_HEADER_SIZE)
- return -1;
-
- byteOrder = geoBuffer[ptr];
-
- if(byteOrder != 0x1)
- return -1;
-
- ptr++;
- geoType = geoBuffer[ptr];
-
- if(geoType > 0 && geoType < 8)
- return geoType;
- else
- return -1;
-
-}
-
-/**
- * Return the WKT type of the geoBuffer ie if buffer represents a POINT, LINESTRING, etc.
- * according to stored wkbType in header file. It returns nil if an error occurred.
- */
-- (NSString*)wktType
-{
- switch([self wkbType])
- {
- case wkb_point:
- return @"POINT";
- case wkb_linestring:
- return @"LINESTRING";
- case wkb_polygon:
- return @"POLYGON";
- case wkb_multipoint:
- return @"MULTIPOINT";
- case wkb_multilinestring:
- return @"MULTILINESTRING";
- case wkb_multipolygon:
- return @"MULTIPOLYGON";
- case wkb_geometrycollection:
- return @"GEOMETRYCOLLECTION";
- default:
- return nil;
- }
- return nil;
-}
-
-/**
- * dealloc
- */
-- (void)dealloc
-{
- if(geoBuffer && bufferLength) free(geoBuffer);
- [super dealloc];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPKit.h b/Frameworks/MCPKit/MCPFoundationKit/MCPKit.h
deleted file mode 100644
index 57e6d62d..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPKit.h
+++ /dev/null
@@ -1,44 +0,0 @@
-//
-// $Id$
-//
-// MCPKit.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 08/12/2001.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-#import <MCPKit/MCPConstants.h>
-#import <MCPKit/MCPNull.h>
-#import <MCPKit/MCPResult.h>
-#import <MCPKit/MCPStreamingResult.h>
-#import <MCPKit/MCPConnection.h>
-#import <MCPKit/MCPNumber.h>
-#import <MCPKit/MCPResultPlus.h>
-#import <MCPKit/MCPFastQueries.h>
-#import <MCPKit/MCPGeometryData.h>
-
-#import <MCPKit/MCPConnectionProxy.h>
-#import <MCPKit/MCPConnectionDelegate.h>
-
-#import "mysql.h"
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPNull.h b/Frameworks/MCPKit/MCPFoundationKit/MCPNull.h
deleted file mode 100644
index 500e0cf8..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPNull.h
+++ /dev/null
@@ -1,35 +0,0 @@
-//
-// $Id$
-//
-// MCPNull.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 02/06/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-@interface NSObject (MCPNSNullTest)
-
-- (BOOL)isNSNull;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPNull.m b/Frameworks/MCPKit/MCPFoundationKit/MCPNull.m
deleted file mode 100644
index 4232fb2a..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPNull.m
+++ /dev/null
@@ -1,43 +0,0 @@
-//
-// $Id$
-//
-// MCPNull.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 02/06/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPNull.h"
-
-@implementation NSObject (MCPNSNullTest)
-
-/**
- * This Category is meant to make any kind of object the possible target to the test (isNSNull).
- */
-- (BOOL) isNSNull
-{
- static id NSNullForComparison;
- if (!NSNullForComparison) NSNullForComparison = [NSNull null];
- return (self == NSNullForComparison);
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPNumber.h b/Frameworks/MCPKit/MCPFoundationKit/MCPNumber.h
deleted file mode 100644
index 8be1dd8b..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPNumber.h
+++ /dev/null
@@ -1,83 +0,0 @@
-//
-// $Id$
-//
-// MCPNumber.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 08/12/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-@interface MCPNumber : NSNumber
-{
- const char *typeCode;
- NSNumber *number;
-}
-
-+ (MCPNumber *)numberWithChar:(char)value;
-+ (MCPNumber *)numberWithUnsignedChar:(unsigned char)value;
-+ (MCPNumber *)numberWithShort:(short)value;
-+ (MCPNumber *)numberWithUnsignedShort:(unsigned short)value;
-+ (MCPNumber *)numberWithInt:(int)value;
-+ (MCPNumber *)numberWithUnsignedInt:(unsigned int)value;
-+ (MCPNumber *)numberWithLong:(long)value;
-+ (MCPNumber *)numberWithUnsignedLong:(unsigned long)value;
-+ (MCPNumber *)numberWithLongLong:(long long)value;
-+ (MCPNumber *)numberWithUnsignedLongLong:(unsigned long long)value;
-+ (MCPNumber *)numberWithFloat:(float)value;
-+ (MCPNumber *)numberWithDouble:(double)value;
-+ (MCPNumber *)numberWithBool:(BOOL)value;
-
-- (id)initWithChar:(char)value;
-- (id)initWithUnsignedChar:(unsigned char)value;
-- (id)initWithShort:(short)value;
-- (id)initWithUnsignedShort:(unsigned short)value;
-- (id)initWithInt:(int)value;
-- (id)initWithUnsignedInt:(unsigned int)value;
-- (id)initWithLong:(long)value;
-- (id)initWithUnsignedLong:(unsigned long)value;
-- (id)initWithLongLong:(long long)value;
-- (id)initWithUnsignedLongLong:(unsigned long long)value;
-- (id)initWithFloat:(float)value;
-- (id)initWithDouble:(double)value;
-- (id)initWithBool:(BOOL)value;
-
-// Important NSNumber primitive methods
-- (const char *)objCType;
-- (void)getValue:(void *)buffer;
-
-- (char)charValue;
-- (unsigned char)unsignedCharValue;
-- (short)shortValue;
-- (unsigned short)unsignedShortValue;
-- (int)intValue;
-- (unsigned int)unsignedIntValue;
-- (long)longValue;
-- (unsigned long)unsignedLongValue;
-- (long long)longLongValue;
-- (unsigned long long)unsignedLongLongValue;
-- (float)floatValue;
-- (double)doubleValue;
-- (BOOL)boolValue;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPNumber.m b/Frameworks/MCPKit/MCPFoundationKit/MCPNumber.m
deleted file mode 100644
index de035ee8..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPNumber.m
+++ /dev/null
@@ -1,301 +0,0 @@
-//
-// $Id$
-//
-// MCPNumber.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 08/12/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPNumber.h"
-
-@implementation MCPNumber
-
-#pragma mark -
-#pragma mark 'Creator' class methods
-
-+ (MCPNumber *)numberWithChar:(char)value
-{
- return [[[MCPNumber alloc] initWithChar:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithUnsignedChar:(unsigned char)value
-{
- return [[[MCPNumber alloc] initWithUnsignedChar:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithShort:(short)value
-{
- return [[[MCPNumber alloc] initWithShort:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithUnsignedShort:(unsigned short)value
-{
- return [[[MCPNumber alloc] initWithUnsignedShort:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithInt:(int)value
-{
- return [[[MCPNumber alloc] initWithInteger:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithUnsignedInt:(unsigned int)value
-{
- return [[[MCPNumber alloc] initWithUnsignedInteger:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithLong:(long)value
-{
- return [[[MCPNumber alloc] initWithLong:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithUnsignedLong:(unsigned long)value
-{
- return [[[MCPNumber alloc] initWithUnsignedLong:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithLongLong:(long long)value
-{
- return [[[MCPNumber alloc] initWithLongLong:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithUnsignedLongLong:(unsigned long long)value
-{
- return [[[MCPNumber alloc] initWithUnsignedLongLong:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithFloat:(float)value
-{
- return [[[MCPNumber alloc] initWithDouble:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithDouble:(double)value
-{
- return [[[MCPNumber alloc] initWithDouble:value] autorelease];
-}
-
-+ (MCPNumber *)numberWithBool:(BOOL)value
-{
- return [[[MCPNumber alloc] initWithBool:value] autorelease];
-}
-
-#pragma mark -
-#pragma mark Initialilzers
-
-- (id)initWithChar:(char)value
-{
- typeCode = @encode(char);
- number = [[NSNumber alloc] initWithChar:value];
-
- return self;
-}
-
-- (id)initWithUnsignedChar:(unsigned char)value
-{
- typeCode = @encode(unsigned char);
- number = [[NSNumber alloc] initWithUnsignedChar:value];
-
- return self;
-}
-
-- (id)initWithShort:(short)value
-{
- typeCode = @encode(short);
- number = [[NSNumber alloc] initWithShort:value];
-
- return self;
-}
-
-- (id)initWithUnsignedShort:(unsigned short)value
-{
- typeCode = @encode(unsigned short);
- number = [[NSNumber alloc] initWithUnsignedShort:value];
-
- return self;
-}
-
-- (id)initWithInt:(int)value
-{
- typeCode = @encode(NSInteger);
- number = [[NSNumber alloc] initWithInteger:value];
-
- return self;
-}
-
-- (id)initWithUnsignedInt:(unsigned int)value
-{
- typeCode = @encode(NSUInteger);
- number = [[NSNumber alloc] initWithUnsignedInteger:value];
-
- return self;
-}
-
-- (id)initWithLong:(long) value
-{
- typeCode = @encode(long);
- number = [[NSNumber alloc] initWithLong:value];
-
- return self;
-}
-
-- (id)initWithUnsignedLong:(unsigned long)value
-{
- typeCode = @encode(unsigned long);
- number = [[NSNumber alloc] initWithUnsignedLong:value];
-
- return self;
-}
-
-- (id)initWithLongLong:(long long)value
-{
- typeCode = @encode(long long);
- number = [[NSNumber alloc] initWithLongLong:value];
-
- return self;
-}
-
-- (id)initWithUnsignedLongLong:(unsigned long long)value
-{
- typeCode = @encode(unsigned long long);
- number = [[NSNumber alloc] initWithUnsignedLongLong:value];
-
- return self;
-}
-
-- (id)initWithFloat:(float)value
-{
- typeCode = @encode(CGFloat);
- number = [[NSNumber alloc] initWithDouble:value];
-
- return self;
-}
-
-- (id)initWithDouble:(double)value
-{
- typeCode = @encode(double);
- number = [[NSNumber alloc] initWithDouble:value];
-
- return self;
-}
-
-- (id)initWithBool:(BOOL)value
-{
- typeCode = @encode(BOOL);
- number = [[NSNumber alloc] initWithBool:value];
-
- return self;
-}
-
-#pragma mark -
-#pragma mark NSValue primitive methods
-
-- (const char *)objCType
-{
- return typeCode;
-}
-
-- (void)getValue:(void *)buffer
-{
- [number getValue:buffer];
-}
-
-#pragma mark -
-#pragma mark NSNumber primitive methods
-
-/**
- * Reparing the absence of primitive methodes in NSNumber
- */
-- (char)charValue
-{
- return [number charValue];
-}
-
-- (unsigned char)unsignedCharValue
-{
- return [number unsignedCharValue];
-}
-
-- (short)shortValue
-{
- return [number shortValue];
-}
-
-- (unsigned short)unsignedShortValue
-{
- return [number unsignedShortValue];
-}
-
-- (int)intValue
-{
- return [number intValue];
-}
-
-- (unsigned int)unsignedIntValue
-{
- return [number unsignedIntValue];
-}
-
-- (long)longValue
-{
- return [number longValue];
-}
-
-- (unsigned long)unsignedLongValue
-{
- return [number unsignedLongValue];
-}
-
-- (long long)longLongValue
-{
- return [number longLongValue];
-}
-
-- (unsigned long long)unsignedLongLongValue
-{
- return [number unsignedLongLongValue];
-}
-
-- (float)floatValue
-{
- return [number floatValue];
-}
-
-- (double)doubleValue
-{
- return [number doubleValue];
-}
-
-- (BOOL)boolValue
-{
- return [number boolValue];
-}
-
-#pragma mark -
-
-- (void)dealloc
-{
- [number release];
-
- [super dealloc];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPResult.h b/Frameworks/MCPKit/MCPFoundationKit/MCPResult.h
deleted file mode 100644
index ad50af75..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPResult.h
+++ /dev/null
@@ -1,86 +0,0 @@
-//
-// $Id$
-//
-// MCPResult.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 08/12/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-#import "MCPConstants.h"
-#import "mysql.h"
-
-#define MAGIC_BINARY_CHARSET_NR 63
-
-@interface MCPResult : NSObject
-{
- MYSQL_RES *mResult; /* The MYSQL_RES structure of the C API. */
- NSArray *mNames; /* An NSArray holding the name of the columns. */
- NSStringEncoding mEncoding; /* The encoding used by MySQL server, to ISO-1 default. */
- NSUInteger mNumOfFields; /* The number of fields in the result. */
- NSTimeZone *mTimeZone; /* The time zone of the connection when the query was made. */
- BOOL mReturnDataAsStrings; /* Whether to return data types as strings */
-}
-
-// Initialization
-- (id)initWithMySQLPtr:(MYSQL *)mySQLPtr encoding:(NSStringEncoding)theEncoding timeZone:(NSTimeZone *)iTimeZone;
-- (id)initWithResPtr:(MYSQL_RES *)mySQLResPtr encoding:(NSStringEncoding)theEncoding timeZone:(NSTimeZone *)iTimeZone;
-
-// Result info
-- (my_ulonglong)numOfRows;
-- (NSUInteger)numOfFields;
-
-// Rows
-- (void)dataSeek:(my_ulonglong)row;
-- (id)fetchRowAsType:(MCPReturnType) aType;
-- (NSArray *)fetchRowAsArray;
-- (NSDictionary *)fetchRowAsDictionary;
-
-// Columns
-- (NSArray *)fetchFieldNames;
-- (id)fetchTypesAsType:(MCPReturnType)aType;
-- (NSArray *)fetchTypesAsArray;
-- (NSDictionary *)fetchTypesAsDictionary;
-- (NSArray *)fetchResultFieldsStructure;
-
-- (NSUInteger)fetchFlagsAtIndex:(NSUInteger)index;
-- (NSUInteger)fetchFlagsForKey:(NSString *)key;
-
-- (BOOL)isBlobAtIndex:(NSUInteger)index;
-- (BOOL)isBlobForKey:(NSString *)key;
-
-// Conversion
-- (void) setReturnDataAsStrings:(BOOL)alwaysConvertData;
-- (NSString *)stringWithText:(NSData *)theTextData;
-- (const char *)cStringFromString:(NSString *)theString;
-- (NSString *)stringWithCString:(const char *)theCString;
-
-// Other
-- (NSString *)mysqlTypeToStringForType:(NSUInteger)type withCharsetNr:(NSUInteger)charsetnr withFlags:(NSUInteger)flags withLength:(unsigned long long)length;
-- (NSString *)mysqlTypeToGroupForType:(NSUInteger)type withCharsetNr:(NSUInteger)charsetnr withFlags:(NSUInteger)flags;
-- (NSString *)findCharsetName:(NSUInteger)charsetnr;
-- (NSString *)findCharsetCollation:(NSUInteger)charsetnr;
-- (NSUInteger)findCharsetMaxByteLengthPerChar:(NSUInteger)charsetnr;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPResult.m b/Frameworks/MCPKit/MCPFoundationKit/MCPResult.m
deleted file mode 100644
index f112a02d..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPResult.m
+++ /dev/null
@@ -1,1354 +0,0 @@
-//
-// $Id$
-//
-// MCPResult.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 08/12/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPConnection.h"
-#import "MCPNull.h"
-#import "MCPNumber.h"
-#import "MCPResult.h"
-#import "MCPGeometryData.h"
-
-NSCalendarDate *MCPYear0000;
-
-const OUR_CHARSET our_charsets60[] =
-{
- {1, "big5","big5_chinese_ci", 1, 2},
- {3, "dec8", "dec8_swedisch_ci", 1, 1},
- {4, "cp850", "cp850_general_ci", 1, 1},
- {6, "hp8", "hp8_english_ci", 1, 1},
- {7, "koi8r", "koi8r_general_ci", 1, 1},
- {8, "latin1", "latin1_swedish_ci", 1, 1},
- {9, "latin2", "latin2_general_ci", 1, 1},
- {10, "swe7", "swe7_swedish_ci", 1, 1},
- {11, "ascii", "ascii_general_ci", 1, 1},
- {12, "ujis", "ujis_japanese_ci", 1, 3},
- {13, "sjis", "sjis_japanese_ci", 1, 2},
- {16, "hebrew", "hebrew_general_ci", 1, 1},
- {18, "tis620", "tis620_thai_ci", 1, 1},
- {19, "euckr", "euckr_korean_ci", 1, 2},
- {22, "koi8u", "koi8u_general_ci", 1, 1},
- {24, "gb2312", "gb2312_chinese_ci", 1, 2},
- {25, "greek", "greek_general_ci", 1, 1},
- {26, "cp1250", "cp1250_general_ci", 1, 1},
- {28, "gbk", "gbk_chinese_ci", 1, 2},
- {30, "latin5", "latin5_turkish_ci", 1, 1},
- {32, "armscii8", "armscii8_general_ci", 1, 1},
- {33, "utf8", "utf8_general_ci", 1, 3},
- {35, "ucs2", "ucs2_general_ci", 2, 2},
- {36, "cp866", "cp866_general_ci", 1, 1},
- {37, "keybcs2", "keybcs2_general_ci", 1, 1},
- {38, "macce", "macce_general_ci", 1, 1},
- {39, "macroman", "macroman_general_ci", 1, 1},
- {40, "cp852", "cp852_general_ci", 1, 1},
- {41, "latin7", "latin7_general_ci", 1, 1},
- {51, "cp1251", "cp1251_general_ci", 1, 1},
- {57, "cp1256", "cp1256_general_ci", 1, 1},
- {59, "cp1257", "cp1257_general_ci", 1, 1},
- {63, "binary", "binary", 1, 1},
- {92, "geostd8", "geostd8_general_ci", 1, 1},
- {95, "cp932", "cp932_japanese_ci", 1, 2},
- {97, "eucjpms", "eucjpms_japanese_ci", 1, 3},
- {2, "latin2", "latin2_czech_cs", 1, 1},
- {5, "latin1", "latin1_german_ci", 1, 1},
- {14, "cp1251", "cp1251_bulgarian_ci", 1, 1},
- {15, "latin1", "latin1_danish_ci", 1, 1},
- {17, "filename", "filename", 1, 5},
- {20, "latin7", "latin7_estonian_cs", 1, 1},
- {21, "latin2", "latin2_hungarian_ci", 1, 1},
- {23, "cp1251", "cp1251_ukrainian_ci", 1, 1},
- {27, "latin2", "latin2_croatian_ci", 1, 1},
- {29, "cp1257", "cp1257_lithunian_ci", 1, 1},
- {31, "latin1", "latin1_german2_ci", 1, 1},
- {34, "cp1250", "cp1250_czech_cs", 1, 1},
- {42, "latin7", "latin7_general_cs", 1, 1},
- {43, "macce", "macce_bin", 1, 1},
- {44, "cp1250", "cp1250_croatian_ci", 1, 1},
- {45, "utf8", "utf8_general_ci", 1, 1},
- {46, "utf8", "utf8_bin", 1, 1},
- {47, "latin1", "latin1_bin", 1, 1},
- {48, "latin1", "latin1_general_ci", 1, 1},
- {49, "latin1", "latin1_general_cs", 1, 1},
- {50, "cp1251", "cp1251_bin", 1, 1},
- {52, "cp1251", "cp1251_general_cs", 1, 1},
- {53, "macroman", "macroman_bin", 1, 1},
- {58, "cp1257", "cp1257_bin", 1, 1},
- {60, "armascii8", "armascii8_bin", 1, 1},
- {65, "ascii", "ascii_bin", 1, 1},
- {66, "cp1250", "cp1250_bin", 1, 1},
- {67, "cp1256", "cp1256_bin", 1, 1},
- {68, "cp866", "cp866_bin", 1, 1},
- {69, "dec8", "dec8_bin", 1, 1},
- {70, "greek", "greek_bin", 1, 1},
- {71, "hebew", "hebrew_bin", 1, 1},
- {72, "hp8", "hp8_bin", 1, 1},
- {73, "keybcs2", "keybcs2_bin", 1, 1},
- {74, "koi8r", "koi8r_bin", 1, 1},
- {75, "koi8u", "koi8u_bin", 1, 1},
- {77, "latin2", "latin2_bin", 1, 1},
- {78, "latin5", "latin5_bin", 1, 1},
- {79, "latin7", "latin7_bin", 1, 1},
- {80, "cp850", "cp850_bin", 1, 1},
- {81, "cp852", "cp852_bin", 1, 1},
- {82, "swe7", "swe7_bin", 1, 1},
- {93, "geostd8", "geostd8_bin", 1, 1},
- {83, "utf8", "utf8_bin", 1, 3},
- {84, "big5", "big5_bin", 1, 2},
- {85, "euckr", "euckr_bin", 1, 2},
- {86, "gb2312", "gb2312_bin", 1, 2},
- {87, "gbk", "gbk_bin", 1, 2},
- {88, "sjis", "sjis_bin", 1, 2},
- {89, "tis620", "tis620_bin", 1, 1},
- {90, "ucs2", "ucs2_bin", 2, 2},
- {91, "ujis", "ujis_bin", 1, 3},
- {94, "latin1", "latin1_spanish_ci", 1, 1},
- {96, "cp932", "cp932_bin", 1, 2},
- {99, "cp1250", "cp1250_polish_ci", 1, 1},
- {98, "eucjpms", "eucjpms_bin", 1, 3},
- {128, "ucs2", "ucs2_unicode_ci", 2, 2},
- {129, "ucs2", "ucs2_icelandic_ci", 2, 2},
- {130, "ucs2", "ucs2_latvian_ci", 2, 2},
- {131, "ucs2", "ucs2_romanian_ci", 2, 2},
- {132, "ucs2", "ucs2_slovenian_ci", 2, 2},
- {133, "ucs2", "ucs2_polish_ci", 2, 2},
- {134, "ucs2", "ucs2_estonian_ci", 2, 2},
- {135, "ucs2", "ucs2_spanish_ci", 2, 2},
- {136, "ucs2", "ucs2_swedish_ci", 2, 2},
- {137, "ucs2", "ucs2_turkish_ci", 2, 2},
- {138, "ucs2", "ucs2_czech_ci", 2, 2},
- {139, "ucs2", "ucs2_danish_ci", 2, 2},
- {140, "ucs2", "ucs2_lithunian_ci", 2, 2},
- {141, "ucs2", "ucs2_slovak_ci", 2, 2},
- {142, "ucs2", "ucs2_spanish2_ci", 2, 2},
- {143, "ucs2", "ucs2_roman_ci", 2, 2},
- {144, "ucs2", "ucs2_persian_ci", 2, 2},
- {145, "ucs2", "ucs2_esperanto_ci", 2, 2},
- {146, "ucs2", "ucs2_hungarian_ci", 2, 2},
- {147, "ucs2", "ucs2_sinhala_ci", 2, 2},
- {192, "utf8mb3", "utf8mb3_general_ci", 1, 3},
- {193, "utf8mb3", "utf8mb3_icelandic_ci", 1, 3},
- {194, "utf8mb3", "utf8mb3_latvian_ci", 1, 3},
- {195, "utf8mb3", "utf8mb3_romanian_ci", 1, 3},
- {196, "utf8mb3", "utf8mb3_slovenian_ci", 1, 3},
- {197, "utf8mb3", "utf8mb3_polish_ci", 1, 3},
- {198, "utf8mb3", "utf8mb3_estonian_ci", 1, 3},
- {119, "utf8mb3", "utf8mb3_spanish_ci", 1, 3},
- {200, "utf8mb3", "utf8mb3_swedish_ci", 1, 3},
- {201, "utf8mb3", "utf8mb3_turkish_ci", 1, 3},
- {202, "utf8mb3", "utf8mb3_czech_ci", 1, 3},
- {203, "utf8mb3", "utf8mb3_danish_ci", 1, 3},
- {204, "utf8mb3", "utf8mb3_lithunian_ci", 1, 3},
- {205, "utf8mb3", "utf8mb3_slovak_ci", 1, 3},
- {206, "utf8mb3", "utf8mb3_spanish2_ci", 1, 3},
- {207, "utf8mb3", "utf8mb3_roman_ci", 1, 3},
- {208, "utf8mb3", "utf8mb3_persian_ci", 1, 3},
- {209, "utf8mb3", "utf8mb3_esperanto_ci", 1, 3},
- {210, "utf8mb3", "utf8mb3_hungarian_ci", 1, 3},
- {211, "utf8mb3", "utf8mb3_sinhala_ci", 1, 3},
- {224, "utf8", "utf8_unicode_ci", 1, 3},
- {225, "utf8", "utf8_icelandic_ci", 1, 3},
- {226, "utf8", "utf8_latvian_ci", 1, 3},
- {227, "utf8", "utf8_romanian_ci", 1, 3},
- {228, "utf8", "utf8_slovenian_ci", 1, 3},
- {229, "utf8", "utf8_polish_ci", 1, 3},
- {230, "utf8", "utf8_estonian_ci", 1, 3},
- {231, "utf8", "utf8_spanish_ci", 1, 3},
- {232, "utf8", "utf8_swedish_ci", 1, 3},
- {233, "utf8", "utf8_turkish_ci", 1, 3},
- {234, "utf8", "utf8_czech_ci", 1, 3},
- {235, "utf8", "utf8_danish_ci", 1, 3},
- {236, "utf8", "utf8_lithuanian_ci", 1, 3},
- {237, "utf8", "utf8_slovak_ci", 1, 3},
- {238, "utf8", "utf8_spanish2_ci", 1, 3},
- {239, "utf8", "utf8_roman_ci", 1, 3},
- {240, "utf8", "utf8_persian_ci", 1, 3},
- {241, "utf8", "utf8_esperanto_ci", 1, 3},
- {242, "utf8", "utf8_hungarian_ci", 1, 3},
- {243, "utf8", "utf8_sinhala_ci", 1, 3},
- {254, "utf8mb3", "utf8mb3_general_cs", 1, 3},
- {0, NULL, NULL, 0, 0}
-};
-
-@implementation MCPResult
-
-/**
- * Hold the results of a query to a MySQL database server. It correspond to the MYSQL_RES structure of the C API, and to the statement handle of the PERL DBI/DBD.
- *
- * Uses the !{mysql_store_result()} function from the C API.
- *
- * This object is generated only by a MCPConnection object, in this way (see #{MCPConnection} documentation):
- *
- * MCPConnection *theConnec = [MCPConnection alloc];
- * MCPResult *theRes;
- * NSDictionary *theDict;
- * NSArray *theColNames;
- * int i, j;
- *
- * theConnec = [theConnec initToHost:@"albert.com" withLogin:@"toto" password:@"albert" usingPort:0];
- * [theConnec selectDB:@"db1"];
- * theRes = [theConnec queryString:@"select * from table1"];
- * theColNames = [theRes fetchFiedlsName];
- * i = 0;
- *
- * while (theDict = [theRes fetchRowAsDictionary]) {
- * NSLog(@"Row : %d\n", i);
- * for (j=0; j<[theColNames count]; j++) {
- * NSLog(@" Field : %@, contain : %@\n", [theColNames objectAtIndex:j], [theDict objectForKey:[theColNames objectAtIndex:j]]);
- * }
- * i++;
- * }
- */
-
-/**
- * Initialize the class version to 3.0.1
- */
-+ (void)initialize
-{
- if ((self = [MCPResult class])) {
- [self setVersion:030001]; // Ma.Mi.Re -> MaMiRe
- MCPYear0000 = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:-63146822400.0];
- [MCPYear0000 setCalendarFormat:@"%Y"];
- }
-}
-
-#pragma mark -
-#pragma mark Initialisation
-
-/**
- * Empty init, normaly of NO use to the user, again, MCPResult should be made through calls to MCPConnection
- */
-- (id)init
-{
- if ((self = [super init])) {
- mEncoding = [MCPConnection defaultMySQLEncoding];
- mReturnDataAsStrings = NO;
- mTimeZone = nil;
-
- if (mResult) {
- mysql_free_result(mResult);
- mResult = NULL;
- }
-
- if (mNames) {
- [mNames release];
- mNames = nil;
- }
-
- mNumOfFields = 0;
- }
-
- return self;
-}
-
-/**
- * Initialise a MCPResult, it is used internally by MCPConnection !{queryString:} method: the only proper
- * way to get a running MCPResult object.
- */
-- (id)initWithMySQLPtr:(MYSQL *)mySQLPtr encoding:(NSStringEncoding)iEncoding timeZone:(NSTimeZone *)iTimeZone
-{
- if ((self = [super init])) {
- mEncoding = iEncoding;
- mTimeZone = [iTimeZone retain];
- mReturnDataAsStrings = NO;
-
- if (mResult) {
- mysql_free_result(mResult);
- mResult = NULL;
- }
-
- if (mNames) {
- [mNames release];
- mNames = nil;
- }
-
- mResult = mysql_store_result(mySQLPtr);
-
- if (mResult) {
- mNumOfFields = mysql_num_fields(mResult);
- }
- else {
- mNumOfFields = 0;
- }
- }
-
- return self;
-}
-
-/**
- * This metod is used internally by MCPConnection object when it have already a MYSQL_RES object to initialise
- * MCPResult object. Initialise a MCPResult with the MYSQL_RES pointer (returned by such a function as mysql_list_dbs).
- * NB: MCPResult should be made by using one of the method of MCPConnection.
- */
-- (id)initWithResPtr:(MYSQL_RES *)mySQLResPtr encoding:(NSStringEncoding)iEncoding timeZone:(NSTimeZone *)iTimeZone
-{
- if ((self = [super init])) {
- mEncoding = iEncoding;
- mTimeZone = [iTimeZone retain];
- mReturnDataAsStrings = NO;
-
- if (mResult) {
- mysql_free_result(mResult);
- mResult = NULL;
- }
-
- if (mNames) {
- [mNames release];
- mNames = nil;
- }
-
- mResult = mySQLResPtr;
-
- if (mResult) {
- mNumOfFields = mysql_num_fields(mResult);
- }
- else {
- mNumOfFields = 0;
- }
- }
-
- return self;
-}
-
-#pragma mark -
-#pragma mark Result info
-
-/**
- * Return the number of rows selected by the query.
- */
-- (my_ulonglong)numOfRows
-{
- if (mResult) {
- return mysql_num_rows(mResult);
- }
-
- return 0;
-}
-
-/**
- * Return the number of fields selected by the query. As a side effect it forces an update of the number of fields.
- */
-- (NSUInteger)numOfFields
-{
- if (mResult) {
- return mNumOfFields = mysql_num_fields(mResult);
- }
-
- return mNumOfFields = 0;
-}
-
-#pragma mark -
-#pragma mark Rows
-
-/**
- * Go to a precise row in the selected result. 0 is the very first row.
- */
-- (void)dataSeek:(my_ulonglong)row
-{
- my_ulonglong theRow = (row < 1)? 0 : row;
- theRow = (theRow < [self numOfRows]) ? theRow : ([self numOfRows] - 1);
- mysql_data_seek(mResult,theRow);
-}
-
-/**
- *
- */
-- (id)fetchRowAsType:(MCPReturnType)aType
-{
- MYSQL_ROW theRow;
- unsigned long *theLengths;
- MYSQL_FIELD *theField;
- NSUInteger i;
- id theReturn;
-
- if (mResult == NULL) {
- // If there is no results, returns nil, as after the last row...
- return nil;
- }
-
- theRow = mysql_fetch_row(mResult);
-
- if (theRow == NULL) {
- return nil;
- }
-
- switch (aType) {
- case MCPTypeArray:
- theReturn = [NSMutableArray arrayWithCapacity:mNumOfFields];
- break;
- case MCPTypeDictionary:
- if (mNames == nil) {
- [self fetchFieldNames];
- }
- theReturn = [NSMutableDictionary dictionaryWithCapacity:mNumOfFields];
- break;
- default :
- NSLog (@"Unknown type : %d, will return an Array!\n", (int)aType);
- theReturn = [NSMutableArray arrayWithCapacity:mNumOfFields];
- break;
- }
-
- theLengths = mysql_fetch_lengths(mResult);
- theField = mysql_fetch_fields(mResult);
-
- for (i=0; i<mNumOfFields; i++) {
- id theCurrentObj;
-
- if (theRow[i] == NULL) {
- theCurrentObj = [NSNull null];
- } else {
- char *theData = theRow[i];
-
- switch (theField[i].type) {
- case FIELD_TYPE_TINY:
- case FIELD_TYPE_SHORT:
- case FIELD_TYPE_INT24:
- case FIELD_TYPE_LONG:
- case FIELD_TYPE_LONGLONG:
- case FIELD_TYPE_DECIMAL:
- case FIELD_TYPE_NEWDECIMAL:
- case FIELD_TYPE_FLOAT:
- case FIELD_TYPE_DOUBLE:
- case FIELD_TYPE_TIMESTAMP:
- case FIELD_TYPE_DATE:
- case FIELD_TYPE_TIME:
- case FIELD_TYPE_DATETIME:
- case FIELD_TYPE_YEAR:
- case FIELD_TYPE_VAR_STRING:
- case FIELD_TYPE_STRING:
- case FIELD_TYPE_SET:
- case FIELD_TYPE_ENUM:
- case FIELD_TYPE_NEWDATE: // Don't know what the format for this type is...
- theCurrentObj = [[[NSString alloc] initWithBytes:theData length:theLengths[i] encoding:mEncoding] autorelease];
- break;
-
- case FIELD_TYPE_BIT:
- theCurrentObj = [NSString stringWithFormat:@"%u", theData[0]];
- break;
-
- case FIELD_TYPE_TINY_BLOB:
- case FIELD_TYPE_BLOB:
- case FIELD_TYPE_MEDIUM_BLOB:
- case FIELD_TYPE_LONG_BLOB:
- theCurrentObj = [NSData dataWithBytes:theData length:theLengths[i]];
-
- // If the field is TEXT and NOT BLOB, or if force-return-as-string is
- // enabled, return a NSString instead of NSData
- if (mReturnDataAsStrings || !(theField[i].flags & BINARY_FLAG)) {
- theCurrentObj = [self stringWithText:theCurrentObj];
- }
-
- break;
-
- case FIELD_TYPE_NULL:
- theCurrentObj = [NSNull null];
- break;
-
- case FIELD_TYPE_GEOMETRY:
- theCurrentObj = [MCPGeometryData dataWithBytes:theData length:theLengths[i]];
- break;
-
- default:
- NSLog (@"in fetchRowAsType : Unknown type : %d for column %lu, send back a NSData object", (int)theField[i].type, (unsigned long)i);
- theCurrentObj = [NSData dataWithBytes:theData length:theLengths[i]];
- break;
- }
-
- // Some of the creators return nil object...
- if (theCurrentObj == nil) {
- theCurrentObj = [NSNull null];
- }
- }
-
- switch (aType) {
- case MCPTypeDictionary :
- [theReturn setObject:theCurrentObj forKey:[mNames objectAtIndex:i]];
- break;
-
- case MCPTypeArray :
- default :
- [theReturn addObject:theCurrentObj];
- break;
- }
- }
-
- return theReturn;
-}
-
-/**
- * Return the next row of the result as an array, the index in select field order, the object a proper object
- * for handling the information in the field (NSString, NSNumber ...).
- *
- * Just a #{typed} wrapper for method !{fetchRosAsType:} (with arg MCPTypeArray).
- *
- * NB: Returned object is immutable.
- */
-- (NSArray *)fetchRowAsArray
-{
- NSMutableArray *theArray = [self fetchRowAsType:MCPTypeArray];
-
- return (theArray) ? [NSArray arrayWithArray:theArray] : nil;
-}
-
-/**
- * Return the next row of the result as a dictionary, the key being the field name, the object a proper object
- * for handling the information in the field (NSString, NSNumber ...).
- *
- * Just a #{typed} wrapper for method !{fetchRosAsType:} (with arg MCPTypeDictionary).
- *
- * NB: Returned object is immutable.
- */
-- (NSDictionary *)fetchRowAsDictionary
-{
- NSMutableDictionary *theDict = [self fetchRowAsType:MCPTypeDictionary];
-
- return (theDict) ? [NSDictionary dictionaryWithDictionary:theDict] : nil;
-}
-
-#pragma mark -
-#pragma mark Columns
-
-/**
- * Generate the mNames if not already generated, and return it.
- *
- * mNames is a NSArray holding the names of the fields(columns) of the results.
- */
-- (NSArray *)fetchFieldNames
-{
- NSUInteger i;
- NSUInteger theNumFields;
- NSMutableArray *theNamesArray;
- MYSQL_FIELD *theField;
-
- if (mNames) {
- return mNames;
- }
-
- if (mResult == NULL) {
- // If no results, give an empty array. Maybe it's better to give a nil pointer?
- return (mNames = [[NSArray array] retain]);
- }
-
- theNumFields = [self numOfFields];
- theNamesArray = [NSMutableArray arrayWithCapacity: theNumFields];
- theField = mysql_fetch_fields(mResult);
-
- for (i=0; i<theNumFields; i++) {
- NSString *theName = [self stringWithCString:theField[i].name];
- if ((theName) && (![theName isEqualToString:@""])) {
- [theNamesArray addObject:theName];
- }
- else {
- [theNamesArray addObject:[NSString stringWithFormat:@"Column %ld", i]];
- }
- }
-
- return (mNames = [[NSArray arrayWithArray:theNamesArray] retain]);
-}
-
-/**
- * Return a collection of the fields's type. The type of collection is choosen by the aType variable
- * (MCPTypeArray or MCPTypeDictionary).
- *
- * This method returned directly the #{mutable} object generated while going through all the columns
- */
-- (id)fetchTypesAsType:(MCPReturnType)aType
-{
- NSUInteger i;
- id theTypes;
- MYSQL_FIELD *theField;
-
- if (mResult == NULL) {
- // If no results, give an empty array. Maybe it's better to give a nil pointer?
- return nil;
- }
-
- switch (aType) {
- case MCPTypeArray:
- theTypes = [NSMutableArray arrayWithCapacity:mNumOfFields];
- break;
- case MCPTypeDictionary:
- if (mNames == nil) {
- [self fetchFieldNames];
- }
- theTypes = [NSMutableDictionary dictionaryWithCapacity:mNumOfFields];
- break;
- default :
- NSLog (@"Unknown type : %d, will return an Array!\n", (int)aType);
- theTypes = [NSMutableArray arrayWithCapacity:mNumOfFields];
- break;
- }
-
- theField = mysql_fetch_fields(mResult);
-
- for (i=0; i<mNumOfFields; i++) {
- NSString *theType;
- switch (theField[i].type) {
- case FIELD_TYPE_TINY:
- theType = @"tiny";
- break;
- case FIELD_TYPE_SHORT:
- theType = @"short";
- break;
- case FIELD_TYPE_LONG:
- theType = @"long";
- break;
- case FIELD_TYPE_INT24:
- theType = @"int24";
- break;
- case FIELD_TYPE_LONGLONG:
- theType = @"longlong";
- break;
- case FIELD_TYPE_DECIMAL:
- case FIELD_TYPE_NEWDECIMAL:
- theType = @"decimal";
- break;
- case FIELD_TYPE_FLOAT:
- theType = @"float";
- break;
- case FIELD_TYPE_DOUBLE:
- theType = @"double";
- break;
- case FIELD_TYPE_TIMESTAMP:
- theType = @"timestamp";
- break;
- case FIELD_TYPE_DATE:
- theType = @"date";
- break;
- case FIELD_TYPE_TIME:
- theType = @"time";
- break;
- case FIELD_TYPE_DATETIME:
- theType = @"datetime";
- break;
- case FIELD_TYPE_YEAR:
- theType = @"year";
- break;
- case FIELD_TYPE_VAR_STRING:
- theType = @"varstring";
- break;
- case FIELD_TYPE_STRING:
- theType = @"string";
- break;
- case FIELD_TYPE_TINY_BLOB:
- theType = @"tinyblob";
- break;
- case FIELD_TYPE_BLOB:
- theType = @"blob";
- break;
- case FIELD_TYPE_MEDIUM_BLOB:
- theType = @"mediumblob";
- break;
- case FIELD_TYPE_LONG_BLOB:
- theType = @"longblob";
- break;
- case FIELD_TYPE_SET:
- theType = @"set";
- break;
- case FIELD_TYPE_ENUM:
- theType = @"enum";
- break;
- case FIELD_TYPE_NULL:
- theType = @"null";
- break;
- case FIELD_TYPE_NEWDATE:
- theType = @"newdate";
- break;
- case FIELD_TYPE_GEOMETRY:
- theType = @"geometry";
- break;
- default:
- theType = @"unknown";
- NSLog (@"in fetchTypesAsArray : Unknown type for column %lu of the MCPResult, type = %d", (unsigned long)i, (int)theField[i].type);
- break;
- }
-
- switch (aType) {
- case MCPTypeArray :
- [theTypes addObject:theType];
- break;
- case MCPTypeDictionary :
- [theTypes setObject:theType forKey:[mNames objectAtIndex:i]];
- break;
- default :
- [theTypes addObject:theType];
- break;
- }
- }
-
- return theTypes;
-}
-
-/**
- * Return an array of the fields' types.
- *
- * NB: Returned object is immutable.
- */
-- (NSArray *)fetchTypesAsArray
-{
- NSMutableArray *theArray = [self fetchTypesAsType:MCPTypeArray];
-
- return (theArray) ? [NSArray arrayWithArray:theArray] : nil;
-}
-
-/**
- * Return a dictionnary of the fields' types (keys are the fields' names).
- *
- * NB: Returned object is immutable.
- */
-- (NSDictionary*) fetchTypesAsDictionary
-{
- NSMutableDictionary *theDict = [self fetchTypesAsType:MCPTypeDictionary];
-
- return (theDict) ? [NSDictionary dictionaryWithDictionary:theDict] : nil;
-}
-
-/**
- * Return an array of dicts containg column data of the last executed query
- */
-- (NSArray *)fetchResultFieldsStructure
-{
- MYSQL_FIELD *theField;
-
- NSMutableArray *structureResult = [NSMutableArray array];
-
- NSUInteger i;
- NSUInteger numFields = mysql_num_fields(mResult);
-
- if (mResult == NULL) return nil;
-
- theField = mysql_fetch_fields(mResult);
-
- for (i=0; i < numFields; i++)
- {
- NSMutableDictionary *fieldStructure = [NSMutableDictionary dictionaryWithCapacity:39];
-
- /* Original column position */
- [fieldStructure setObject:[NSString stringWithFormat:@"%llu", (unsigned long long)i] forKey:@"datacolumnindex"];
-
- /* Name of column */
- [fieldStructure setObject:[self stringWithCString:theField[i].name] forKey:@"name"];
- // [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].name_length] forKey:@"name_length"];
-
- /* Original column name, if an alias */
- [fieldStructure setObject:[self stringWithCString:theField[i].org_name] forKey:@"org_name"];
- // [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].org_name_length] forKey:@"org_name_length"];
-
- /* Table of column if column was a field */
- [fieldStructure setObject:[self stringWithCString:theField[i].table] forKey:@"table"];
- // [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].table_length] forKey:@"table_length"];
-
- /* Org table name, if table was an alias */
- [fieldStructure setObject:[self stringWithCString:theField[i].org_table] forKey:@"org_table"];
- // [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].org_table_length] forKey:@"org_table_length"];
-
- /* Database for table */
- [fieldStructure setObject:[self stringWithCString:theField[i].db] forKey:@"db"];
- // [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].db_length] forKey:@"db_length"];
-
- /* Catalog for table */
- // [fieldStructure setObject:[self stringWithCString:theField[i].catalog] forKey:@"catalog"];
- // [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].catalog_length] forKey:@"catalog_length"];
-
- /* Default value (set by mysql_list_fields) */
- // [fieldStructure setObject:[self stringWithCString:theField[i].def] forKey:@"def"];
- // [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].def_length] forKey:@"def_length"];
-
- /* Width of column (real length in bytes) */
- [fieldStructure setObject:[NSNumber numberWithUnsignedLongLong:theField[i].length] forKey:@"byte_length"];
- /* Width of column (as in create)*/
- [fieldStructure setObject:[NSNumber numberWithUnsignedLongLong:theField[i].length/[self findCharsetMaxByteLengthPerChar:theField[i].charsetnr]]
- forKey:@"char_length"];
- /* Max width (bytes) for selected set */
- [fieldStructure setObject:[NSNumber numberWithUnsignedLongLong:theField[i].max_length] forKey:@"max_byte_length"];
- /* Max width (chars) for selected set */
- // [fieldStructure setObject:[NSNumber numberWithUnsignedLongLong:theField[i].max_length/[self find_charsetMaxByteLengthPerChar:theField[i].charsetnr]]
- // forKey:@"max_char_length"];
-
- /* Div flags */
- [fieldStructure setObject:[NSNumber numberWithUnsignedInt:theField[i].flags] forKey:@"flags"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & NOT_NULL_FLAG) ? YES : NO] forKey:@"null"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & PRI_KEY_FLAG) ? YES : NO] forKey:@"PRI_KEY_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & UNIQUE_KEY_FLAG) ? YES : NO] forKey:@"UNIQUE_KEY_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & MULTIPLE_KEY_FLAG) ? YES : NO] forKey:@"MULTIPLE_KEY_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & BLOB_FLAG) ? YES : NO] forKey:@"BLOB_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & UNSIGNED_FLAG) ? YES : NO] forKey:@"UNSIGNED_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & ZEROFILL_FLAG) ? YES : NO] forKey:@"ZEROFILL_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & BINARY_FLAG) ? YES : NO] forKey:@"BINARY_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & ENUM_FLAG) ? YES : NO] forKey:@"ENUM_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & AUTO_INCREMENT_FLAG) ? YES : NO] forKey:@"AUTO_INCREMENT_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & SET_FLAG) ? YES : NO] forKey:@"SET_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & NUM_FLAG) ? YES : NO] forKey:@"NUM_FLAG"];
- [fieldStructure setObject:[NSNumber numberWithBool:(theField[i].flags & PART_KEY_FLAG) ? YES : NO] forKey:@"PART_KEY_FLAG"];
- // [fieldStructure setObject:[NSNumber numberWithInt:(theField[i].flags & GROUP_FLAG) ? 1 : 0] forKey:@"GROUP_FLAG"];
- // [fieldStructure setObject:[NSNumber numberWithInt:(theField[i].flags & UNIQUE_FLAG) ? 1 : 0] forKey:@"UNIQUE_FLAG"];
- // [fieldStructure setObject:[NSNumber numberWithInt:(theField[i].flags & BINCMP_FLAG) ? 1 : 0] forKey:@"BINCMP_FLAG"];
-
- /* Number of decimals in field */
- [fieldStructure setObject:[NSNumber numberWithUnsignedInteger:theField[i].decimals] forKey:@"decimals"];
-
- /* Character set */
- [fieldStructure setObject:[NSNumber numberWithUnsignedInteger:theField[i].charsetnr] forKey:@"charsetnr"];
- [fieldStructure setObject:[self findCharsetName:theField[i].charsetnr] forKey:@"charset_name"];
- [fieldStructure setObject:[self findCharsetCollation:theField[i].charsetnr] forKey:@"charset_collation"];
-
- /* Table type */
- [fieldStructure setObject:[self mysqlTypeToStringForType:theField[i].type
- withCharsetNr:theField[i].charsetnr
- withFlags:theField[i].flags
- withLength:theField[i].length
- ] forKey:@"type"];
-
- /* Table type group*/
- [fieldStructure setObject:[self mysqlTypeToGroupForType:theField[i].type
- withCharsetNr:theField[i].charsetnr
- withFlags:theField[i].flags
- ] forKey:@"typegrouping"];
-
- [structureResult addObject:fieldStructure];
-
- }
-
- return structureResult;
-
-}
-
-/**
- * Return the MySQL flags of the column at the given index... Can be used to check if a number is signed or not...
- */
-- (NSUInteger)fetchFlagsAtIndex:(NSUInteger)anIndex
-{
- NSUInteger theRet;
- NSUInteger theNumFields;
- MYSQL_FIELD *theField;
-
- if (mResult == NULL) {
- // If no results, give an empty array. Maybe it's better to give a nil pointer?
- return (0);
- }
-
- theNumFields = [self numOfFields];
- theField = mysql_fetch_fields(mResult);
-
- if (anIndex >= theNumFields) {
- // Out of range... should raise an exception
- theRet = 0;
- }
- else {
- theRet = theField[anIndex].flags;
- }
-
- return theRet;
-}
-
-/**
- *
- */
-- (NSUInteger)fetchFlagsForKey:(NSString *)key
-{
- NSUInteger theRet;
- NSUInteger anIndex;
- MYSQL_FIELD *theField;
-
- if (mResult == NULL) {
- // If no results, give an empty array. Maybe it's better to give a nil pointer?
- return (0);
- }
-
- if (mNames == nil) {
- [self fetchFieldNames];
- }
-
- theField = mysql_fetch_fields(mResult);
-
- if ([mNames indexOfObject:key] == NSNotFound) {
- // Non existent key... should raise an exception
- theRet = 0;
- }
- else {
- anIndex = [mNames indexOfObject:key];
-
- theRet = theField[anIndex].flags;
- }
-
- return theRet;
-}
-
-/**
- * Return YES if the field with the given index is a BLOB. It should be used to discriminates between BLOBs
- * and TEXTs.
- *
- * #{DEPRECATED}, This method is not consistent with the C API which is supposed to return YES for BOTH
- * text and blob (and BTW is also deprecated)...
- *
- * #{NOTE} That the current version handles properly TEXT, and returns those as NSString (and not NSData as
- * it used to be).
- */
-- (BOOL)isBlobAtIndex:(NSUInteger)anIndex
-{
- BOOL theRet;
- NSUInteger theNumFields;
- MYSQL_FIELD *theField;
-
- if (mResult == NULL) {
- // If no results, give an empty array. Maybe it's better to give a nil pointer?
- return (NO);
- }
-
- theNumFields = [self numOfFields];
- theField = mysql_fetch_fields(mResult);
-
- if (anIndex >= theNumFields) {
- // Out of range... should raise an exception
- theRet = NO;
- }
- else {
- switch(theField[anIndex].type) {
- case FIELD_TYPE_TINY_BLOB:
- case FIELD_TYPE_BLOB:
- case FIELD_TYPE_MEDIUM_BLOB:
- case FIELD_TYPE_LONG_BLOB:
- theRet = (theField[anIndex].flags & BINARY_FLAG);
- break;
- default:
- theRet = NO;
- break;
- }
- }
-
- return theRet;
-}
-
-/**
- * Return YES if the field (by name) with the given index is a BLOB. It should be used to discriminates
- * between BLOBs and TEXTs.
- *
- * #{DEPRECATED}, This method is not consistent with the C API which is supposed to return YES for BOTH
- * text and blob (and BTW is also deprecated)...
- *
- * #{NOTE} That the current version handles properly TEXT, and returns those as NSString (and not NSData
- * as it used to be).
- */
-- (BOOL)isBlobForKey:(NSString *)key
-{
- BOOL theRet;
- NSUInteger anIndex;
- MYSQL_FIELD *theField;
-
- if (mResult == NULL) {
- // If no results, give an empty array. Maybe it's better to give a nil pointer?
- return (NO);
- }
-
- if (mNames == nil) {
- [self fetchFieldNames];
- }
-
- theField = mysql_fetch_fields(mResult);
-
- if ([mNames indexOfObject:key] == NSNotFound) {
- // Non existent key... should raise an exception
- theRet = NO;
- }
- else {
- anIndex = [mNames indexOfObject:key];
-
- switch(theField[anIndex].type) {
- case FIELD_TYPE_TINY_BLOB:
- case FIELD_TYPE_BLOB:
- case FIELD_TYPE_MEDIUM_BLOB:
- case FIELD_TYPE_LONG_BLOB:
- theRet = (theField[anIndex].flags & BINARY_FLAG);
- break;
- default:
- theRet = NO;
- break;
- }
- }
-
- return theRet;
-}
-
-#pragma mark -
-#pragma mark Conversion
-
-/**
- * Set whether the result should return data types as strings. This may be useful
- * for queries where the result may be returned in either string or data form, but
- * will be converted to string for display and use anyway.
- * Note that certain MySQL versions also return data types for strings - eg SHOW
- * commands like SHOW CREATE TABLE or SHOW VARIABLES, and this conversion can be
- * necessary there.
- */
-- (void) setReturnDataAsStrings:(BOOL)alwaysConvertData
-{
- mReturnDataAsStrings = alwaysConvertData;
-}
-
-/**
- * Use the string encoding to convert the returned NSData to a string (for a TEXT field).
- */
-- (NSString *)stringWithText:(NSData *)theTextData
-{
- NSString *theString;
-
- if (theTextData == nil) {
- return nil;
- }
-
- theString = [[NSString alloc] initWithData:theTextData encoding:mEncoding];
-
- if (theString) {
- [theString autorelease];
- }
-
- return theString;
-}
-
-/**
- * Return a (long) string containing the table of results, first line being the fields name, next line(s)
- * the row(s). Useful to have NSLog logging a MCPResult (example).
- */
-- (NSString *)description
-{
- if (mResult == NULL) {
- return @"This is an empty MCPResult\n";
- }
- else {
- NSMutableString *theString = [NSMutableString stringWithCapacity:0];
- NSUInteger i;
- NSArray *theRow;
- MYSQL_ROW_OFFSET thePosition;
- BOOL shouldTruncateFields = [MCPConnection truncateLongField];
-
- // First line, saying we are displaying a MCPResult
- [theString appendFormat:@"MCPResult: (encoding : %ld, dim %ld x %ld)\n", (long)mEncoding, (long)mNumOfFields, (long)[self numOfRows]];
-
- // Second line: the field names, tab separated
- [self fetchFieldNames];
-
- for (i=0; i<(mNumOfFields-1); i++) {
- [theString appendFormat:@"%@\t", [mNames objectAtIndex:i]];
- }
-
- [theString appendFormat:@"%@\n", [mNames objectAtIndex:i]];
- // Next lines, the records (saving current position to put it back after the full display)
- thePosition = mysql_row_tell(mResult);
- [self dataSeek:0];
-
- while ((theRow = [self fetchRowAsArray]))
- {
- id theField = [theRow objectAtIndex:i];
-
- if (shouldTruncateFields) {
- if (([theField isKindOfClass:[NSString class]]) && (kLengthOfTruncationForLog < [(NSString *)theField length])) {
- theField = [theField substringToIndex:kLengthOfTruncationForLog];
- }
- else if (([theField isKindOfClass:[NSData class]]) && (kLengthOfTruncationForLog < [(NSData *)theField length])) {
- theField = [NSData dataWithBytes:[theField bytes] length:kLengthOfTruncationForLog];
- }
- }
-
- for (i=0; i<(mNumOfFields - 1); i++)
- {
- [theString appendFormat:@"%@\t", theField];
- }
-
- [theString appendFormat:@"%@\n", theField];
- }
-
- // Returning to the proper row
- mysql_row_seek(mResult, thePosition);
-
- return theString;
- }
-}
-
-/**
- * For internal use only. Transform a NSString to a C type string (ended with \0) using ethe character set
- * from the MCPConnection. Lossy conversions are enabled.
- */
-- (const char *)cStringFromString:(NSString *)theString
-{
- NSMutableData *theData;
-
- if (!theString) {
- return (const char *)NULL;
- }
-
- theData = [NSMutableData dataWithData:[theString dataUsingEncoding:mEncoding allowLossyConversion:YES]];
- [theData increaseLengthBy:1];
-
- return (const char *)[theData bytes];
-}
-
-/**
- * Return a NSString from a C style string encoded with the character set of theMCPConnection.
- */
-- (NSString *)stringWithCString:(const char *)theCString
-{
- if (theCString == NULL) return @"";
-
- return [NSString stringWithCString:theCString encoding:mEncoding];
-}
-
-#pragma mark -
-#pragma mark Other
-
-/**
- * Convert a mysql_type to a string
- */
-- (NSString *)mysqlTypeToStringForType:(NSUInteger)type withCharsetNr:(NSUInteger)charsetnr withFlags:(NSUInteger)flags withLength:(unsigned long long)length
-{
- // BOOL isUnsigned = (flags & UNSIGNED_FLAG) != 0;
- // BOOL isZerofill = (flags & ZEROFILL_FLAG) != 0;
-
- switch (type) {
- case FIELD_TYPE_BIT:
- return @"BIT";
- case MYSQL_TYPE_DECIMAL:
- case MYSQL_TYPE_NEWDECIMAL:
- //return isUnsigned ? (isZerofill? @"DECIMAL UNSIGNED ZEROFILL" : @"DECIMAL UNSIGNED"):
- return @"DECIMAL";
- case MYSQL_TYPE_TINY:
- // return isUnsigned ? (isZerofill? @"TINYINT UNSIGNED ZEROFILL" : @"TINYINT UNSIGNED"):
- return @"TINYINT";
- case MYSQL_TYPE_SHORT:
- // return isUnsigned ? (isZerofill? @"SMALLINT UNSIGNED ZEROFILL" : @"SMALLINT UNSIGNED"):
- return @"SMALLINT";
- case MYSQL_TYPE_LONG:
- // return isUnsigned ? (isZerofill? @"INT UNSIGNED ZEROFILL" : @"INT UNSIGNED"):
- return @"INT";
- case MYSQL_TYPE_FLOAT:
- // return isUnsigned ? (isZerofill? @"FLOAT UNSIGNED ZEROFILL" : @"FLOAT UNSIGNED"):
- return @"FLOAT";
- case MYSQL_TYPE_DOUBLE:
- // return isUnsigned ? (isZerofill? @"DOUBLE UNSIGNED ZEROFILL" : @"DOUBLE UNSIGNED"):
- return @"DOUBLE";
- case MYSQL_TYPE_NULL:
- return @"NULL";
- case MYSQL_TYPE_TIMESTAMP:
- return @"TIMESTAMP";
- case MYSQL_TYPE_LONGLONG:
- // return isUnsigned ? (isZerofill? @"BIGINT UNSIGNED ZEROFILL" : @"BIGINT UNSIGNED") :
- return @"BIGINT";
- case MYSQL_TYPE_INT24:
- // return isUnsigned ? (isZerofill? @"MEDIUMINT UNSIGNED ZEROFILL" : @"MEDIUMINT UNSIGNED") :
- return @"MEDIUMINT";
- case MYSQL_TYPE_DATE:
- return @"DATE";
- case MYSQL_TYPE_TIME:
- return @"TIME";
- case MYSQL_TYPE_DATETIME:
- return @"DATETIME";
- case MYSQL_TYPE_TINY_BLOB:// should no appear over the wire
- case MYSQL_TYPE_MEDIUM_BLOB:// should no appear over the wire
- case MYSQL_TYPE_LONG_BLOB:// should no appear over the wire
- case MYSQL_TYPE_BLOB:
- {
- BOOL isBlob = (charsetnr == MAGIC_BINARY_CHARSET_NR);
- switch ((NSInteger)length/[self findCharsetMaxByteLengthPerChar:charsetnr]) {
- case 255: return isBlob? @"TINYBLOB":@"TINYTEXT";
- case 65535: return isBlob? @"BLOB":@"TEXT";
- case 16777215: return isBlob? @"MEDIUMBLOB":@"MEDIUMTEXT";
- case 4294967295: return isBlob? @"LONGBLOB":@"LONGTEXT";
- default:
- switch (length) {
- case 255: return isBlob? @"TINYBLOB":@"TINYTEXT";
- case 65535: return isBlob? @"BLOB":@"TEXT";
- case 16777215: return isBlob? @"MEDIUMBLOB":@"MEDIUMTEXT";
- case 4294967295: return isBlob? @"LONGBLOB":@"LONGTEXT";
- default:
- return @"UNKNOWN";
- }
- }
- }
- case MYSQL_TYPE_VAR_STRING:
- if (flags & ENUM_FLAG) {
- return @"ENUM";
- }
- if (flags & SET_FLAG) {
- return @"SET";
- }
- if (charsetnr == MAGIC_BINARY_CHARSET_NR) {
- return @"VARBINARY";
- }
- return @"VARCHAR";
- case MYSQL_TYPE_STRING:
- if (flags & ENUM_FLAG) {
- return @"ENUM";
- }
- if (flags & SET_FLAG) {
- return @"SET";
- }
- if ((flags & BINARY_FLAG) && charsetnr == MAGIC_BINARY_CHARSET_NR) {
- return @"BINARY";
- }
- return @"CHAR";
- case MYSQL_TYPE_ENUM:
- /* This should never happen */
- return @"ENUM";
- case MYSQL_TYPE_YEAR:
- return @"YEAR";
- case MYSQL_TYPE_SET:
- /* This should never happen */
- return @"SET";
- case MYSQL_TYPE_GEOMETRY:
- return @"GEOMETRY";
- default:
- return @"UNKNOWN";
- }
-}
-
-/**
- * Merge mysql_types into type groups
- */
-- (NSString *)mysqlTypeToGroupForType:(NSUInteger)type withCharsetNr:(NSUInteger)charsetnr withFlags:(NSUInteger)flags
-{
- switch(type){
- case FIELD_TYPE_BIT:
- return @"bit";
- case MYSQL_TYPE_TINY:
- case MYSQL_TYPE_SHORT:
- case MYSQL_TYPE_LONG:
- case MYSQL_TYPE_LONGLONG:
- case MYSQL_TYPE_INT24:
- return @"integer";
- case MYSQL_TYPE_FLOAT:
- case MYSQL_TYPE_DOUBLE:
- case MYSQL_TYPE_DECIMAL:
- case MYSQL_TYPE_NEWDECIMAL:
- return @"float";
- case MYSQL_TYPE_YEAR:
- case MYSQL_TYPE_DATETIME:
- case MYSQL_TYPE_TIME:
- case MYSQL_TYPE_DATE:
- case MYSQL_TYPE_TIMESTAMP:
- return @"date";
- case MYSQL_TYPE_VAR_STRING:
- if (flags & ENUM_FLAG) {
- return @"enum";
- }
- if (flags & SET_FLAG) {
- return @"enum";
- }
- if (charsetnr == MAGIC_BINARY_CHARSET_NR) {
- return @"binary";
- }
- return @"string";
- case MYSQL_TYPE_STRING:
- if (flags & ENUM_FLAG) {
- return @"enum";
- }
- if (flags & SET_FLAG) {
- return @"enum";
- }
- if ((flags & BINARY_FLAG) && charsetnr == MAGIC_BINARY_CHARSET_NR) {
- return @"binary";
- }
- return @"string";
- case MYSQL_TYPE_TINY_BLOB: // should no appear over the wire
- case MYSQL_TYPE_MEDIUM_BLOB: // should no appear over the wire
- case MYSQL_TYPE_LONG_BLOB: // should no appear over the wire
- case MYSQL_TYPE_BLOB:
- {
- if (charsetnr == MAGIC_BINARY_CHARSET_NR) {
- return @"blobdata";
- } else {
- return @"textdata";
- }
- }
- case MYSQL_TYPE_GEOMETRY:
- return @"geometry";
- default:
- return @"blobdata";
-
- }
-}
-
-/**
- * Convert a mysql_charsetnr into a charset name as string
- */
-- (NSString *)findCharsetName:(NSUInteger)charsetnr
-{
- const OUR_CHARSET * c = our_charsets60;
-
- do {
- if (c->nr == charsetnr)
- return [self stringWithCString:c->name];
- ++c;
- } while (c[0].nr != 0);
-
- return @"UNKNOWN";
-}
-
-/**
- * Convert a mysql_charsetnr into a collation name as string
- */
-- (NSString *)findCharsetCollation:(NSUInteger)charsetnr
-{
- const OUR_CHARSET * c = our_charsets60;
-
- do {
- if (c->nr == charsetnr)
- return [self stringWithCString:c->collation];
- ++c;
- } while (c[0].nr != 0);
-
- return @"UNKNOWN";
-}
-
-/**
- * Return the max byte length to store a char by using
- * a specific mysql_charsetnr
- */
-- (NSUInteger)findCharsetMaxByteLengthPerChar:(NSUInteger)charsetnr
-{
- const OUR_CHARSET * c = our_charsets60;
-
- do {
- if (c->nr == charsetnr)
- return c->char_maxlen;
- ++c;
- } while (c[0].nr != 0);
-
- return 1;
-}
-
-#pragma mark -
-
-/**
- * Do one really needs an explanation for this method? Which by the way you should not use...
- */
-- (void) dealloc
-{
- if (mResult) mysql_free_result(mResult);
- if (mNames) [mNames release];
- if (mTimeZone) [mTimeZone release];
-
- [super dealloc];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.h b/Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.h
deleted file mode 100644
index f161bd0c..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.h
+++ /dev/null
@@ -1,42 +0,0 @@
-//
-// $Id$
-//
-// MCPResultPlus.h
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 03/06/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import <Foundation/Foundation.h>
-
-#import "MCPResult.h"
-
-@interface MCPResult (MCPResultPlus)
-
-// Getting a complete column as an array
-- (NSArray *)fetchColAtIndex:(NSUInteger)col;
-- (NSArray *)fetchColWithName:(NSString *)colName;
-
-// Getting the complete result as 2D array
-- (id)fetch2DResultAsType:(MCPReturnType)type;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.m b/Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.m
deleted file mode 100644
index dbf9d070..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPResultPlus.m
+++ /dev/null
@@ -1,188 +0,0 @@
-//
-// $Id$
-//
-// MCPResultPlus.m
-// MCPKit
-//
-// Created by Serge Cohen (serge.cohen@m4x.org) on 03/06/2002.
-// Copyright (c) 2001 Serge Cohen. All rights reserved.
-//
-// Forked by the Sequel Pro team (sequelpro.com), April 2009
-//
-// 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://mysql-cocoa.sourceforge.net/>
-// More info at <http://code.google.com/p/sequel-pro/>
-
-#import "MCPResultPlus.h"
-
-/**
- * This Category is provided to get shortcuts reformat the table obtained by a MCPResult
- * (fetching a column, a 2D array...).
- */
-@implementation MCPResult (MCPResultPlus)
-
-/**
- * Getting a complete column into a NSArray (1D). The index starts from 0 (first column).
- *
- * The index 0 of the returned array always correspond to the first row (ie: returned NSArray is indexed
- * by row number), the read position is restored after to it's initial position after the read.
- */
-- (NSArray *)fetchColAtIndex:(NSUInteger)col
-{
- NSMutableArray *theCol = [NSMutableArray arrayWithCapacity:(NSUInteger)[self numOfRows]];
- MYSQL_ROW_OFFSET thePosition;
- NSArray *theRow;
-
- if ((mResult == NULL) || ([self numOfRows] == 0)) {
- // If there is no results, returns nil.
- return nil;
- }
- if (col >= mNumOfFields) {
- // Bad column number
- NSLog (@"The index : %ld is not within the range 0 - %ld\n", (long)col, (long)mNumOfFields);
- return nil;
- }
-
- thePosition = mysql_row_tell(mResult);
-
- [self dataSeek:0];
-
- // One might want to have optimized code here. Maybe in later versions
- while ((theRow = [self fetchRowAsType:MCPTypeArray]))
- {
- [theCol addObject:[theRow objectAtIndex:col]];
- }
-
- // Returning to the proper row
- mysql_row_seek(mResult, thePosition);
-
- return [NSArray arrayWithArray:theCol];
-}
-
-/**
- * The same as !{fetchColAtIndex:}, but the choice of the column is done by it's field name. Indeed it is just
- * a wrapper to !{fetchColAtIndex}.
- */
-- (NSArray *)fetchColWithName:(NSString *)colName
-{
- NSUInteger theCol;
-
- if (mResult == NULL) {
- // If there is no results, returns nil.
- return nil;
- }
-
- if (mNames == nil) {
- [self fetchFieldNames];
- }
-
- if ([mNames indexOfObject:colName] == NSNotFound) {
- NSLog(@"No column have been found with name : %@\n", colName);
- return nil;
- }
-
- theCol = [mNames indexOfObject:colName];
-
- return [self fetchColAtIndex:theCol];
-}
-
-/**
- * Returns the complete result table in a 2D object, which type depends on aType:
- *
- * - !{MCPTypeArray} : a NSArray of rows as NSArray,
- *
- * - !{MCPTypeDictionary} : a NSArray of rows as NSDictionary,
- *
- * - !{MCPTypeFlippedArray} : a NSArray of columns (as NSArray),
- *
- * - !{MCPTypeFlippedDictionary} : a NSDictionary of columns (as NSArray)
- *
- * In any case the read position is restored at the end of the call (hence a fetchRow will get the same row
- * wether this method is called before it or not).
- */
-- (id) fetch2DResultAsType:(MCPReturnType)type;
-{
- id theTable, theVect;
- MYSQL_ROW_OFFSET thePosition;
- NSUInteger i;
-
- if (mResult == NULL) {
- // If there is no results, returns nil.
- return nil;
- }
-
- thePosition = mysql_row_tell(mResult);
-
- [self dataSeek:0];
-
- switch (type)
- {
- case MCPTypeArray :
- theTable = [NSMutableArray arrayWithCapacity:(NSUInteger)[self numOfRows]];
-
- while ((theVect = [self fetchRowAsArray]))
- {
- [theTable addObject:theVect];
- }
-
- theTable = [NSArray arrayWithArray:theTable];
- break;
- case MCPTypeDictionary :
- theTable = [NSMutableArray arrayWithCapacity:(NSUInteger)[self numOfRows]];
-
- while ((theVect = [self fetchRowAsDictionary]))
- {
- [theTable addObject:theVect];
- }
-
- theTable = [NSArray arrayWithArray:theTable];
- break;
- case MCPTypeFlippedArray :
- theTable = [NSMutableArray arrayWithCapacity:mNumOfFields];
-
- for (i=0; i<mNumOfFields; i++)
- {
- [theTable addObject:[self fetchColAtIndex:i]];
- }
-
- theTable = [NSArray arrayWithArray:theTable];
- break;
- case MCPTypeFlippedDictionary :
- theTable = [NSMutableDictionary dictionaryWithCapacity:mNumOfFields];
-
- if (mNames == nil) {
- [self fetchFieldNames];
- }
-
- for (i=0; i<mNumOfFields; i++)
- {
- [theTable setObject:[self fetchColAtIndex:i] forKey:[mNames objectAtIndex:i]];
- }
-
- theTable = [NSDictionary dictionaryWithDictionary:theTable];
- break;
- default :
- NSLog (@"Unknown MCPReturnType : %d; return nil\n", (int)type);
- theTable = nil;
- break;
- }
-
- mysql_row_seek(mResult, thePosition);
-
- return theTable;
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.h b/Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.h
deleted file mode 100644
index e8230fff..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.h
+++ /dev/null
@@ -1,74 +0,0 @@
-//
-// $Id$
-//
-// MCPStreamingResult.h
-// sequel-pro
-//
-// Created by Rowan Beentje on Aug 16, 2009
-// Copyright 2009 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 <Foundation/Foundation.h>
-
-#import "MCPResult.h"
-#import "mysql.h"
-
-@class MCPConnection;
-
-typedef struct SP_MYSQL_ROWS {
- char *data;
- unsigned long *dataLengths;
- struct SP_MYSQL_ROWS *nextRow;
-} LOCAL_ROW_DATA;
-
-@interface MCPStreamingResult : MCPResult
-{
- MCPConnection *parentConnection;
-
- MYSQL_FIELD *fieldDefinitions;
-
- BOOL fullyStreaming;
- BOOL connectionUnlocked;
- BOOL dataDownloaded;
- BOOL dataFreed;
-
- LOCAL_ROW_DATA *localDataStore;
- LOCAL_ROW_DATA *currentDataStoreEntry;
- LOCAL_ROW_DATA *localDataStoreLastEntry;
-
- unsigned long localDataRows;
- unsigned long localDataAllocated;
- unsigned long downloadedRowCount;
- unsigned long processedRowCount;
- unsigned long freedRowCount;
-
- pthread_mutex_t dataCreationLock;
- pthread_mutex_t dataFreeLock;
-
- IMP isConnectedPtr;
- SEL isConnectedSEL;
-}
-
-- (id)initWithMySQLPtr:(MYSQL *)mySQLPtr encoding:(NSStringEncoding)theEncoding timeZone:(NSTimeZone *)theTimeZone connection:(MCPConnection *)theConnection;
-- (id)initWithMySQLPtr:(MYSQL *)mySQLPtr encoding:(NSStringEncoding)theEncoding timeZone:(NSTimeZone *)theTimeZone connection:(MCPConnection *)theConnection withFullStreaming:(BOOL)useFullStreaming;
-
-// Results fetching
-- (NSArray *)fetchNextRowAsArray;
-- (void) cancelResultLoad;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.m b/Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.m
deleted file mode 100644
index bdb271fe..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPStreamingResult.m
+++ /dev/null
@@ -1,566 +0,0 @@
-//
-// $Id$
-//
-// MCPStreamingResult.m
-// sequel-pro
-//
-// Created by Rowan Beentje on Aug 16, 2009
-// Copyright 2009 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 "MCPStreamingResult.h"
-#import "MCPConnection.h"
-#import "MCPNull.h"
-#import "MCPNumber.h"
-#import "MCPGeometryData.h"
-
-/**
- * IMPORTANT NOTE
- *
- * MCPStreamingResult can operate in two modes. The default mode is a safe implementation,
- * which operates in a multithreaded fashion - a worker thread is set up to download the results as
- * fast as possible in the background, while the results are made available via a blocking (and so
- * single-thread-compatible) fetchNextRowAsArray call. This provides the benefit of allowing a progress
- * bar to be shown during downloads, and threaded processing, but still has reasonable memory usage for
- * the downloaded result - and won't block the server.
- * Alternatively, withFullStreaming: can be set to YES, in which case each row will be accessed on-demand;
- * this can be dangerous as it means a SELECT will tie up the server for longer, as for MyISAM tables
- * updates (and subsequent reads) must block while a SELECT is still running. However this can be useful
- * for certain processes such as working with very large tables to keep memory usage low.
- */
-
-
-@interface MCPStreamingResult (PrivateAPI)
-
-void _bytes2bin(Byte *n, NSUInteger nbytes, NSUInteger len, char *buf);
-
-- (void) _downloadAllData;
-- (void) _freeAllDataWhenDone;
-
-@end
-
-@implementation MCPStreamingResult : MCPResult
-
-#pragma mark -
-#pragma mark Setup and teardown
-
-/**
- * Initialise a MCPStreamingResult in the same way as MCPResult - as used
- * internally by the MCPConnection !{queryString:} method.
- */
-- (id)initWithMySQLPtr:(MYSQL *)mySQLPtr encoding:(NSStringEncoding)theEncoding timeZone:(NSTimeZone *)theTimeZone connection:(MCPConnection *)theConnection
-{
- return [self initWithMySQLPtr:mySQLPtr encoding:theEncoding timeZone:theTimeZone connection:theConnection withFullStreaming:NO];
-}
-
-/**
- * Master initialisation method, allowing selection of either full streaming or safe streaming
- * (see "important note" above)
- */
-- (id)initWithMySQLPtr:(MYSQL *)mySQLPtr encoding:(NSStringEncoding)theEncoding timeZone:(NSTimeZone *)theTimeZone connection:(MCPConnection *)theConnection withFullStreaming:(BOOL)useFullStreaming
-{
- if ((self = [super init])) {
- mEncoding = theEncoding;
- mTimeZone = [theTimeZone retain];
- parentConnection = theConnection;
- fullyStreaming = useFullStreaming;
- connectionUnlocked = NO;
-
- if (mResult) {
- mysql_free_result(mResult);
- mResult = NULL;
- }
-
- if (mNames) {
- [mNames release];
- mNames = nil;
- }
-
- mResult = mysql_use_result(mySQLPtr);
-
- if (mResult) {
- mNumOfFields = mysql_num_fields(mResult);
- fieldDefinitions = mysql_fetch_fields(mResult);
- } else {
- mNumOfFields = 0;
- }
-
- // Obtain SEL references and pointer
- isConnectedSEL = @selector(isConnected);
- isConnectedPtr = [parentConnection methodForSelector:isConnectedSEL];
-
- // If the result is opened in download-data-fast safe mode, set up the additional variables
- // and threads required.
- if (!fullyStreaming) {
- dataDownloaded = NO;
- dataFreed = NO;
- localDataStore = NULL;
- currentDataStoreEntry = NULL;
- localDataStoreLastEntry = NULL;
- localDataRows = 0;
- localDataAllocated = 0;
- downloadedRowCount = 0;
- processedRowCount = 0;
- freedRowCount = 0;
- pthread_mutex_init(&dataCreationLock, NULL);
- pthread_mutex_init(&dataFreeLock, NULL);
-
- // Start the data download thread
- [NSThread detachNewThreadSelector:@selector(_downloadAllData) toTarget:self withObject:nil];
-
- // Start the data freeing thread
- [NSThread detachNewThreadSelector:@selector(_freeAllDataWhenDone) toTarget:self withObject:nil];
- }
- }
-
- return self;
-}
-
-/**
- * Deallocate the result and unlock the parent connection for further use
- */
-- (void) dealloc
-{
- [self cancelResultLoad]; //this should close the connection if it is still open
-
- if (!connectionUnlocked) {
- //this should NEVER happen
- NSLog(@"MCPStreamingResult: The connection has not been unlocked.");
- [parentConnection unlockConnection];
- }
-
- if (!fullyStreaming) {
- pthread_mutex_destroy(&dataFreeLock);
- pthread_mutex_destroy(&dataCreationLock);
- }
-
- [super dealloc];
-}
-
-#pragma mark -
-#pragma mark Results fetching
-
-/**
- * Retrieve the next row of the result as an array. Should be called in a loop
- * until nil is returned to ensure all the results have been retrieved.
- */
-- (NSArray *)fetchNextRowAsArray
-{
- MYSQL_ROW theRow;
- char *theRowData, *buf;
- unsigned long *fieldLengths;
- NSUInteger i, copiedDataLength;
- NSMutableArray *returnArray;
-
- // Retrieve the next row according to the mode this result set is in.
- // If fully streaming, retrieve the MYSQL_ROW
- if (fullyStreaming) {
- theRow = mysql_fetch_row(mResult);
-
- // If no data was returned, we're at the end of the result set - unlock the connection and return nil
- if (theRow == NULL) {
- if (!connectionUnlocked) {
- [parentConnection unlockConnection];
- connectionUnlocked = YES;
- }
- return nil;
- }
-
- // Retrieve the lengths of the returned data
- fieldLengths = mysql_fetch_lengths(mResult);
-
- // If in cached-streaming/fast download mode, get a reference to the data for the current row
- } else {
- copiedDataLength = 0;
-
- // Lock the data mutex
- pthread_mutex_lock(&dataCreationLock);
-
- // Check to see whether we need to wait for the data to be availabe
- // - if so, wait 1ms before checking again.
- while (!dataDownloaded && processedRowCount == downloadedRowCount) {
- pthread_mutex_unlock(&dataCreationLock);
- usleep(1000);
- pthread_mutex_lock(&dataCreationLock);
- }
-
- // If all rows have been processed, we're at the end of the result set - return nil
- // once all memory has been freed
- if (processedRowCount == downloadedRowCount) {
- pthread_mutex_unlock(&dataCreationLock);
-
- while (!dataFreed) usleep(1000);
-
- // Update the connection's error statuses in case of error during content download
- [parentConnection updateErrorStatuses];
-
- return nil;
- }
-
- // Retrieve a reference to the data and the associated lengths
- theRowData = currentDataStoreEntry->data;
- fieldLengths = currentDataStoreEntry->dataLengths;
-
- // Unlock the data mutex
- pthread_mutex_unlock(&dataCreationLock);
- }
-
- // Initialise the array to return
- returnArray = [NSMutableArray arrayWithCapacity:mNumOfFields];
- for (i = 0; i < mNumOfFields; i++) {
- id cellData = nil;
- char *theData = NULL;
-
- // In fully streaming mode, get a reference to the data for the MYSQL_ROW
- if (fullyStreaming) {
- if (theRow[i] == NULL) {
- cellData = [NSNull null];
- } else {
- theData = theRow[i];
- }
-
- // In cached-streaming mode, use a reference to the downloaded data
- } else {
- if (fieldLengths[i] == NSNotFound) {
- cellData = [NSNull null];
- } else {
- theData = theRowData+copiedDataLength;
- copiedDataLength += fieldLengths[i] + 1;
- }
- }
-
- // If the data hasn't already been detected as NULL - in which case it will have been
- // set to NSNull - process the data by type
-
- if (cellData == nil) {
- switch (fieldDefinitions[i].type) {
- case FIELD_TYPE_TINY:
- case FIELD_TYPE_SHORT:
- case FIELD_TYPE_INT24:
- case FIELD_TYPE_LONG:
- case FIELD_TYPE_LONGLONG:
- case FIELD_TYPE_DECIMAL:
- case FIELD_TYPE_NEWDECIMAL:
- case FIELD_TYPE_FLOAT:
- case FIELD_TYPE_DOUBLE:
- case FIELD_TYPE_TIMESTAMP:
- case FIELD_TYPE_DATE:
- case FIELD_TYPE_TIME:
- case FIELD_TYPE_DATETIME:
- case FIELD_TYPE_YEAR:
- case FIELD_TYPE_VAR_STRING:
- case FIELD_TYPE_STRING:
- case FIELD_TYPE_SET:
- case FIELD_TYPE_ENUM:
- case FIELD_TYPE_NEWDATE: // Don't know what the format for this type is...
-
- // For fields of type BINARY/VARBINARY, return the data. Also add an extra check to make
- // sure it's binary data (seems that it's returned as type STRING) to get around a MySQL
- // bug (#28214) returning DATE fields with the binary flag set.
- if ((fieldDefinitions[i].flags & BINARY_FLAG) &&
- (fieldDefinitions[i].type == FIELD_TYPE_STRING || fieldDefinitions[i].type == FIELD_TYPE_VAR_STRING))
- {
- cellData = [NSData dataWithBytes:theData length:fieldLengths[i]];
- }
- // For string data, convert to text
- else {
- cellData = [[[NSString alloc] initWithBytes:theData length:fieldLengths[i] encoding:mEncoding] autorelease];
- }
-
- break;
-
- case FIELD_TYPE_BIT:
- // Get a binary representation of the data
-
- buf = malloc(fieldDefinitions[i].length + 1);
- _bytes2bin((Byte *)theData, fieldLengths[i], fieldDefinitions[i].length, buf);
-
- cellData = (theData != NULL) ? [NSString stringWithUTF8String:buf] : @"";
-
- free(buf);
- break;
-
- case FIELD_TYPE_TINY_BLOB:
- case FIELD_TYPE_BLOB:
- case FIELD_TYPE_MEDIUM_BLOB:
- case FIELD_TYPE_LONG_BLOB:
-
- // For binary data, return the data if force-return-as-string is not enabled
- if ((fieldDefinitions[i].flags & BINARY_FLAG) && !mReturnDataAsStrings) {
- cellData = [NSData dataWithBytes:theData length:fieldLengths[i]];
- }
- else {
- cellData = [[NSString alloc] initWithBytes:theData length:fieldLengths[i] encoding:mEncoding];
-
- if (cellData) [cellData autorelease];
- }
-
- break;
-
- case FIELD_TYPE_NULL:
- cellData = [NSNull null];
- break;
-
- case FIELD_TYPE_GEOMETRY:
- cellData = [MCPGeometryData dataWithBytes:theData length:fieldLengths[i]];
- break;
-
- default:
- NSLog(@"in fetchNextRowAsArray : Unknown type : %d for column %lu, sending back a NSData object", (int)fieldDefinitions[i].type, (unsigned long)i);
- cellData = [NSData dataWithBytes:theData length:fieldLengths[i]];
- break;
- }
-
- // If a creator returned a nil object, replace with NSNull
- if (cellData == nil) cellData = [NSNull null];
- }
-
- [returnArray insertObject:cellData atIndex:i];
- }
-
- // If in cached-streaming mode, update the current entry processed count
- if (!fullyStreaming) {
-
- // Lock both mutexes
- pthread_mutex_lock(&dataCreationLock);
- pthread_mutex_lock(&dataFreeLock);
-
- // Update the active-data pointer to the next item in the list, or set to NULL if no more items
- currentDataStoreEntry = currentDataStoreEntry->nextRow;
-
- // Increment counter
- processedRowCount++;
-
- // Unlock both mutexes
- pthread_mutex_unlock(&dataCreationLock);
- pthread_mutex_unlock(&dataFreeLock);
- }
-
- return returnArray;
-}
-
-/*
- * Ensure the result set is fully processed and freed without any processing
- * This method ensures that the connection is unlocked.
- */
-- (void) cancelResultLoad
-{
- MYSQL_ROW theRow;
-
- // Loop through all the rows and ensure the rows are fetched.
- // If fully streaming, loop through the rows directly
- if (fullyStreaming) {
- while (1) {
- theRow = mysql_fetch_row(mResult);
-
- // If no data was returned, we're at the end of the result set - return.
- if (theRow == NULL) {
- if (!connectionUnlocked) {
- [parentConnection unlockConnection];
- connectionUnlocked = YES;
- }
- return;
- }
- }
-
- // If in cached-streaming/fast download mode, loop until all data is fetched and freed
- } else {
-
- while (1) {
-
- // Check to see whether we need to wait for the data to be available
- // - if so, wait 1ms before checking again
- while (!dataDownloaded && processedRowCount == downloadedRowCount) usleep(1000);
-
- // If all rows have been processed, we're at the end of the result set - return
- // once all memory has been freed
- if (processedRowCount == downloadedRowCount) {
- while (!dataFreed) usleep(1000);
- // we don't need to unlock the connection because
- // the data loading thread already did that
- return;
- }
- processedRowCount++;
- }
- }
-}
-
-#pragma mark -
-#pragma mark Overrides for safety
-
-/**
- * If numOfRows is used before the data is fully downloaded, -1 will be returned;
- * otherwise the number of rows is returned.
- */
-- (my_ulonglong)numOfRows
-{
- if (!dataDownloaded) return -1;
-
- return downloadedRowCount;
-}
-
-- (void)dataSeek:(my_ulonglong) row
-{
- NSLog(@"dataSeek cannot be used with streaming results");
-}
-
-@end
-
-@implementation MCPStreamingResult (PrivateAPI)
-
-/**
- * Provides a binary representation of the supplied chars (n) in the supplied buffer (buf). The resulting
- * binary representation will be zero-padded according to the supplied field length (len).
- */
-void _bytes2bin(Byte *n, NSUInteger nbytes, NSUInteger len, char *buf)
-{
-
- // NSUInteger i = 0;
- // nbytes--;
- // while (++i <= len)
- // buf[len - i] = ( (n[nbytes - (i >> 3)] >> (i & 0x7)) & 1 ) ? '1' : '0';
- //
- // buf[len] = '\0';
- // ↑ why does this code not working anymore?
-
- NSUInteger i = 0;
- nbytes--;
- len--;
- while (i <= len)
- buf[len - i++] = ( (n[nbytes - (i >> 3)] >> (i & 0x7)) & 1 ) ? '1' : '0';
-
- buf[len+1] = '\0';
-
-}
-
-/**
- * Used internally to download results in a background thread
- */
-- (void)_downloadAllData
-{
- NSAutoreleasePool *downloadPool = [[NSAutoreleasePool alloc] init];
- MYSQL_ROW theRow;
- unsigned long *fieldLengths;
- NSUInteger i, dataCopiedLength, rowDataLength;
- LOCAL_ROW_DATA *newRowStore;
-
- size_t sizeOfLocalRowData = sizeof(LOCAL_ROW_DATA);
- size_t sizeOfDataLengths = (size_t)(sizeof(unsigned long) * mNumOfFields);
-
- // Loop through the rows until the end of the data is reached - indicated via a NULL
- while ((*isConnectedPtr)(parentConnection, isConnectedSEL) && (theRow = mysql_fetch_row(mResult))) {
-
- // Retrieve the lengths of the returned data
- fieldLengths = mysql_fetch_lengths(mResult);
- rowDataLength = 0;
- dataCopiedLength = 0;
- for (i = 0; i < mNumOfFields; i++)
- rowDataLength += fieldLengths[i];
-
- // Initialise memory for the row and set a NULL pointer for the next item
- newRowStore = malloc(sizeOfLocalRowData);
- newRowStore->nextRow = NULL;
-
- // Set up the row data store - a char* - and copy in the data if there is any,
- // using a null terminator for each field boundary for easier data processing later
- newRowStore->data = malloc(sizeof(char) * (rowDataLength + mNumOfFields));
- for (i = 0; i < mNumOfFields; i++) {
- if (theRow[i] != NULL) {
- memcpy(newRowStore->data+dataCopiedLength, theRow[i], fieldLengths[i]);
- newRowStore->data[dataCopiedLength+fieldLengths[i]] = '\0';
- dataCopiedLength += fieldLengths[i] + 1;
- } else {
- fieldLengths[i] = NSNotFound;
- }
- }
-
- // Set up and copy in the field lengths
- newRowStore->dataLengths = memcpy(malloc(sizeOfDataLengths), fieldLengths, sizeOfDataLengths);
-
- // Lock both mutexes
- pthread_mutex_lock(&dataCreationLock);
- pthread_mutex_lock(&dataFreeLock);
-
- // Add the newly allocated row to end of the storage linked list
- if (localDataStore) {
- localDataStoreLastEntry->nextRow = newRowStore;
- } else {
- localDataStore = newRowStore;
- }
- localDataStoreLastEntry = newRowStore;
- if (!currentDataStoreEntry) currentDataStoreEntry = newRowStore;
-
- // Update the downloaded row count
- downloadedRowCount++;
-
- // Unlock both mutexes
- pthread_mutex_unlock(&dataCreationLock);
- pthread_mutex_unlock(&dataFreeLock);
- }
-
- // Unlock the parent connection now data has been retrieved
- [parentConnection unlockConnection];
- connectionUnlocked = YES;
-
- dataDownloaded = YES;
- [downloadPool drain];
-}
-
-/**
- * Used internally to free data which has been fully processed; done in a thread to allow
- * fetchNextRowAsArray to be faster.
- */
-- (void) _freeAllDataWhenDone
-{
- NSAutoreleasePool *dataFreeingPool = [[NSAutoreleasePool alloc] init];
-
- while (!dataDownloaded || freedRowCount != downloadedRowCount) {
-
- // Lock the data free mutex
- pthread_mutex_lock(&dataFreeLock);
-
- // If the freed row count matches the processed row count, wait before retrying
- if (freedRowCount == processedRowCount) {
- pthread_mutex_unlock(&dataFreeLock);
- usleep(1000);
- continue;
- }
-
- // Free a single item off the bottom of the list
- // Update the data pointer to the next item in the list, or set to NULL if no more items
- LOCAL_ROW_DATA *rowToRemove = localDataStore;
- localDataStore = localDataStore->nextRow;
-
- // Free memory for the first row
- rowToRemove->nextRow = NULL;
- free(rowToRemove->dataLengths);
- if (rowToRemove->data != NULL) free(rowToRemove->data);
- free(rowToRemove);
-
- // Increment the counter
- freedRowCount++;
-
- // Unlock the data free mutex
- pthread_mutex_unlock(&dataFreeLock);
- }
-
- dataFreed = YES;
- [dataFreeingPool drain];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.h b/Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.h
deleted file mode 100644
index bf57b789..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.h
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// $Id$
-//
-// MCPStringAdditions.h
-// sequel-pro
-//
-// Created by Stuart Connolly (stuconnolly.com) on March 25, 2010
-// Copyright (c) 2010 Stuart Connolly. 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 <Foundation/Foundation.h>
-
-/**
- * NSStringDataUsingLossyEncoding(aStr, enc, lossy) := [aStr dataUsingEncoding:enc allowLossyConversion:lossy]
- */
-static inline NSData *NSStringDataUsingLossyEncoding(NSString *self, NSInteger encoding, NSInteger lossy)
-{
- typedef NSData *(*SPStringDataUsingLossyEncodingMethodPtr)(NSString*, SEL, NSInteger, NSInteger);
- static SPStringDataUsingLossyEncodingMethodPtr SPNSStringDataUsingLossyEncoding;
-
- if (!SPNSStringDataUsingLossyEncoding) SPNSStringDataUsingLossyEncoding = (SPStringDataUsingLossyEncodingMethodPtr)[self methodForSelector:@selector(dataUsingEncoding:allowLossyConversion:)];
-
- return SPNSStringDataUsingLossyEncoding(self, @selector(dataUsingEncoding:allowLossyConversion:), encoding, lossy);
-}
-
-@interface NSString (MCPStringAdditions)
-
-- (NSString *)backtickQuotedString;
-- (NSString *)tickQuotedString;
-
-@end
diff --git a/Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.m b/Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.m
deleted file mode 100644
index bd5b06cd..00000000
--- a/Frameworks/MCPKit/MCPFoundationKit/MCPStringAdditions.m
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// $Id$
-//
-// MCPStringAdditions.m
-// sequel-pro
-//
-// Created by Stuart Connolly (stuconnolly.com) on March 25, 2010
-// Copyright (c) 2010 Stuart Connolly. 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/>
-
-
-
-@implementation NSString (MCPStringAdditions)
-
-/**
- * Returns the string quoted with backticks as required for MySQL identifiers
- * eg.: tablename => `tablename`
- * my`table => `my``table`
- */
-- (NSString *)backtickQuotedString
-{
- return [NSString stringWithFormat: @"`%@`", [self stringByReplacingOccurrencesOfString:@"`" withString:@"``"]];
-}
-
-/**
- * Returns the string quoted with ticks as required for MySQL identifiers
- * eg.: tablename => 'tablename'
- * my'table => 'my''table'
- */
-- (NSString *)tickQuotedString
-{
- return [NSString stringWithFormat: @"'%@'", [self stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
-}
-
-@end
diff --git a/Frameworks/MCPKit/MySQL/include/my_alloc.h b/Frameworks/MCPKit/MySQL/include/my_alloc.h
deleted file mode 100644
index 93b7438a..00000000
--- a/Frameworks/MCPKit/MySQL/include/my_alloc.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (C) 2000 MySQL AB
-
- 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; version 2 of the License.
-
- 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 */
-
-/*
- Data structures for mysys/my_alloc.c (root memory allocator)
-*/
-
-#ifndef _my_alloc_h
-#define _my_alloc_h
-
-#define ALLOC_MAX_BLOCK_TO_DROP 4096
-#define ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP 10
-
-typedef struct st_used_mem
-{ /* struct for once_alloc (block) */
- struct st_used_mem *next; /* Next block in use */
- unsigned int left; /* memory left in block */
- unsigned int size; /* size of block */
-} USED_MEM;
-
-
-typedef struct st_mem_root
-{
- USED_MEM *free; /* blocks with free memory in it */
- USED_MEM *used; /* blocks almost without free memory */
- USED_MEM *pre_alloc; /* preallocated block */
- /* if block have less memory it will be put in 'used' list */
- size_t min_malloc;
- size_t block_size; /* initial block size */
- unsigned int block_num; /* allocated blocks counter */
- /*
- first free block in queue test counter (if it exceed
- MAX_BLOCK_USAGE_BEFORE_DROP block will be dropped in 'used' list)
- */
- unsigned int first_block_usage;
-
- void (*error_handler)(void);
-} MEM_ROOT;
-#endif
diff --git a/Frameworks/MCPKit/MySQL/include/my_list.h b/Frameworks/MCPKit/MySQL/include/my_list.h
deleted file mode 100644
index 775b5658..00000000
--- a/Frameworks/MCPKit/MySQL/include/my_list.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Copyright (C) 2000 MySQL AB
-
- 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; version 2 of the License.
-
- 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 */
-
-#ifndef _list_h_
-#define _list_h_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct st_list {
- struct st_list *prev,*next;
- void *data;
-} LIST;
-
-typedef int (*list_walk_action)(void *,void *);
-
-extern LIST *list_add(LIST *root,LIST *element);
-extern LIST *list_delete(LIST *root,LIST *element);
-extern LIST *list_cons(void *data,LIST *root);
-extern LIST *list_reverse(LIST *root);
-extern void list_free(LIST *root,unsigned int free_data);
-extern unsigned int list_length(LIST *);
-extern int list_walk(LIST *,list_walk_action action,unsigned char * argument);
-
-#define list_rest(a) ((a)->next)
-#define list_push(a,b) (a)=list_cons((b),(a))
-#define list_pop(A) {LIST *old=(A); (A)=list_delete(old,old) ; my_free((unsigned char *) old,MYF(MY_FAE)); }
-
-#ifdef __cplusplus
-}
-#endif
-#endif
diff --git a/Frameworks/MCPKit/MySQL/include/mysql.h b/Frameworks/MCPKit/MySQL/include/mysql.h
deleted file mode 100644
index 699bd1f1..00000000
--- a/Frameworks/MCPKit/MySQL/include/mysql.h
+++ /dev/null
@@ -1,870 +0,0 @@
-/* Copyright (C) 2000-2003 MySQL AB
-
- 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; version 2 of the License.
-
- 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 */
-
-/*
- This file defines the client API to MySQL and also the ABI of the
- dynamically linked libmysqlclient.
-
- The ABI should never be changed in a released product of MySQL
- thus you need to take great care when changing the file. In case
- the file is changed so the ABI is broken, you must also
- update the SHAREDLIB_MAJOR_VERSION in configure.in .
-
-*/
-
-#ifndef _mysql_h
-#define _mysql_h
-
-#ifdef _AIX /* large-file support will break without this */
-#include <standards.h>
-#endif
-
-#ifdef __CYGWIN__ /* CYGWIN implements a UNIX API */
-#undef WIN
-#undef _WIN
-#undef _WIN32
-#undef _WIN64
-#undef __WIN__
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef _global_h /* If not standard header */
-#ifndef MYSQL_ABI_CHECK
-#include <sys/types.h>
-#endif
-#ifdef __LCC__
-#include <winsock2.h> /* For windows */
-#endif
-typedef char my_bool;
-#if (defined(_WIN32) || defined(_WIN64)) && !defined(__WIN__)
-#define __WIN__
-#endif
-#if !defined(__WIN__)
-#define STDCALL
-#else
-#define STDCALL __stdcall
-#endif
-
-#ifndef my_socket_defined
-#ifdef __WIN__
-#define my_socket SOCKET
-#else
-typedef int my_socket;
-#endif /* __WIN__ */
-#endif /* my_socket_defined */
-#endif /* _global_h */
-
-#include "mysql_version.h"
-#include "mysql_com.h"
-#include "mysql_time.h"
-
-#include "my_list.h" /* for LISTs used in 'MYSQL' and 'MYSQL_STMT' */
-
-extern unsigned int mysql_port;
-extern char *mysql_unix_port;
-
-#define CLIENT_NET_READ_TIMEOUT 365*24*3600 /* Timeout on read */
-#define CLIENT_NET_WRITE_TIMEOUT 365*24*3600 /* Timeout on write */
-
-#ifdef __NETWARE__
-#pragma pack(push, 8) /* 8 byte alignment */
-#endif
-
-#define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG)
-#define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG)
-#define IS_BLOB(n) ((n) & BLOB_FLAG)
-#define IS_NUM(t) ((t) <= MYSQL_TYPE_INT24 || (t) == MYSQL_TYPE_YEAR || (t) == MYSQL_TYPE_NEWDECIMAL)
-#define IS_NUM_FIELD(f) ((f)->flags & NUM_FLAG)
-#define INTERNAL_NUM_FIELD(f) (((f)->type <= MYSQL_TYPE_INT24 && ((f)->type != MYSQL_TYPE_TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == MYSQL_TYPE_YEAR)
-#define IS_LONGDATA(t) ((t) >= MYSQL_TYPE_TINY_BLOB && (t) <= MYSQL_TYPE_STRING)
-
-
-typedef struct st_mysql_field {
- char *name; /* Name of column */
- char *org_name; /* Original column name, if an alias */
- char *table; /* Table of column if column was a field */
- char *org_table; /* Org table name, if table was an alias */
- char *db; /* Database for table */
- char *catalog; /* Catalog for table */
- char *def; /* Default value (set by mysql_list_fields) */
- unsigned long length; /* Width of column (create length) */
- unsigned long max_length; /* Max width for selected set */
- unsigned int name_length;
- unsigned int org_name_length;
- unsigned int table_length;
- unsigned int org_table_length;
- unsigned int db_length;
- unsigned int catalog_length;
- unsigned int def_length;
- unsigned int flags; /* Div flags */
- unsigned int decimals; /* Number of decimals in field */
- unsigned int charsetnr; /* Character set */
- enum enum_field_types type; /* Type of field. See mysql_com.h for types */
- void *extension;
-} MYSQL_FIELD;
-
-typedef char **MYSQL_ROW; /* return data as array of strings */
-typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */
-
-#ifndef _global_h
-#if defined(NO_CLIENT_LONG_LONG)
-typedef unsigned long my_ulonglong;
-#elif defined (__WIN__)
-typedef unsigned __int64 my_ulonglong;
-#else
-typedef unsigned long long my_ulonglong;
-#endif
-#endif
-
-#include "typelib.h"
-
-#define MYSQL_COUNT_ERROR (~(my_ulonglong) 0)
-
-/* backward compatibility define - to be removed eventually */
-#define ER_WARN_DATA_TRUNCATED WARN_DATA_TRUNCATED
-
-typedef struct st_mysql_rows {
- struct st_mysql_rows *next; /* list of rows */
- MYSQL_ROW data;
- unsigned long length;
-} MYSQL_ROWS;
-
-typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */
-
-#include "my_alloc.h"
-
-typedef struct embedded_query_result EMBEDDED_QUERY_RESULT;
-typedef struct st_mysql_data {
- MYSQL_ROWS *data;
- struct embedded_query_result *embedded_info;
- MEM_ROOT alloc;
- my_ulonglong rows;
- unsigned int fields;
- /* extra info for embedded library */
- void *extension;
-} MYSQL_DATA;
-
-enum mysql_option
-{
- MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE,
- MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP,
- MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE,
- MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT,
- MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT,
- MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION,
- MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH,
- MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT,
- MYSQL_OPT_SSL_VERIFY_SERVER_CERT
-};
-
-struct st_mysql_options {
- unsigned int connect_timeout, read_timeout, write_timeout;
- unsigned int port, protocol;
- unsigned long client_flag;
- char *host,*user,*password,*unix_socket,*db;
- struct st_dynamic_array *init_commands;
- char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name;
- char *ssl_key; /* PEM key file */
- char *ssl_cert; /* PEM cert file */
- char *ssl_ca; /* PEM CA file */
- char *ssl_capath; /* PEM directory of CA-s? */
- char *ssl_cipher; /* cipher to use */
- char *shared_memory_base_name;
- unsigned long max_allowed_packet;
- my_bool use_ssl; /* if to use SSL or not */
- my_bool compress,named_pipe;
- /*
- On connect, find out the replication role of the server, and
- establish connections to all the peers
- */
- my_bool rpl_probe;
- /*
- Each call to mysql_real_query() will parse it to tell if it is a read
- or a write, and direct it to the slave or the master
- */
- my_bool rpl_parse;
- /*
- If set, never read from a master, only from slave, when doing
- a read that is replication-aware
- */
- my_bool no_master_reads;
-#if !defined(CHECK_EMBEDDED_DIFFERENCES) || defined(EMBEDDED_LIBRARY)
- my_bool separate_thread;
-#endif
- enum mysql_option methods_to_use;
- char *client_ip;
- /* Refuse client connecting to server if it uses old (pre-4.1.1) protocol */
- my_bool secure_auth;
- /* 0 - never report, 1 - always report (default) */
- my_bool report_data_truncation;
-
- /* function pointers for local infile support */
- int (*local_infile_init)(void **, const char *, void *);
- int (*local_infile_read)(void *, char *, unsigned int);
- void (*local_infile_end)(void *);
- int (*local_infile_error)(void *, char *, unsigned int);
- void *local_infile_userdata;
- void *extension;
-};
-
-enum mysql_status
-{
- MYSQL_STATUS_READY, MYSQL_STATUS_GET_RESULT, MYSQL_STATUS_USE_RESULT,
- MYSQL_STATUS_STATEMENT_GET_RESULT
-};
-
-enum mysql_protocol_type
-{
- MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET,
- MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY
-};
-/*
- There are three types of queries - the ones that have to go to
- the master, the ones that go to a slave, and the adminstrative
- type which must happen on the pivot connectioin
-*/
-enum mysql_rpl_type
-{
- MYSQL_RPL_MASTER, MYSQL_RPL_SLAVE, MYSQL_RPL_ADMIN
-};
-
-typedef struct character_set
-{
- unsigned int number; /* character set number */
- unsigned int state; /* character set state */
- const char *csname; /* collation name */
- const char *name; /* character set name */
- const char *comment; /* comment */
- const char *dir; /* character set directory */
- unsigned int mbminlen; /* min. length for multibyte strings */
- unsigned int mbmaxlen; /* max. length for multibyte strings */
-} MY_CHARSET_INFO;
-
-struct st_mysql_methods;
-struct st_mysql_stmt;
-
-typedef struct st_mysql
-{
- NET net; /* Communication parameters */
- unsigned char *connector_fd; /* ConnectorFd for SSL */
- char *host,*user,*passwd,*unix_socket,*server_version,*host_info;
- char *info, *db;
- struct charset_info_st *charset;
- MYSQL_FIELD *fields;
- MEM_ROOT field_alloc;
- my_ulonglong affected_rows;
- my_ulonglong insert_id; /* id if insert on table with NEXTNR */
- my_ulonglong extra_info; /* Not used */
- unsigned long thread_id; /* Id for connection in server */
- unsigned long packet_length;
- unsigned int port;
- unsigned long client_flag,server_capabilities;
- unsigned int protocol_version;
- unsigned int field_count;
- unsigned int server_status;
- unsigned int server_language;
- unsigned int warning_count;
- struct st_mysql_options options;
- enum mysql_status status;
- my_bool free_me; /* If free in mysql_close */
- my_bool reconnect; /* set to 1 if automatic reconnect */
-
- /* session-wide random string */
- char scramble[SCRAMBLE_LENGTH+1];
-
- /*
- Set if this is the original connection, not a master or a slave we have
- added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
- */
- my_bool rpl_pivot;
- /*
- Pointers to the master, and the next slave connections, points to
- itself if lone connection.
- */
- struct st_mysql* master, *next_slave;
-
- struct st_mysql* last_used_slave; /* needed for round-robin slave pick */
- /* needed for send/read/store/use result to work correctly with replication */
- struct st_mysql* last_used_con;
-
- LIST *stmts; /* list of all statements */
- const struct st_mysql_methods *methods;
- void *thd;
- /*
- Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
- from mysql_stmt_close if close had to cancel result set of this object.
- */
- my_bool *unbuffered_fetch_owner;
- /* needed for embedded server - no net buffer to store the 'info' */
- char *info_buffer;
- void *extension;
-} MYSQL;
-
-
-typedef struct st_mysql_res {
- my_ulonglong row_count;
- MYSQL_FIELD *fields;
- MYSQL_DATA *data;
- MYSQL_ROWS *data_cursor;
- unsigned long *lengths; /* column lengths of current row */
- MYSQL *handle; /* for unbuffered reads */
- const struct st_mysql_methods *methods;
- MYSQL_ROW row; /* If unbuffered read */
- MYSQL_ROW current_row; /* buffer to current row */
- MEM_ROOT field_alloc;
- unsigned int field_count, current_field;
- my_bool eof; /* Used by mysql_fetch_row */
- /* mysql_stmt_close() had to cancel this result */
- my_bool unbuffered_fetch_cancelled;
- void *extension;
-} MYSQL_RES;
-
-#define MAX_MYSQL_MANAGER_ERR 256
-#define MAX_MYSQL_MANAGER_MSG 256
-
-#define MANAGER_OK 200
-#define MANAGER_INFO 250
-#define MANAGER_ACCESS 401
-#define MANAGER_CLIENT_ERR 450
-#define MANAGER_INTERNAL_ERR 500
-
-#if !defined(MYSQL_SERVER) && !defined(MYSQL_CLIENT)
-#define MYSQL_CLIENT
-#endif
-
-
-typedef struct st_mysql_manager
-{
- NET net;
- char *host, *user, *passwd;
- char *net_buf, *net_buf_pos, *net_data_end;
- unsigned int port;
- int cmd_status;
- int last_errno;
- int net_buf_size;
- my_bool free_me;
- my_bool eof;
- char last_error[MAX_MYSQL_MANAGER_ERR];
- void *extension;
-} MYSQL_MANAGER;
-
-typedef struct st_mysql_parameters
-{
- unsigned long *p_max_allowed_packet;
- unsigned long *p_net_buffer_length;
- void *extension;
-} MYSQL_PARAMETERS;
-
-#if !defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY)
-#define max_allowed_packet (*mysql_get_parameters()->p_max_allowed_packet)
-#define net_buffer_length (*mysql_get_parameters()->p_net_buffer_length)
-#endif
-
-/*
- Set up and bring down the server; to ensure that applications will
- work when linked against either the standard client library or the
- embedded server library, these functions should be called.
-*/
-int STDCALL mysql_server_init(int argc, char **argv, char **groups);
-void STDCALL mysql_server_end(void);
-
-/*
- mysql_server_init/end need to be called when using libmysqld or
- libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so
- you don't need to call it explicitely; but you need to call
- mysql_server_end() to free memory). The names are a bit misleading
- (mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general
- names which suit well whether you're using libmysqld or libmysqlclient. We
- intend to promote these aliases over the mysql_server* ones.
-*/
-#define mysql_library_init mysql_server_init
-#define mysql_library_end mysql_server_end
-
-MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void);
-
-/*
- Set up and bring down a thread; these function should be called
- for each thread in an application which opens at least one MySQL
- connection. All uses of the connection(s) should be between these
- function calls.
-*/
-my_bool STDCALL mysql_thread_init(void);
-void STDCALL mysql_thread_end(void);
-
-/*
- Functions to get information from the MYSQL and MYSQL_RES structures
- Should definitely be used if one uses shared libraries.
-*/
-
-my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res);
-unsigned int STDCALL mysql_num_fields(MYSQL_RES *res);
-my_bool STDCALL mysql_eof(MYSQL_RES *res);
-MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res,
- unsigned int fieldnr);
-MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res);
-MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res);
-MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res);
-
-unsigned int STDCALL mysql_field_count(MYSQL *mysql);
-my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql);
-my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql);
-unsigned int STDCALL mysql_errno(MYSQL *mysql);
-const char * STDCALL mysql_error(MYSQL *mysql);
-const char *STDCALL mysql_sqlstate(MYSQL *mysql);
-unsigned int STDCALL mysql_warning_count(MYSQL *mysql);
-const char * STDCALL mysql_info(MYSQL *mysql);
-unsigned long STDCALL mysql_thread_id(MYSQL *mysql);
-const char * STDCALL mysql_character_set_name(MYSQL *mysql);
-int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname);
-
-MYSQL * STDCALL mysql_init(MYSQL *mysql);
-my_bool STDCALL mysql_ssl_set(MYSQL *mysql, const char *key,
- const char *cert, const char *ca,
- const char *capath, const char *cipher);
-const char * STDCALL mysql_get_ssl_cipher(MYSQL *mysql);
-my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user,
- const char *passwd, const char *db);
-MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host,
- const char *user,
- const char *passwd,
- const char *db,
- unsigned int port,
- const char *unix_socket,
- unsigned long clientflag);
-int STDCALL mysql_select_db(MYSQL *mysql, const char *db);
-int STDCALL mysql_query(MYSQL *mysql, const char *q);
-int STDCALL mysql_send_query(MYSQL *mysql, const char *q,
- unsigned long length);
-int STDCALL mysql_real_query(MYSQL *mysql, const char *q,
- unsigned long length);
-MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql);
-MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql);
-
-/* perform query on master */
-my_bool STDCALL mysql_master_query(MYSQL *mysql, const char *q,
- unsigned long length);
-my_bool STDCALL mysql_master_send_query(MYSQL *mysql, const char *q,
- unsigned long length);
-/* perform query on slave */
-my_bool STDCALL mysql_slave_query(MYSQL *mysql, const char *q,
- unsigned long length);
-my_bool STDCALL mysql_slave_send_query(MYSQL *mysql, const char *q,
- unsigned long length);
-void STDCALL mysql_get_character_set_info(MYSQL *mysql,
- MY_CHARSET_INFO *charset);
-
-/* local infile support */
-
-#define LOCAL_INFILE_ERROR_LEN 512
-
-void
-mysql_set_local_infile_handler(MYSQL *mysql,
- int (*local_infile_init)(void **, const char *,
- void *),
- int (*local_infile_read)(void *, char *,
- unsigned int),
- void (*local_infile_end)(void *),
- int (*local_infile_error)(void *, char*,
- unsigned int),
- void *);
-
-void
-mysql_set_local_infile_default(MYSQL *mysql);
-
-
-/*
- enable/disable parsing of all queries to decide if they go on master or
- slave
-*/
-void STDCALL mysql_enable_rpl_parse(MYSQL* mysql);
-void STDCALL mysql_disable_rpl_parse(MYSQL* mysql);
-/* get the value of the parse flag */
-int STDCALL mysql_rpl_parse_enabled(MYSQL* mysql);
-
-/* enable/disable reads from master */
-void STDCALL mysql_enable_reads_from_master(MYSQL* mysql);
-void STDCALL mysql_disable_reads_from_master(MYSQL* mysql);
-/* get the value of the master read flag */
-my_bool STDCALL mysql_reads_from_master_enabled(MYSQL* mysql);
-
-enum mysql_rpl_type STDCALL mysql_rpl_query_type(const char* q, int len);
-
-/* discover the master and its slaves */
-my_bool STDCALL mysql_rpl_probe(MYSQL* mysql);
-
-/* set the master, close/free the old one, if it is not a pivot */
-int STDCALL mysql_set_master(MYSQL* mysql, const char* host,
- unsigned int port,
- const char* user,
- const char* passwd);
-int STDCALL mysql_add_slave(MYSQL* mysql, const char* host,
- unsigned int port,
- const char* user,
- const char* passwd);
-
-int STDCALL mysql_shutdown(MYSQL *mysql,
- enum mysql_enum_shutdown_level
- shutdown_level);
-int STDCALL mysql_dump_debug_info(MYSQL *mysql);
-int STDCALL mysql_refresh(MYSQL *mysql,
- unsigned int refresh_options);
-int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid);
-int STDCALL mysql_set_server_option(MYSQL *mysql,
- enum enum_mysql_set_option
- option);
-int STDCALL mysql_ping(MYSQL *mysql);
-const char * STDCALL mysql_stat(MYSQL *mysql);
-const char * STDCALL mysql_get_server_info(MYSQL *mysql);
-const char * STDCALL mysql_get_client_info(void);
-unsigned long STDCALL mysql_get_client_version(void);
-const char * STDCALL mysql_get_host_info(MYSQL *mysql);
-unsigned long STDCALL mysql_get_server_version(MYSQL *mysql);
-unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql);
-MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild);
-MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild);
-MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql);
-int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option,
- const void *arg);
-void STDCALL mysql_free_result(MYSQL_RES *result);
-void STDCALL mysql_data_seek(MYSQL_RES *result,
- my_ulonglong offset);
-MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result,
- MYSQL_ROW_OFFSET offset);
-MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result,
- MYSQL_FIELD_OFFSET offset);
-MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
-unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result);
-MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result);
-MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table,
- const char *wild);
-unsigned long STDCALL mysql_escape_string(char *to,const char *from,
- unsigned long from_length);
-unsigned long STDCALL mysql_hex_string(char *to,const char *from,
- unsigned long from_length);
-unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql,
- char *to,const char *from,
- unsigned long length);
-void STDCALL mysql_debug(const char *debug);
-void STDCALL myodbc_remove_escape(MYSQL *mysql,char *name);
-unsigned int STDCALL mysql_thread_safe(void);
-my_bool STDCALL mysql_embedded(void);
-MYSQL_MANAGER* STDCALL mysql_manager_init(MYSQL_MANAGER* con);
-MYSQL_MANAGER* STDCALL mysql_manager_connect(MYSQL_MANAGER* con,
- const char* host,
- const char* user,
- const char* passwd,
- unsigned int port);
-void STDCALL mysql_manager_close(MYSQL_MANAGER* con);
-int STDCALL mysql_manager_command(MYSQL_MANAGER* con,
- const char* cmd, int cmd_len);
-int STDCALL mysql_manager_fetch_line(MYSQL_MANAGER* con,
- char* res_buf,
- int res_buf_size);
-my_bool STDCALL mysql_read_query_result(MYSQL *mysql);
-
-
-/*
- The following definitions are added for the enhanced
- client-server protocol
-*/
-
-/* statement state */
-enum enum_mysql_stmt_state
-{
- MYSQL_STMT_INIT_DONE= 1, MYSQL_STMT_PREPARE_DONE, MYSQL_STMT_EXECUTE_DONE,
- MYSQL_STMT_FETCH_DONE
-};
-
-
-/*
- This structure is used to define bind information, and
- internally by the client library.
- Public members with their descriptions are listed below
- (conventionally `On input' refers to the binds given to
- mysql_stmt_bind_param, `On output' refers to the binds given
- to mysql_stmt_bind_result):
-
- buffer_type - One of the MYSQL_* types, used to describe
- the host language type of buffer.
- On output: if column type is different from
- buffer_type, column value is automatically converted
- to buffer_type before it is stored in the buffer.
- buffer - On input: points to the buffer with input data.
- On output: points to the buffer capable to store
- output data.
- The type of memory pointed by buffer must correspond
- to buffer_type. See the correspondence table in
- the comment to mysql_stmt_bind_param.
-
- The two above members are mandatory for any kind of bind.
-
- buffer_length - the length of the buffer. You don't have to set
- it for any fixed length buffer: float, double,
- int, etc. It must be set however for variable-length
- types, such as BLOBs or STRINGs.
-
- length - On input: in case when lengths of input values
- are different for each execute, you can set this to
- point at a variable containining value length. This
- way the value length can be different in each execute.
- If length is not NULL, buffer_length is not used.
- Note, length can even point at buffer_length if
- you keep bind structures around while fetching:
- this way you can change buffer_length before
- each execution, everything will work ok.
- On output: if length is set, mysql_stmt_fetch will
- write column length into it.
-
- is_null - On input: points to a boolean variable that should
- be set to TRUE for NULL values.
- This member is useful only if your data may be
- NULL in some but not all cases.
- If your data is never NULL, is_null should be set to 0.
- If your data is always NULL, set buffer_type
- to MYSQL_TYPE_NULL, and is_null will not be used.
-
- is_unsigned - On input: used to signify that values provided for one
- of numeric types are unsigned.
- On output describes signedness of the output buffer.
- If, taking into account is_unsigned flag, column data
- is out of range of the output buffer, data for this column
- is regarded truncated. Note that this has no correspondence
- to the sign of result set column, if you need to find it out
- use mysql_stmt_result_metadata.
- error - where to write a truncation error if it is present.
- possible error value is:
- 0 no truncation
- 1 value is out of range or buffer is too small
-
- Please note that MYSQL_BIND also has internals members.
-*/
-
-typedef struct st_mysql_bind
-{
- unsigned long *length; /* output length pointer */
- my_bool *is_null; /* Pointer to null indicator */
- void *buffer; /* buffer to get/put data */
- /* set this if you want to track data truncations happened during fetch */
- my_bool *error;
- unsigned char *row_ptr; /* for the current data position */
- void (*store_param_func)(NET *net, struct st_mysql_bind *param);
- void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *,
- unsigned char **row);
- void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *,
- unsigned char **row);
- /* output buffer length, must be set when fetching str/binary */
- unsigned long buffer_length;
- unsigned long offset; /* offset position for char/binary fetch */
- unsigned long length_value; /* Used if length is 0 */
- unsigned int param_number; /* For null count and error messages */
- unsigned int pack_length; /* Internal length for packed data */
- enum enum_field_types buffer_type; /* buffer type */
- my_bool error_value; /* used if error is 0 */
- my_bool is_unsigned; /* set if integer type is unsigned */
- my_bool long_data_used; /* If used with mysql_send_long_data */
- my_bool is_null_value; /* Used if is_null is 0 */
- void *extension;
-} MYSQL_BIND;
-
-
-/* statement handler */
-typedef struct st_mysql_stmt
-{
- MEM_ROOT mem_root; /* root allocations */
- LIST list; /* list to keep track of all stmts */
- MYSQL *mysql; /* connection handle */
- MYSQL_BIND *params; /* input parameters */
- MYSQL_BIND *bind; /* output parameters */
- MYSQL_FIELD *fields; /* result set metadata */
- MYSQL_DATA result; /* cached result set */
- MYSQL_ROWS *data_cursor; /* current row in cached result */
- /*
- mysql_stmt_fetch() calls this function to fetch one row (it's different
- for buffered, unbuffered and cursor fetch).
- */
- int (*read_row_func)(struct st_mysql_stmt *stmt,
- unsigned char **row);
- /* copy of mysql->affected_rows after statement execution */
- my_ulonglong affected_rows;
- my_ulonglong insert_id; /* copy of mysql->insert_id */
- unsigned long stmt_id; /* Id for prepared statement */
- unsigned long flags; /* i.e. type of cursor to open */
- unsigned long prefetch_rows; /* number of rows per one COM_FETCH */
- /*
- Copied from mysql->server_status after execute/fetch to know
- server-side cursor status for this statement.
- */
- unsigned int server_status;
- unsigned int last_errno; /* error code */
- unsigned int param_count; /* input parameter count */
- unsigned int field_count; /* number of columns in result set */
- enum enum_mysql_stmt_state state; /* statement state */
- char last_error[MYSQL_ERRMSG_SIZE]; /* error message */
- char sqlstate[SQLSTATE_LENGTH+1];
- /* Types of input parameters should be sent to server */
- my_bool send_types_to_server;
- my_bool bind_param_done; /* input buffers were supplied */
- unsigned char bind_result_done; /* output buffers were supplied */
- /* mysql_stmt_close() had to cancel this result */
- my_bool unbuffered_fetch_cancelled;
- /*
- Is set to true if we need to calculate field->max_length for
- metadata fields when doing mysql_stmt_store_result.
- */
- my_bool update_max_length;
- void *extension;
-} MYSQL_STMT;
-
-enum enum_stmt_attr_type
-{
- /*
- When doing mysql_stmt_store_result calculate max_length attribute
- of statement metadata. This is to be consistent with the old API,
- where this was done automatically.
- In the new API we do that only by request because it slows down
- mysql_stmt_store_result sufficiently.
- */
- STMT_ATTR_UPDATE_MAX_LENGTH,
- /*
- unsigned long with combination of cursor flags (read only, for update,
- etc)
- */
- STMT_ATTR_CURSOR_TYPE,
- /*
- Amount of rows to retrieve from server per one fetch if using cursors.
- Accepts unsigned long attribute in the range 1 - ulong_max
- */
- STMT_ATTR_PREFETCH_ROWS
-};
-
-
-typedef struct st_mysql_methods
-{
- my_bool (*read_query_result)(MYSQL *mysql);
- my_bool (*advanced_command)(MYSQL *mysql,
- enum enum_server_command command,
- const unsigned char *header,
- unsigned long header_length,
- const unsigned char *arg,
- unsigned long arg_length,
- my_bool skip_check,
- MYSQL_STMT *stmt);
- MYSQL_DATA *(*read_rows)(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
- unsigned int fields);
- MYSQL_RES * (*use_result)(MYSQL *mysql);
- void (*fetch_lengths)(unsigned long *to,
- MYSQL_ROW column, unsigned int field_count);
- void (*flush_use_result)(MYSQL *mysql);
-#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY)
- MYSQL_FIELD * (*list_fields)(MYSQL *mysql);
- my_bool (*read_prepare_result)(MYSQL *mysql, MYSQL_STMT *stmt);
- int (*stmt_execute)(MYSQL_STMT *stmt);
- int (*read_binary_rows)(MYSQL_STMT *stmt);
- int (*unbuffered_fetch)(MYSQL *mysql, char **row);
- void (*free_embedded_thd)(MYSQL *mysql);
- const char *(*read_statistics)(MYSQL *mysql);
- my_bool (*next_result)(MYSQL *mysql);
- int (*read_change_user_result)(MYSQL *mysql, char *buff, const char *passwd);
- int (*read_rows_from_cursor)(MYSQL_STMT *stmt);
-#endif
-} MYSQL_METHODS;
-
-
-MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql);
-int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query,
- unsigned long length);
-int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt);
-int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt);
-int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg,
- unsigned int column,
- unsigned long offset);
-int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt);
-unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt);
-my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt,
- enum enum_stmt_attr_type attr_type,
- const void *attr);
-my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt,
- enum enum_stmt_attr_type attr_type,
- void *attr);
-my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
-my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
-my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt);
-my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt);
-my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt);
-my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt,
- unsigned int param_number,
- const char *data,
- unsigned long length);
-MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt);
-MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt);
-unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt);
-const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt);
-const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt);
-MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt,
- MYSQL_ROW_OFFSET offset);
-MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt);
-void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset);
-my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt);
-my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt);
-my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt);
-unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt);
-
-my_bool STDCALL mysql_commit(MYSQL * mysql);
-my_bool STDCALL mysql_rollback(MYSQL * mysql);
-my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode);
-my_bool STDCALL mysql_more_results(MYSQL *mysql);
-int STDCALL mysql_next_result(MYSQL *mysql);
-void STDCALL mysql_close(MYSQL *sock);
-
-
-/* status return codes */
-#define MYSQL_NO_DATA 100
-#define MYSQL_DATA_TRUNCATED 101
-
-#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
-
-#ifdef USE_OLD_FUNCTIONS
-MYSQL * STDCALL mysql_connect(MYSQL *mysql, const char *host,
- const char *user, const char *passwd);
-int STDCALL mysql_create_db(MYSQL *mysql, const char *DB);
-int STDCALL mysql_drop_db(MYSQL *mysql, const char *DB);
-#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
-#endif
-#define HAVE_MYSQL_REAL_CONNECT
-
-/*
- The following functions are mainly exported because of mysqlbinlog;
- They are not for general usage
-*/
-
-#define simple_command(mysql, command, arg, length, skip_check) \
- (*(mysql)->methods->advanced_command)(mysql, command, 0, \
- 0, arg, length, skip_check, NULL)
-#define stmt_command(mysql, command, arg, length, stmt) \
- (*(mysql)->methods->advanced_command)(mysql, command, 0, \
- 0, arg, length, 1, stmt)
-
-#ifdef __NETWARE__
-#pragma pack(pop) /* restore alignment */
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _mysql_h */
diff --git a/Frameworks/MCPKit/MySQL/include/mysql_com.h b/Frameworks/MCPKit/MySQL/include/mysql_com.h
deleted file mode 100644
index 357519d5..00000000
--- a/Frameworks/MCPKit/MySQL/include/mysql_com.h
+++ /dev/null
@@ -1,532 +0,0 @@
-/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. 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; version 2 of the License.
-
- 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 */
-
-/*
-** Common definition between mysql server & client
-*/
-
-#ifndef _mysql_com_h
-#define _mysql_com_h
-
-#define HOSTNAME_LENGTH 60
-#define SYSTEM_CHARSET_MBMAXLEN 3
-#define NAME_CHAR_LEN 64 /* Field/table name length */
-#define USERNAME_CHAR_LENGTH 16
-#define NAME_LEN (NAME_CHAR_LEN*SYSTEM_CHARSET_MBMAXLEN)
-#define USERNAME_LENGTH (USERNAME_CHAR_LENGTH*SYSTEM_CHARSET_MBMAXLEN)
-
-#define SERVER_VERSION_LENGTH 60
-#define SQLSTATE_LENGTH 5
-
-/*
- USER_HOST_BUFF_SIZE -- length of string buffer, that is enough to contain
- username and hostname parts of the user identifier with trailing zero in
- MySQL standard format:
- user_name_part@host_name_part\0
-*/
-#define USER_HOST_BUFF_SIZE HOSTNAME_LENGTH + USERNAME_LENGTH + 2
-
-#define LOCAL_HOST "localhost"
-#define LOCAL_HOST_NAMEDPIPE "."
-
-
-#if defined(__WIN__) && !defined( _CUSTOMCONFIG_)
-#define MYSQL_NAMEDPIPE "MySQL"
-#define MYSQL_SERVICENAME "MySQL"
-#endif /* __WIN__ */
-
-/*
- You should add new commands to the end of this list, otherwise old
- servers won't be able to handle them as 'unsupported'.
-*/
-
-enum enum_server_command
-{
- COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST,
- COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS,
- COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING,
- COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP,
- COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE,
- COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE,
- COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_DAEMON,
- /* don't forget to update const char *command_name[] in sql_parse.cc */
-
- /* Must be last */
- COM_END
-};
-
-
-/*
- Length of random string sent by server on handshake; this is also length of
- obfuscated password, recieved from client
-*/
-#define SCRAMBLE_LENGTH 20
-#define SCRAMBLE_LENGTH_323 8
-/* length of password stored in the db: new passwords are preceeded with '*' */
-#define SCRAMBLED_PASSWORD_CHAR_LENGTH (SCRAMBLE_LENGTH*2+1)
-#define SCRAMBLED_PASSWORD_CHAR_LENGTH_323 (SCRAMBLE_LENGTH_323*2)
-
-
-#define NOT_NULL_FLAG 1 /* Field can't be NULL */
-#define PRI_KEY_FLAG 2 /* Field is part of a primary key */
-#define UNIQUE_KEY_FLAG 4 /* Field is part of a unique key */
-#define MULTIPLE_KEY_FLAG 8 /* Field is part of a key */
-#define BLOB_FLAG 16 /* Field is a blob */
-#define UNSIGNED_FLAG 32 /* Field is unsigned */
-#define ZEROFILL_FLAG 64 /* Field is zerofill */
-#define BINARY_FLAG 128 /* Field is binary */
-
-/* The following are only sent to new clients */
-#define ENUM_FLAG 256 /* field is an enum */
-#define AUTO_INCREMENT_FLAG 512 /* field is a autoincrement field */
-#define TIMESTAMP_FLAG 1024 /* Field is a timestamp */
-#define SET_FLAG 2048 /* field is a set */
-#define NO_DEFAULT_VALUE_FLAG 4096 /* Field doesn't have default value */
-#define ON_UPDATE_NOW_FLAG 8192 /* Field is set to NOW on UPDATE */
-#define NUM_FLAG 32768 /* Field is num (for clients) */
-#define PART_KEY_FLAG 16384 /* Intern; Part of some key */
-#define GROUP_FLAG 32768 /* Intern: Group field */
-#define UNIQUE_FLAG 65536 /* Intern: Used by sql_yacc */
-#define BINCMP_FLAG 131072 /* Intern: Used by sql_yacc */
-#define GET_FIXED_FIELDS_FLAG (1 << 18) /* Used to get fields in item tree */
-#define FIELD_IN_PART_FUNC_FLAG (1 << 19)/* Field part of partition func */
-#define FIELD_IN_ADD_INDEX (1<< 20) /* Intern: Field used in ADD INDEX */
-#define FIELD_IS_RENAMED (1<< 21) /* Intern: Field is being renamed */
-
-#define REFRESH_GRANT 1 /* Refresh grant tables */
-#define REFRESH_LOG 2 /* Start on new log file */
-#define REFRESH_TABLES 4 /* close all tables */
-#define REFRESH_HOSTS 8 /* Flush host cache */
-#define REFRESH_STATUS 16 /* Flush status variables */
-#define REFRESH_THREADS 32 /* Flush thread cache */
-#define REFRESH_SLAVE 64 /* Reset master info and restart slave
- thread */
-#define REFRESH_MASTER 128 /* Remove all bin logs in the index
- and truncate the index */
-
-/* The following can't be set with mysql_refresh() */
-#define REFRESH_READ_LOCK 16384 /* Lock tables for read */
-#define REFRESH_FAST 32768 /* Intern flag */
-
-/* RESET (remove all queries) from query cache */
-#define REFRESH_QUERY_CACHE 65536
-#define REFRESH_QUERY_CACHE_FREE 0x20000L /* pack query cache */
-#define REFRESH_DES_KEY_FILE 0x40000L
-#define REFRESH_USER_RESOURCES 0x80000L
-
-#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */
-#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */
-#define CLIENT_LONG_FLAG 4 /* Get all column flags */
-#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */
-#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
-#define CLIENT_COMPRESS 32 /* Can use compression protocol */
-#define CLIENT_ODBC 64 /* Odbc client */
-#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */
-#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */
-#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */
-#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */
-#define CLIENT_SSL 2048 /* Switch to SSL after handshake */
-#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */
-#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */
-#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */
-#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */
-#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */
-#define CLIENT_MULTI_RESULTS (1UL << 17) /* Enable/disable multi-results */
-
-#define CLIENT_SSL_VERIFY_SERVER_CERT (1UL << 30)
-#define CLIENT_REMEMBER_OPTIONS (1UL << 31)
-
-/* Gather all possible capabilites (flags) supported by the server */
-#define CLIENT_ALL_FLAGS (CLIENT_LONG_PASSWORD | \
- CLIENT_FOUND_ROWS | \
- CLIENT_LONG_FLAG | \
- CLIENT_CONNECT_WITH_DB | \
- CLIENT_NO_SCHEMA | \
- CLIENT_COMPRESS | \
- CLIENT_ODBC | \
- CLIENT_LOCAL_FILES | \
- CLIENT_IGNORE_SPACE | \
- CLIENT_PROTOCOL_41 | \
- CLIENT_INTERACTIVE | \
- CLIENT_SSL | \
- CLIENT_IGNORE_SIGPIPE | \
- CLIENT_TRANSACTIONS | \
- CLIENT_RESERVED | \
- CLIENT_SECURE_CONNECTION | \
- CLIENT_MULTI_STATEMENTS | \
- CLIENT_MULTI_RESULTS | \
- CLIENT_SSL_VERIFY_SERVER_CERT | \
- CLIENT_REMEMBER_OPTIONS)
-
-/*
- Switch off the flags that are optional and depending on build flags
- If any of the optional flags is supported by the build it will be switched
- on before sending to the client during the connection handshake.
-*/
-#define CLIENT_BASIC_FLAGS (((CLIENT_ALL_FLAGS & ~CLIENT_SSL) \
- & ~CLIENT_COMPRESS) \
- & ~CLIENT_SSL_VERIFY_SERVER_CERT)
-
-#define SERVER_STATUS_IN_TRANS 1 /* Transaction has started */
-#define SERVER_STATUS_AUTOCOMMIT 2 /* Server in auto_commit mode */
-#define SERVER_MORE_RESULTS_EXISTS 8 /* Multi query - next query exists */
-#define SERVER_QUERY_NO_GOOD_INDEX_USED 16
-#define SERVER_QUERY_NO_INDEX_USED 32
-/**
- The server was able to fulfill the clients request and opened a
- read-only non-scrollable cursor for a query. This flag comes
- in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands.
-*/
-#define SERVER_STATUS_CURSOR_EXISTS 64
-/**
- This flag is sent when a read-only cursor is exhausted, in reply to
- COM_STMT_FETCH command.
-*/
-#define SERVER_STATUS_LAST_ROW_SENT 128
-#define SERVER_STATUS_DB_DROPPED 256 /* A database was dropped */
-#define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512
-/**
- Sent to the client if after a prepared statement reprepare
- we discovered that the new statement returns a different
- number of result set columns.
-*/
-#define SERVER_STATUS_METADATA_CHANGED 1024
-
-/**
- Server status flags that must be cleared when starting
- execution of a new SQL statement.
- Flags from this set are only added to the
- current server status by the execution engine, but
- never removed -- the execution engine expects them
- to disappear automagically by the next command.
-*/
-#define SERVER_STATUS_CLEAR_SET (SERVER_QUERY_NO_GOOD_INDEX_USED| \
- SERVER_QUERY_NO_INDEX_USED|\
- SERVER_MORE_RESULTS_EXISTS|\
- SERVER_STATUS_METADATA_CHANGED)
-
-#define MYSQL_ERRMSG_SIZE 512
-#define NET_READ_TIMEOUT 30 /* Timeout on read */
-#define NET_WRITE_TIMEOUT 60 /* Timeout on write */
-#define NET_WAIT_TIMEOUT 8*60*60 /* Wait for new query */
-
-#define ONLY_KILL_QUERY 1
-
-
-struct st_vio; /* Only C */
-typedef struct st_vio Vio;
-
-#define MAX_TINYINT_WIDTH 3 /* Max width for a TINY w.o. sign */
-#define MAX_SMALLINT_WIDTH 5 /* Max width for a SHORT w.o. sign */
-#define MAX_MEDIUMINT_WIDTH 8 /* Max width for a INT24 w.o. sign */
-#define MAX_INT_WIDTH 10 /* Max width for a LONG w.o. sign */
-#define MAX_BIGINT_WIDTH 20 /* Max width for a LONGLONG */
-#define MAX_CHAR_WIDTH 255 /* Max length for a CHAR colum */
-#define MAX_BLOB_WIDTH 16777216 /* Default width for blob */
-
-typedef struct st_net {
-#if !defined(CHECK_EMBEDDED_DIFFERENCES) || !defined(EMBEDDED_LIBRARY)
- Vio *vio;
- unsigned char *buff,*buff_end,*write_pos,*read_pos;
- my_socket fd; /* For Perl DBI/dbd */
- /*
- The following variable is set if we are doing several queries in one
- command ( as in LOAD TABLE ... FROM MASTER ),
- and do not want to confuse the client with OK at the wrong time
- */
- unsigned long remain_in_buf,length, buf_length, where_b;
- unsigned long max_packet,max_packet_size;
- unsigned int pkt_nr,compress_pkt_nr;
- unsigned int write_timeout, read_timeout, retry_count;
- int fcntl;
- unsigned int *return_status;
- unsigned char reading_or_writing;
- char save_char;
- my_bool unused0; /* Please remove with the next incompatible ABI change. */
- my_bool unused; /* Please remove with the next incompatible ABI change */
- my_bool compress;
- my_bool unused1; /* Please remove with the next incompatible ABI change. */
- /*
- Pointer to query object in query cache, do not equal NULL (0) for
- queries in cache that have not stored its results yet
- */
-#endif
- /*
- 'query_cache_query' should be accessed only via query cache
- functions and methods to maintain proper locking.
- */
- unsigned char *query_cache_query;
- unsigned int last_errno;
- unsigned char error;
- my_bool unused2; /* Please remove with the next incompatible ABI change. */
- my_bool return_errno;
- /** Client library error message buffer. Actually belongs to struct MYSQL. */
- char last_error[MYSQL_ERRMSG_SIZE];
- /** Client library sqlstate buffer. Set along with the error message. */
- char sqlstate[SQLSTATE_LENGTH+1];
- void *extension;
-#if defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY)
- /*
- Controls whether a big packet should be skipped.
-
- Initially set to FALSE by default. Unauthenticated sessions must have
- this set to FALSE so that the server can't be tricked to read packets
- indefinitely.
- */
- my_bool skip_big_packet;
-#endif
-} NET;
-
-
-#define packet_error (~(unsigned long) 0)
-
-enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY,
- MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
- MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
- MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP,
- MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24,
- MYSQL_TYPE_DATE, MYSQL_TYPE_TIME,
- MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR,
- MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
- MYSQL_TYPE_BIT,
- MYSQL_TYPE_NEWDECIMAL=246,
- MYSQL_TYPE_ENUM=247,
- MYSQL_TYPE_SET=248,
- MYSQL_TYPE_TINY_BLOB=249,
- MYSQL_TYPE_MEDIUM_BLOB=250,
- MYSQL_TYPE_LONG_BLOB=251,
- MYSQL_TYPE_BLOB=252,
- MYSQL_TYPE_VAR_STRING=253,
- MYSQL_TYPE_STRING=254,
- MYSQL_TYPE_GEOMETRY=255
-
-};
-
-/* For backward compatibility */
-#define CLIENT_MULTI_QUERIES CLIENT_MULTI_STATEMENTS
-#define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL
-#define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL
-#define FIELD_TYPE_TINY MYSQL_TYPE_TINY
-#define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT
-#define FIELD_TYPE_LONG MYSQL_TYPE_LONG
-#define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT
-#define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE
-#define FIELD_TYPE_NULL MYSQL_TYPE_NULL
-#define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP
-#define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG
-#define FIELD_TYPE_INT24 MYSQL_TYPE_INT24
-#define FIELD_TYPE_DATE MYSQL_TYPE_DATE
-#define FIELD_TYPE_TIME MYSQL_TYPE_TIME
-#define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME
-#define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR
-#define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE
-#define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM
-#define FIELD_TYPE_SET MYSQL_TYPE_SET
-#define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB
-#define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB
-#define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB
-#define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB
-#define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING
-#define FIELD_TYPE_STRING MYSQL_TYPE_STRING
-#define FIELD_TYPE_CHAR MYSQL_TYPE_TINY
-#define FIELD_TYPE_INTERVAL MYSQL_TYPE_ENUM
-#define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY
-#define FIELD_TYPE_BIT MYSQL_TYPE_BIT
-
-
-/* Shutdown/kill enums and constants */
-
-/* Bits for THD::killable. */
-#define MYSQL_SHUTDOWN_KILLABLE_CONNECT (unsigned char)(1 << 0)
-#define MYSQL_SHUTDOWN_KILLABLE_TRANS (unsigned char)(1 << 1)
-#define MYSQL_SHUTDOWN_KILLABLE_LOCK_TABLE (unsigned char)(1 << 2)
-#define MYSQL_SHUTDOWN_KILLABLE_UPDATE (unsigned char)(1 << 3)
-
-enum mysql_enum_shutdown_level {
- /*
- We want levels to be in growing order of hardness (because we use number
- comparisons). Note that DEFAULT does not respect the growing property, but
- it's ok.
- */
- SHUTDOWN_DEFAULT = 0,
- /* wait for existing connections to finish */
- SHUTDOWN_WAIT_CONNECTIONS= MYSQL_SHUTDOWN_KILLABLE_CONNECT,
- /* wait for existing trans to finish */
- SHUTDOWN_WAIT_TRANSACTIONS= MYSQL_SHUTDOWN_KILLABLE_TRANS,
- /* wait for existing updates to finish (=> no partial MyISAM update) */
- SHUTDOWN_WAIT_UPDATES= MYSQL_SHUTDOWN_KILLABLE_UPDATE,
- /* flush InnoDB buffers and other storage engines' buffers*/
- SHUTDOWN_WAIT_ALL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1),
- /* don't flush InnoDB buffers, flush other storage engines' buffers*/
- SHUTDOWN_WAIT_CRITICAL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1) + 1,
- /* Now the 2 levels of the KILL command */
-#if MYSQL_VERSION_ID >= 50000
- KILL_QUERY= 254,
-#endif
- KILL_CONNECTION= 255
-};
-
-
-enum enum_cursor_type
-{
- CURSOR_TYPE_NO_CURSOR= 0,
- CURSOR_TYPE_READ_ONLY= 1,
- CURSOR_TYPE_FOR_UPDATE= 2,
- CURSOR_TYPE_SCROLLABLE= 4
-};
-
-
-/* options for mysql_set_option */
-enum enum_mysql_set_option
-{
- MYSQL_OPTION_MULTI_STATEMENTS_ON,
- MYSQL_OPTION_MULTI_STATEMENTS_OFF
-};
-
-#define net_new_transaction(net) ((net)->pkt_nr=0)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-my_bool my_net_init(NET *net, Vio* vio);
-void my_net_local_init(NET *net);
-void net_end(NET *net);
- void net_clear(NET *net, my_bool clear_buffer);
-my_bool net_realloc(NET *net, size_t length);
-my_bool net_flush(NET *net);
-my_bool my_net_write(NET *net,const unsigned char *packet, size_t len);
-my_bool net_write_command(NET *net,unsigned char command,
- const unsigned char *header, size_t head_len,
- const unsigned char *packet, size_t len);
-int net_real_write(NET *net,const unsigned char *packet, size_t len);
-unsigned long my_net_read(NET *net);
-
-#ifdef _global_h
-void my_net_set_write_timeout(NET *net, uint timeout);
-void my_net_set_read_timeout(NET *net, uint timeout);
-#endif
-
-/*
- The following function is not meant for normal usage
- Currently it's used internally by manager.c
-*/
-struct sockaddr;
-int my_connect(my_socket s, const struct sockaddr *name, unsigned int namelen,
- unsigned int timeout);
-
-struct rand_struct {
- unsigned long seed1,seed2,max_value;
- double max_value_dbl;
-};
-
-#ifdef __cplusplus
-}
-#endif
-
- /* The following is for user defined functions */
-
-enum Item_result {STRING_RESULT=0, REAL_RESULT, INT_RESULT, ROW_RESULT,
- DECIMAL_RESULT};
-
-typedef struct st_udf_args
-{
- unsigned int arg_count; /* Number of arguments */
- enum Item_result *arg_type; /* Pointer to item_results */
- char **args; /* Pointer to argument */
- unsigned long *lengths; /* Length of string arguments */
- char *maybe_null; /* Set to 1 for all maybe_null args */
- char **attributes; /* Pointer to attribute name */
- unsigned long *attribute_lengths; /* Length of attribute arguments */
- void *extension;
-} UDF_ARGS;
-
- /* This holds information about the result */
-
-typedef struct st_udf_init
-{
- my_bool maybe_null; /* 1 if function can return NULL */
- unsigned int decimals; /* for real functions */
- unsigned long max_length; /* For string functions */
- char *ptr; /* free pointer for function data */
- my_bool const_item; /* 1 if function always returns the same value */
- void *extension;
-} UDF_INIT;
-/*
- TODO: add a notion for determinism of the UDF.
- See Item_udf_func::update_used_tables ()
-*/
-
- /* Constants when using compression */
-#define NET_HEADER_SIZE 4 /* standard header size */
-#define COMP_HEADER_SIZE 3 /* compression header extra size */
-
- /* Prototypes to password functions */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- These functions are used for authentication by client and server and
- implemented in sql/password.c
-*/
-
-void randominit(struct rand_struct *, unsigned long seed1,
- unsigned long seed2);
-double my_rnd(struct rand_struct *);
-void create_random_string(char *to, unsigned int length, struct rand_struct *rand_st);
-
-void hash_password(unsigned long *to, const char *password, unsigned int password_len);
-void make_scrambled_password_323(char *to, const char *password);
-void scramble_323(char *to, const char *message, const char *password);
-my_bool check_scramble_323(const char *, const char *message,
- unsigned long *salt);
-void get_salt_from_password_323(unsigned long *res, const char *password);
-void make_password_from_salt_323(char *to, const unsigned long *salt);
-
-void make_scrambled_password(char *to, const char *password);
-void scramble(char *to, const char *message, const char *password);
-my_bool check_scramble(const char *reply, const char *message,
- const unsigned char *hash_stage2);
-void get_salt_from_password(unsigned char *res, const char *password);
-void make_password_from_salt(char *to, const unsigned char *hash_stage2);
-char *octet2hex(char *to, const char *str, unsigned int len);
-
-/* end of password.c */
-
-char *get_tty_password(const char *opt_message);
-const char *mysql_errno_to_sqlstate(unsigned int mysql_errno);
-
-/* Some other useful functions */
-
-my_bool my_thread_init(void);
-void my_thread_end(void);
-
-#ifdef _global_h
-ulong STDCALL net_field_length(uchar **packet);
-my_ulonglong net_field_length_ll(uchar **packet);
-uchar *net_store_length(uchar *pkg, ulonglong length);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */
-#define MYSQL_STMT_HEADER 4
-#define MYSQL_LONG_DATA_HEADER 6
-
-#endif
diff --git a/Frameworks/MCPKit/MySQL/include/mysql_embed.h b/Frameworks/MCPKit/MySQL/include/mysql_embed.h
deleted file mode 100644
index a7d6e610..00000000
--- a/Frameworks/MCPKit/MySQL/include/mysql_embed.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Copyright (C) 2000 MySQL AB
-
- 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; version 2 of the License.
-
- 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 */
-
-/* Defines that are unique to the embedded version of MySQL */
-
-#ifdef EMBEDDED_LIBRARY
-
-/* Things we don't need in the embedded version of MySQL */
-/* TODO HF add #undef HAVE_VIO if we don't want client in embedded library */
-
-#undef HAVE_OPENSSL
-#undef HAVE_SMEM /* No shared memory */
-#undef HAVE_NDBCLUSTER_DB /* No NDB cluster */
-
-#define DONT_USE_RAID
-
-#endif /* EMBEDDED_LIBRARY */
diff --git a/Frameworks/MCPKit/MySQL/include/mysql_time.h b/Frameworks/MCPKit/MySQL/include/mysql_time.h
deleted file mode 100644
index 0a3f17a8..00000000
--- a/Frameworks/MCPKit/MySQL/include/mysql_time.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Copyright (C) 2004 MySQL AB
-
- 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; version 2 of the License.
-
- 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 */
-
-#ifndef _mysql_time_h_
-#define _mysql_time_h_
-
-/*
- Time declarations shared between the server and client API:
- you should not add anything to this header unless it's used
- (and hence should be visible) in mysql.h.
- If you're looking for a place to add new time-related declaration,
- it's most likely my_time.h. See also "C API Handling of Date
- and Time Values" chapter in documentation.
-*/
-
-enum enum_mysql_timestamp_type
-{
- MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1,
- MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2
-};
-
-
-/*
- Structure which is used to represent datetime values inside MySQL.
-
- We assume that values in this structure are normalized, i.e. year <= 9999,
- month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions
- in server such as my_system_gmt_sec() or make_time() family of functions
- rely on this (actually now usage of make_*() family relies on a bit weaker
- restriction). Also functions that produce MYSQL_TIME as result ensure this.
- There is one exception to this rule though if this structure holds time
- value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold
- bigger values.
-*/
-typedef struct st_mysql_time
-{
- unsigned int year, month, day, hour, minute, second;
- unsigned long second_part;
- my_bool neg;
- enum enum_mysql_timestamp_type time_type;
-} MYSQL_TIME;
-
-#endif /* _mysql_time_h_ */
diff --git a/Frameworks/MCPKit/MySQL/include/mysql_version.h b/Frameworks/MCPKit/MySQL/include/mysql_version.h
deleted file mode 100644
index 1eba2ede..00000000
--- a/Frameworks/MCPKit/MySQL/include/mysql_version.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Copyright Abandoned 1996, 1999, 2001 MySQL AB
- This file is public domain and comes with NO WARRANTY of any kind */
-
-/* Version numbers for protocol & mysqld */
-
-#ifndef _mysql_version_h
-#define _mysql_version_h
-#ifdef _CUSTOMCONFIG_
-#include <custom_conf.h>
-#else
-#define PROTOCOL_VERSION 10
-#define MYSQL_SERVER_VERSION "5.1.57"
-#define MYSQL_BASE_VERSION "mysqld-5.1"
-#define MYSQL_SERVER_SUFFIX_DEF ""
-#define FRM_VER 6
-#define MYSQL_VERSION_ID 50157
-#define MYSQL_PORT 3306
-#define MYSQL_PORT_DEFAULT 0
-#define MYSQL_UNIX_ADDR "/tmp/mysql.sock"
-#define MYSQL_CONFIG_NAME "my"
-#define MYSQL_COMPILATION_COMMENT "Source distribution"
-
-/* mysqld compile time options */
-#endif /* _CUSTOMCONFIG_ */
-
-#ifndef LICENSE
-#define LICENSE GPL
-#endif /* LICENSE */
-
-#endif /* _mysql_version_h */
diff --git a/Frameworks/MCPKit/MySQL/include/typelib.h b/Frameworks/MCPKit/MySQL/include/typelib.h
deleted file mode 100644
index 46106d1b..00000000
--- a/Frameworks/MCPKit/MySQL/include/typelib.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Copyright (C) 2000 MySQL AB
-
- 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; version 2 of the License.
-
- 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 */
-
-
-#ifndef _typelib_h
-#define _typelib_h
-
-#include "my_alloc.h"
-
-typedef struct st_typelib { /* Different types saved here */
- unsigned int count; /* How many types */
- const char *name; /* Name of typelib */
- const char **type_names;
- unsigned int *type_lengths;
-} TYPELIB;
-
-extern my_ulonglong find_typeset(char *x, TYPELIB *typelib,int *error_position);
-extern int find_type_or_exit(const char *x, TYPELIB *typelib,
- const char *option);
-extern int find_type(char *x, const TYPELIB *typelib, unsigned int full_name);
-extern void make_type(char *to,unsigned int nr,TYPELIB *typelib);
-extern const char *get_type(TYPELIB *typelib,unsigned int nr);
-extern TYPELIB *copy_typelib(MEM_ROOT *root, TYPELIB *from);
-
-extern TYPELIB sql_protocol_typelib;
-
-#endif /* _typelib_h */
diff --git a/Frameworks/MCPKit/MySQL/lib/libmysqlclient.a b/Frameworks/MCPKit/MySQL/lib/libmysqlclient.a
deleted file mode 100644
index 969697fb..00000000
--- a/Frameworks/MCPKit/MySQL/lib/libmysqlclient.a
+++ /dev/null
Binary files differ
diff --git a/Frameworks/MCPKit/MySQL/lib/libmysqlclient_r.a b/Frameworks/MCPKit/MySQL/lib/libmysqlclient_r.a
deleted file mode 100644
index 3c8d05fd..00000000
--- a/Frameworks/MCPKit/MySQL/lib/libmysqlclient_r.a
+++ /dev/null
Binary files differ
diff --git a/Frameworks/MCPKit/Support files/NSNotificationAdditions.h b/Frameworks/MCPKit/Support files/NSNotificationAdditions.h
deleted file mode 100644
index 82777ebb..00000000
--- a/Frameworks/MCPKit/Support files/NSNotificationAdditions.h
+++ /dev/null
@@ -1,35 +0,0 @@
-//
-// $Id: NSNotificationAdditions.h 2045 2010-03-31 18:01:50Z stuart02 $
-//
-// NSNotificationAdditions.h
-// sequel-pro
-//
-// Copied from the Colloquy project; original code available from Trac at
-// http://colloquy.info/project/browser/trunk/Additions/NSNotificationAdditions.h
-//
-// 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/>
-
-@interface NSNotificationCenter (NSNotificationCenterAdditions)
-
-- (void)postNotificationOnMainThread:(NSNotification *)aNotification;
-- (void)postNotificationOnMainThread:(NSNotification *)aNotification waitUntilDone:(BOOL)shouldWaitUntilDone;
-
-- (void)postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject;
-- (void)postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
-- (void)postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo waitUntilDone:(BOOL)shouldWaitUntilDone;
-
-@end
diff --git a/Frameworks/MCPKit/Support files/NSNotificationAdditions.m b/Frameworks/MCPKit/Support files/NSNotificationAdditions.m
deleted file mode 100644
index 91b8134d..00000000
--- a/Frameworks/MCPKit/Support files/NSNotificationAdditions.m
+++ /dev/null
@@ -1,97 +0,0 @@
-//
-// $Id: NSNotificationAdditions.m 2045 2010-03-31 18:01:50Z stuart02 $
-//
-// NSNotificationAdditions.m
-// sequel-pro
-//
-// Copied from the Colloquy project; original code available from Trac at
-// http://colloquy.info/project/browser/trunk/Additions/NSNotificationAdditions.m
-//
-// 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 "NSNotificationAdditions.h"
-#import "pthread.h"
-
-@interface NSNotificationCenter (NSNotificationCenterAdditions_PrivateAPI)
-+ (void)_postNotification:(NSNotification *)aNotification;
-+ (void)_postNotificationWithDetails:(NSDictionary *)anInfoDictionary;
-@end
-
-@implementation NSNotificationCenter (NSNotificationCenterAdditions)
-
-- (void)postNotificationOnMainThread:(NSNotification *)aNotification
-{
- if (pthread_main_np()) return [self postNotification:aNotification];
-
- [self performSelectorOnMainThread:@selector(_postNotification:) withObject:aNotification waitUntilDone:NO];
-}
-
-- (void)postNotificationOnMainThread:(NSNotification *)aNotification waitUntilDone:(BOOL)shouldWaitUntilDone
-{
- if (pthread_main_np()) return [self postNotification:aNotification];
-
- [self performSelectorOnMainThread:@selector(_postNotification:) withObject:aNotification waitUntilDone:shouldWaitUntilDone];
-}
-
-- (void)postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject
-{
- if (pthread_main_np()) return [self postNotificationName:aName object:anObject userInfo:nil];
-
- [self postNotificationOnMainThreadWithName:aName object:anObject userInfo:nil waitUntilDone:NO];
-}
-
-- (void)postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo
-{
- if(pthread_main_np()) return [self postNotificationName:aName object:anObject userInfo:aUserInfo];
-
- [self postNotificationOnMainThreadWithName:aName object:anObject userInfo:aUserInfo waitUntilDone:NO];
-}
-
-- (void)postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo waitUntilDone:(BOOL)shouldWaitUntilDone
-{
- if (pthread_main_np()) return [self postNotificationName:aName object:anObject userInfo:aUserInfo];
-
- NSMutableDictionary *info = [[NSMutableDictionary allocWithZone:nil] initWithCapacity:3];
-
- if (aName) [info setObject:aName forKey:@"name"];
- if (anObject) [info setObject:anObject forKey:@"object"];
- if (aUserInfo) [info setObject:aUserInfo forKey:@"userInfo"];
-
- [[self class] performSelectorOnMainThread:@selector(_postNotificationWithDetails:) withObject:info waitUntilDone:shouldWaitUntilDone];
-}
-
-@end
-
-@implementation NSNotificationCenter (NSNotificationCenterAdditions_PrivateAPI)
-
-+ (void)_postNotification:(NSNotification *)aNotification
-{
- [[self defaultCenter] postNotification:aNotification];
-}
-
-+ (void)_postNotificationWithDetails:(NSDictionary *)anInfoDictionary
-{
- NSString *name = [anInfoDictionary objectForKey:@"name"];
- id object = [anInfoDictionary objectForKey:@"object"];
- NSDictionary *userInfo = [anInfoDictionary objectForKey:@"userInfo"];
-
- [[self defaultCenter] postNotificationName:name object:object userInfo:userInfo];
-
- [anInfoDictionary release];
-}
-
-@end
diff --git a/Frameworks/SPMySQLFramework/SPMySQLFramework.xcodeproj/project.pbxproj b/Frameworks/SPMySQLFramework/SPMySQLFramework.xcodeproj/project.pbxproj
index 344a498b..a9f8db0d 100644
--- a/Frameworks/SPMySQLFramework/SPMySQLFramework.xcodeproj/project.pbxproj
+++ b/Frameworks/SPMySQLFramework/SPMySQLFramework.xcodeproj/project.pbxproj
@@ -30,6 +30,8 @@
584294FF14CB8002000F8438 /* Server Info.m in Sources */ = {isa = PBXBuildFile; fileRef = 584294FD14CB8002000F8438 /* Server Info.m */; };
586A99FB14F02E21007F82BF /* SPMySQLStreamingResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 586A99F914F02E21007F82BF /* SPMySQLStreamingResult.h */; settings = {ATTRIBUTES = (Public, ); }; };
586A99FC14F02E21007F82BF /* SPMySQLStreamingResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 586A99FA14F02E21007F82BF /* SPMySQLStreamingResult.m */; };
+ 586AA16714F30C5F007F82BF /* Convenience Methods.h in Headers */ = {isa = PBXBuildFile; fileRef = 586AA16514F30C5F007F82BF /* Convenience Methods.h */; settings = {ATTRIBUTES = (Public, ); }; };
+ 586AA16814F30C5F007F82BF /* Convenience Methods.m in Sources */ = {isa = PBXBuildFile; fileRef = 586AA16614F30C5F007F82BF /* Convenience Methods.m */; };
5884127714CC63830078027F /* SPMySQL.h in Headers */ = {isa = PBXBuildFile; fileRef = 5884127614CC63830078027F /* SPMySQL.h */; settings = {ATTRIBUTES = (Public, ); }; };
588412A814CC7A4D0078027F /* Locking.h in Headers */ = {isa = PBXBuildFile; fileRef = 588412A614CC7A4D0078027F /* Locking.h */; };
5884133C14CCEC6B0078027F /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5884133B14CCEC6B0078027F /* libz.dylib */; };
@@ -92,6 +94,8 @@
586A99F914F02E21007F82BF /* SPMySQLStreamingResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPMySQLStreamingResult.h; path = Source/SPMySQLStreamingResult.h; sourceTree = "<group>"; };
586A99FA14F02E21007F82BF /* SPMySQLStreamingResult.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPMySQLStreamingResult.m; path = Source/SPMySQLStreamingResult.m; sourceTree = "<group>"; };
586AA0E714F1CEC8007F82BF /* Readme.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Readme.txt; sourceTree = "<group>"; };
+ 586AA16514F30C5F007F82BF /* Convenience Methods.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "Convenience Methods.h"; path = "Source/SPMySQLResult Categories/Convenience Methods.h"; sourceTree = "<group>"; };
+ 586AA16614F30C5F007F82BF /* Convenience Methods.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "Convenience Methods.m"; path = "Source/SPMySQLResult Categories/Convenience Methods.m"; sourceTree = "<group>"; };
5884127614CC63830078027F /* SPMySQL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPMySQL.h; path = Source/SPMySQL.h; sourceTree = "<group>"; };
588412A614CC7A4D0078027F /* Locking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Locking.h; path = "Source/SPMySQLConnection Categories/Locking.h"; sourceTree = "<group>"; };
588412A714CC7A4D0078027F /* Locking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Locking.m; path = "Source/SPMySQLConnection Categories/Locking.m"; sourceTree = "<group>"; };
@@ -335,6 +339,8 @@
children = (
58C7C1E614DB6E8600436315 /* Field Definitions.h */,
58C7C1E714DB6E8600436315 /* Field Definitions.m */,
+ 586AA16514F30C5F007F82BF /* Convenience Methods.h */,
+ 586AA16614F30C5F007F82BF /* Convenience Methods.m */,
);
name = "Result Categories";
sourceTree = "<group>";
@@ -376,6 +382,7 @@
58C00BD114E7459600AC489A /* Databases & Tables.h in Headers */,
58C00CA514E845D800AC489A /* SPMySQL Private APIs.h in Headers */,
586A99FB14F02E21007F82BF /* SPMySQLStreamingResult.h in Headers */,
+ 586AA16714F30C5F007F82BF /* Convenience Methods.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -458,6 +465,7 @@
58C00AB614E4892E00AC489A /* Delegate & Proxy.m in Sources */,
58C00BD214E7459600AC489A /* Databases & Tables.m in Sources */,
586A99FC14F02E21007F82BF /* SPMySQLStreamingResult.m in Sources */,
+ 586AA16814F30C5F007F82BF /* Convenience Methods.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -526,7 +534,11 @@
1DEB91B208733DA50010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ ARCHS = (
+ i386,
+ ppc,
+ x86_64,
+ );
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
@@ -555,7 +567,11 @@
1DEB91B308733DA50010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ ARCHS = (
+ i386,
+ ppc,
+ x86_64,
+ );
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -579,6 +595,60 @@
};
name = Release;
};
+ 586AA55214F5D599007F82BF /* Distribution */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ARCHS = (
+ i386,
+ ppc,
+ x86_64,
+ );
+ GCC_C_LANGUAGE_STANDARD = gnu99;
+ GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
+ GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES;
+ GCC_WARN_CHECK_SWITCH_STATEMENTS = YES;
+ GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
+ GCC_WARN_MISSING_PARENTHESES = YES;
+ GCC_WARN_PROTOTYPE_CONVERSION = YES;
+ GCC_WARN_SHADOW = YES;
+ GCC_WARN_SIGN_COMPARE = YES;
+ GCC_WARN_STRICT_SELECTOR_MATCH = YES;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ MACH_O_TYPE = mh_dylib;
+ PREBINDING = NO;
+ SDKROOT = macosx10.5;
+ VALID_ARCHS = "i386 ppc x86_64";
+ };
+ name = Distribution;
+ };
+ 586AA55314F5D599007F82BF /* Distribution */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ DEAD_CODE_STRIPPING = YES;
+ DYLIB_COMPATIBILITY_VERSION = 1;
+ DYLIB_CURRENT_VERSION = 1;
+ FRAMEWORK_VERSION = A;
+ GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
+ GCC_MODEL_TUNING = G5;
+ GCC_PRECOMPILE_PREFIX_HEADER = YES;
+ GCC_PREFIX_HEADER = Source/SPMySQLFramework_Prefix.pch;
+ INFOPLIST_FILE = Resources/Info.plist;
+ INSTALL_PATH = "@executable_path/../Frameworks";
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "\"$(SRCROOT)/MySQL Client Libraries/lib\"",
+ );
+ PRODUCT_NAME = SPMySQL;
+ WRAPPER_EXTENSION = framework;
+ };
+ name = Distribution;
+ };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -587,6 +657,7 @@
buildConfigurations = (
1DEB91AE08733DA50010E9CD /* Debug */,
1DEB91AF08733DA50010E9CD /* Release */,
+ 586AA55314F5D599007F82BF /* Distribution */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
@@ -596,6 +667,7 @@
buildConfigurations = (
1DEB91B208733DA50010E9CD /* Debug */,
1DEB91B308733DA50010E9CD /* Release */,
+ 586AA55214F5D599007F82BF /* Distribution */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQL.h b/Frameworks/SPMySQLFramework/Source/SPMySQL.h
index a9150f46..3c4c78f8 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQL.h
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQL.h
@@ -57,6 +57,7 @@
#import "SPMySQLStreamingResult.h"
#import "SPMySQLFastStreamingResult.h"
#import "Field Definitions.h"
+#import "Convenience Methods.h"
// Result data objects
-#import "SPMySQLGeometryData.h" \ No newline at end of file
+#import "SPMySQLGeometryData.h"
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.h b/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.h
index ff55f796..9ab8bc6a 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.h
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.h
@@ -45,6 +45,10 @@
- (id)streamingQueryString:(NSString *)theQueryString useLowMemoryBlockingStreaming:(BOOL)fullStreaming;
- (id)queryString:(NSString *)theQueryString usingEncoding:(NSStringEncoding)theEncoding withResultType:(SPMySQLResultType)theReturnType;
+// Query convenience functions
+- (NSArray *)getAllRowsFromQuery:(NSString *)theQueryString;
+- (id)getFirstFieldFromQuery:(NSString *)theQueryString;
+
// Query information
- (unsigned long long)rowsAffectedByLastQuery;
- (unsigned long long)lastInsertID;
@@ -100,4 +104,4 @@ static inline id SPMySQLConnectionQueryString(SPMySQLConnection* self, NSString
if (!cachedMethodPointer) cachedMethodPointer = (SPMySQLConnectionQueryStringMethodPtr)[self methodForSelector:cachedSelector];
return cachedMethodPointer(self, cachedSelector, theQueryString, theEncoding, theReturnType);
-} \ No newline at end of file
+}
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.m b/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.m
index 4134880c..e3ce599a 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.m
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Querying & Preparation.m
@@ -357,6 +357,27 @@
}
#pragma mark -
+#pragma mark Query convenience functions
+
+/**
+ * Run a query and retrieve the entire result set as an array of dictionaries.
+ * Returns nil if there was a problem running the query or retrieving any results.
+ */
+- (NSArray *)getAllRowsFromQuery:(NSString *)theQueryString
+{
+ return [[self queryString:theQueryString] getAllRows];
+}
+
+/**
+ * Run a query and retrieve the first field of any response. Returns nil if there
+ * was a problem running the query or retrieving any results.
+ */
+- (id)getFirstFieldFromQuery:(NSString *)theQueryString
+{
+ return [[[self queryString:theQueryString] getRowAsArray] objectAtIndex:0];
+}
+
+#pragma mark -
#pragma mark Query information
/**
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLConnection.h b/Frameworks/SPMySQLFramework/Source/SPMySQLConnection.h
index db6dc0af..5d1a5d11 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQLConnection.h
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLConnection.h
@@ -174,4 +174,4 @@
+ (NSString *)findSocketPath;
-@end \ No newline at end of file
+@end
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionDelegate.h b/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionDelegate.h
index f1a1f911..97e94170 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionDelegate.h
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionDelegate.h
@@ -30,6 +30,8 @@
//
// More info at <http://code.google.com/p/sequel-pro/>
+#import "SPMySQLConstants.h"
+
@protocol SPMySQLConnectionDelegate <NSObject>
@optional
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionProxy.h b/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionProxy.h
index afd7c95a..2da553c6 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionProxy.h
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLConnectionProxy.h
@@ -74,4 +74,4 @@ typedef enum {
*/
- (BOOL)setConnectionStateChangeSelector:(SEL)theStateChangeSelector delegate:(id)theDelegate;
-@end \ No newline at end of file
+@end
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLConstants.h b/Frameworks/SPMySQLFramework/Source/SPMySQLConstants.h
index 6fb3d279..b1689569 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQLConstants.h
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLConstants.h
@@ -73,4 +73,4 @@ typedef enum {
SPMySQLResultAsResult = 0,
SPMySQLResultAsFastStreamingResult = 1,
SPMySQLResultAsLowMemStreamingResult = 2
-} SPMySQLResultType; \ No newline at end of file
+} SPMySQLResultType;
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.h b/Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.h
new file mode 100644
index 00000000..7d870a93
--- /dev/null
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.h
@@ -0,0 +1,38 @@
+//
+// $Id$
+//
+// Convenience Methods.h
+// SPMySQLFramework
+//
+// Created by Rowan Beentje (rowan.beent.je) on February 20, 2012
+// Copyright (c) 2012 Rowan Beentje. All rights reserved.
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without
+// restriction, including without limitation the rights to use,
+// copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the
+// Software is furnished to do so, subject to the following
+// conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//
+// More info at <http://code.google.com/p/sequel-pro/>
+
+
+@interface SPMySQLResult (Convenience_Methods)
+
+- (NSArray *)getAllRows;
+
+@end
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.m b/Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.m
new file mode 100644
index 00000000..7e3619e1
--- /dev/null
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLResult Categories/Convenience Methods.m
@@ -0,0 +1,71 @@
+//
+// $Id$
+//
+// Convenience Methods.h
+// SPMySQLFramework
+//
+// Created by Rowan Beentje (rowan.beent.je) on February 20, 2012
+// Copyright (c) 2012 Rowan Beentje. All rights reserved.
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without
+// restriction, including without limitation the rights to use,
+// copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the
+// Software is furnished to do so, subject to the following
+// conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//
+// More info at <http://code.google.com/p/sequel-pro/>
+
+#import "Convenience Methods.h"
+
+@implementation SPMySQLResult (Convenience_Methods)
+
+/**
+ * Iterates over the result set, retrieving all the rows, and returns them
+ * as an array.
+ * The rows are in the default format for this instance, as controlled via
+ * -setDefaultRowReturnType:.
+ * Returns nil if there are no rows to return.
+ */
+- (NSArray *)getAllRows
+{
+ unsigned long long previousSeekPosition = currentRowIndex;
+
+ NSMutableArray *rowsToReturn;
+
+ // If the number of rows is known, pre-set the size; otherwise just create an array
+ if (numberOfRows != NSNotFound) {
+ rowsToReturn = [[NSMutableArray alloc] initWithCapacity:numberOfRows];
+ } else {
+ rowsToReturn = [[NSMutableArray alloc] init];
+ }
+
+ // Loop through the rows in the instance-specified return format
+ for (id eachRow in self) {
+ [rowsToReturn addObject:eachRow];
+ }
+
+ // Seek to the previous position if appropriate
+ if (previousSeekPosition) [self seekToRow:previousSeekPosition];
+
+ // Instead of empty arrays, return nil if there are no rows.
+ if (![rowsToReturn count]) return nil;
+
+ return rowsToReturn;
+}
+
+@end
diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLResult.h b/Frameworks/SPMySQLFramework/Source/SPMySQLResult.h
index baddf8aa..29518b5d 100644
--- a/Frameworks/SPMySQLFramework/Source/SPMySQLResult.h
+++ b/Frameworks/SPMySQLFramework/Source/SPMySQLResult.h
@@ -73,6 +73,7 @@ typedef enum {
// Result set information
- (NSUInteger)numberOfFields;
- (unsigned long long)numberOfRows;
+- (double)queryExecutionTime;
// Column information
- (NSArray *)fieldNames;
@@ -117,4 +118,4 @@ static inline id SPMySQLResultGetRow(SPMySQLResult* self, SPMySQLResultRowType r
if (!cachedMethodPointer) cachedMethodPointer = (SPMySQLResultGetRowMethodPtr)[self methodForSelector:cachedSelector];
return cachedMethodPointer(self, cachedSelector, rowType);
-} \ No newline at end of file
+}