/***************************************************************************

    supportware
    Copyright (C) 2001-2008 by c.holzheuer
    c.holzheuer@sourceworx.org

    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.

***************************************************************************/


#include <dddataconnection.h>
#include <ddstringrow.h>


/**
	Default constructor.
*/  

dddataconnection::dddataconnection()
: _connected( false )
{
  ::mysql_init( &_mysql );
}


/**
	Default constructor.
*/  

dddataconnection::dddataconnection( const ddstring& db, const ddstring& host, const ddstring& user, const ddstring& pass )
: _connected( false )
{
	::mysql_init( &_mysql );
	connect( db, host, user, pass );
}
 
 
/**
	Standard constructor.
*/  

dddataconnection::dddataconnection( const ddstring& connectstring )
: _connected( false )
{
	::mysql_init( &_mysql );
	connect( connectstring );
}

          
/**
	Destructor.
*/  

dddataconnection::~dddataconnection()
{
	close();
}

 
/**
	Diese connection schliessen. 
*/  


void dddataconnection::close() 
{
	::mysql_close( &_mysql );
	_connected = false;
}


/**
	Eine Verbindung zu MySql-Server aufbauen.
	@param connectstring der CSV connectstring aka "database;host;user;pass"
*/  

void dddataconnection::connect( const ddstring& connectstring )
{
	ddstringrow row( connectstring, ";" );
	if( row.size()<4 )
		throw runtime_error( "dddataconnection::connect: invalid connectstring" + connectstring );
	connect( row[0], row[1], row[2], row[3] );
}


/**
	Eine Verbindung zu MySql-Server aufbauen.	
*/  


void dddataconnection::connect( const ddstring& db, const ddstring& host ,const ddstring& user, const ddstring& passwd )
{
	if( _connected )
		close();
		
	_connected = ( ::mysql_real_connect(
		&_mysql, 
		host.c_str(),
		user.c_str(), 
		passwd.c_str(), 
		db.c_str(), 
		3306,
		NULL, 
		CLIENT_MULTI_STATEMENTS ) != NULL );
	
	if( !_connected )
		throw runtime_error( "dddataconnection::connect: invalid connect failed" + ddstring( ::mysql_error( &_mysql ) ) );

}







