//
//  DataModeller.m
//  DatabaseExample
//
//  Created by Bernard Teo on 27/06/2007.
//  Copyright 2007 Cutedge. All rights reserved.
//

#import "DataModeller.h"

#import <objc/objc-class.h>

typedef struct objc_class*			ObjC_Class_Info;
typedef struct objc_ivar_list*		ObjC_DataMemberList;

@implementation DataModeller

+ (id)dataModellerWithConnectionForDatabaseDriver:(NSString *)driver url:(NSString *)url databaseName:(NSString *)databaseName user:(NSString *)user password:(NSString *)password
{
	id model = [[self alloc] initForDatabaseDriver:driver url:url databaseName:databaseName user:user password:password];
	
	return [model autorelease];
}

- (id)initForDatabaseDriver:(NSString *)driver url:(NSString *)url databaseName:(NSString *)databaseName user:(NSString *)user password:(NSString *)password 
{
    self = [super init];
    if (self) {
		Class SqlConnectClass;
		if ([driver isEqualToString:@"SQLite3"]) 
			SqlConnectClass = [CEDatabaseSQLite class];
		else if ([driver isEqualToString:@"MySQL5"])
			SqlConnectClass = [CEDatabaseMySQL class];
		else if ([driver isEqualToString:@"PostgreSQL"])
			SqlConnectClass = [CEDatabasePostgreSQL class];
		
		[self setConnection:[SqlConnectClass connectionWithURL:url database:databaseName user:user password:password]];
		[self setDatabaseType:driver];
		[self setDatabase:databaseName];
    }
    return self;
}

- (void)setConnection:(CEDatabase *)value
{
	[connection autorelease];
	connection = [value retain];
}

- (void)setDatabaseType:(NSString *)value
{
	[databaseType autorelease];
	databaseType = [[NSString stringWithString:value] retain];
}

- (NSString *)databaseType
{
	return databaseType;
}

- (void)setDatabase:(NSString *)value
{
	[database autorelease];
	database = [[NSString stringWithString:value] retain];
}

- (NSString *)database
{
	return database;
}

- (void)dealloc
{
	[connection release];
	[databaseType release];
	[database release];
	
	[super dealloc];
}

- (NSMutableArray *)lookup:(NSString *)queryString
{		
	CEResultSet *rs = [connection executeQuery:queryString];		
	return [rs resultAsArrayOfDict];
}

- (void)execute:(NSString *)queryString
{
	[connection executeQuery:queryString];
}

@end
