2010-10-07 15:54:07 +02:00
/*
2012-01-01 00:32:13 +01:00
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
2010-10-07 15:54:07 +02:00
*
* 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, see <http://www.gnu.org/licenses/>.
2010-08-18 02:25:52 +02:00
*/
#ifndef _DATABASEWORKERPOOL_H
#define _DATABASEWORKERPOOL_H
#include <ace/Thread_Mutex.h>
2010-09-03 00:04:14 +02:00
#include "Common.h"
2010-08-18 19:48:51 +02:00
#include "Callback.h"
2010-08-18 02:25:52 +02:00
#include "MySQLConnection.h"
2010-09-03 00:04:14 +02:00
#include "Transaction.h"
2010-09-02 17:47:50 +02:00
#include "DatabaseWorker.h"
2010-09-03 00:08:20 +02:00
#include "PreparedStatement.h"
2010-09-02 17:19:53 -06:00
#include "Log.h"
2010-09-11 21:10:54 +02:00
#include "QueryResult.h"
2010-09-19 12:36:48 +02:00
#include "QueryHolder.h"
#include "AdhocStatement.h"
2010-08-18 02:25:52 +02:00
2010-09-25 01:05:24 +02:00
class PingOperation : public SQLOperation
{
/// Operation for idle delaythreads
bool Execute ()
{
2010-10-31 10:55:29 +01:00
if ( m_conn -> LockIfReady ())
{
m_conn -> Ping ();
m_conn -> Unlock ();
return true ;
}
2010-09-27 00:20:56 +02:00
return false ;
2010-09-25 01:05:24 +02:00
}
};
2010-09-02 17:47:50 +02:00
template < class T >
2010-08-18 02:25:52 +02:00
class DatabaseWorkerPool
{
public :
2010-12-23 16:05:43 +01:00
/* Activity state */
2010-09-02 17:47:50 +02:00
DatabaseWorkerPool () :
2012-03-26 01:49:41 +02:00
m_queue ( new ACE_Activation_Queue ())
2010-09-02 17:47:50 +02:00
{
2010-12-13 17:21:06 +01:00
memset ( m_connectionCount , 0 , sizeof ( m_connectionCount ));
2010-12-13 09:18:49 +01:00
m_connections . resize ( IDX_SIZE );
2010-09-02 17:47:50 +02:00
WPFatal ( mysql_thread_safe (), "Used MySQL library isn't thread-safe." );
}
~ DatabaseWorkerPool ()
{
}
2010-12-13 09:18:49 +01:00
bool Open ( const std :: string & infoString , uint8 async_threads , uint8 synch_threads )
2010-09-02 17:47:50 +02:00
{
2011-04-07 15:30:38 +06:00
bool res = true ;
2010-09-29 15:29:57 +02:00
m_connectionInfo = MySQLConnectionInfo ( infoString );
2010-09-29 08:48:06 +02:00
2010-12-23 23:25:44 +01:00
sLog -> outSQLDriver ( "Opening databasepool '%s'. Async threads: %u, synch threads: %u" , m_connectionInfo . database . c_str (), async_threads , synch_threads );
2010-09-03 10:52:32 +02:00
2010-12-13 09:18:49 +01:00
/// Open asynchronous connections (delayed operations)
m_connections [ IDX_ASYNC ]. resize ( async_threads );
for ( uint8 i = 0 ; i < async_threads ; ++ i )
2010-09-02 17:47:50 +02:00
{
2010-12-13 09:18:49 +01:00
T * t = new T ( m_queue , m_connectionInfo );
m_connections [ IDX_ASYNC ][ i ] = t ;
2010-12-13 16:13:32 +01:00
++ m_connectionCount [ IDX_ASYNC ];
2010-09-02 17:47:50 +02:00
}
2010-12-13 09:18:49 +01:00
/// Open synchronous connections (direct, blocking operations)
m_connections [ IDX_SYNCH ]. resize ( synch_threads );
2010-12-13 22:37:56 +01:00
for ( uint8 i = 0 ; i < synch_threads ; ++ i )
2010-12-13 09:18:49 +01:00
{
T * t = new T ( m_connectionInfo );
2011-04-07 15:30:38 +06:00
res &= t -> Open ();
2010-12-13 09:18:49 +01:00
m_connections [ IDX_SYNCH ][ i ] = t ;
2010-12-13 16:13:32 +01:00
++ m_connectionCount [ IDX_SYNCH ];
2010-12-13 09:18:49 +01:00
}
2010-12-04 21:50:36 +01:00
2011-12-25 02:21:46 +01:00
sLog -> outSQLDriver ( "Databasepool opened successfully. %u total connections running." , ( m_connectionCount [ IDX_SYNCH ] + m_connectionCount [ IDX_ASYNC ]));
2011-04-07 15:30:38 +06:00
return res ;
2010-09-02 17:47:50 +02:00
}
void Close ()
{
2010-12-23 23:25:44 +01:00
sLog -> outSQLDriver ( "Closing down databasepool '%s'." , m_connectionInfo . database . c_str ());
2010-09-02 17:47:50 +02:00
2011-01-13 20:28:40 +01:00
/// Shuts down delaythreads for this connection pool by underlying deactivate()
m_queue -> queue () -> close ();
2010-12-17 16:02:09 +01:00
2010-12-13 16:13:32 +01:00
for ( uint8 i = 0 ; i < m_connectionCount [ IDX_ASYNC ]; ++ i )
2010-12-06 19:52:37 +01:00
{
2010-12-13 09:18:49 +01:00
/// TODO: Better way. probably should flip a boolean and check it on low level code before doing anything on the mysql ctx
/// Now we just wait until m_queue gives the signal to the worker threads to stop
T * t = m_connections [ IDX_ASYNC ][ i ];
2010-12-13 16:13:32 +01:00
DatabaseWorker * worker = t -> m_worker ;
2011-01-16 13:33:47 +01:00
worker -> wait ();
2010-12-06 19:52:37 +01:00
delete worker ;
}
2010-09-02 17:47:50 +02:00
2010-12-23 23:25:44 +01:00
sLog -> outSQLDriver ( "Asynchronous connections on databasepool '%s' terminated. Proceeding with synchronous connections." , m_connectionInfo . database . c_str ());
2010-09-02 17:47:50 +02:00
2010-12-13 09:18:49 +01:00
/// Shut down the synchronous connections
2010-12-13 16:13:32 +01:00
for ( uint8 i = 0 ; i < m_connectionCount [ IDX_SYNCH ]; ++ i )
2010-09-02 17:47:50 +02:00
{
2010-12-13 09:18:49 +01:00
T * t = m_connections [ IDX_SYNCH ][ i ];
//while (1)
2010-12-13 22:37:56 +01:00
// if (t->LockIfReady()) -- For some reason deadlocks us
2010-12-13 09:18:49 +01:00
t -> Close ();
2010-09-02 17:47:50 +02:00
}
2010-12-13 22:37:56 +01:00
2012-03-26 01:49:41 +02:00
delete m_queue ;
2010-12-23 23:25:44 +01:00
sLog -> outSQLDriver ( "All connections on databasepool %s closed." , m_connectionInfo . database . c_str ());
2010-09-02 17:47:50 +02:00
}
2011-01-26 00:41:55 +01:00
/**
2010-12-23 16:05:43 +01:00
Delayed one-way statement methods.
*/
//! Enqueues a one-way SQL operation in string format that will be executed asynchronously.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
2010-09-02 17:47:50 +02:00
void Execute ( const char * sql )
{
if ( ! sql )
return ;
BasicStatementTask * task = new BasicStatementTask ( sql );
Enqueue ( task );
}
2010-12-23 16:05:43 +01:00
//! Enqueues a one-way SQL operation in string format -with variable args- that will be executed asynchronously.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
2010-09-02 17:47:50 +02:00
void PExecute ( const char * sql , ...)
{
if ( ! sql )
return ;
va_list ap ;
char szQuery [ MAX_QUERY_LEN ];
va_start ( ap , sql );
vsnprintf ( szQuery , MAX_QUERY_LEN , sql , ap );
va_end ( ap );
Execute ( szQuery );
}
2010-12-23 16:05:43 +01:00
//! Enqueues a one-way SQL operation in prepared statement format that will be executed asynchronously.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with CONNECTION_ASYNC flag.
2010-12-23 16:05:43 +01:00
void Execute ( PreparedStatement * stmt )
{
PreparedStatementTask * task = new PreparedStatementTask ( stmt );
Enqueue ( task );
}
/**
2012-03-19 18:08:32 +01:00
Direct synchronous one-way statement methods.
2010-12-23 16:05:43 +01:00
*/
//! Directly executes a one-way SQL operation in string format, that will block the calling thread until finished.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
2010-09-02 17:47:50 +02:00
void DirectExecute ( const char * sql )
{
2010-09-27 00:20:56 +02:00
if ( ! sql )
return ;
2010-12-13 22:37:56 +01:00
2010-09-27 00:20:56 +02:00
T * t = GetFreeConnection ();
t -> Execute ( sql );
t -> Unlock ();
2010-09-02 17:47:50 +02:00
}
2010-12-23 16:05:43 +01:00
//! Directly executes a one-way SQL operation in string format -with variable args-, that will block the calling thread until finished.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
2010-09-02 17:47:50 +02:00
void DirectPExecute ( const char * sql , ...)
{
if ( ! sql )
return ;
va_list ap ;
char szQuery [ MAX_QUERY_LEN ];
va_start ( ap , sql );
vsnprintf ( szQuery , MAX_QUERY_LEN , sql , ap );
va_end ( ap );
return DirectExecute ( szQuery );
}
2010-12-23 16:05:43 +01:00
//! Directly executes a one-way SQL operation in prepared statement format, that will block the calling thread until finished.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with the CONNECTION_SYNCH flag.
2010-12-23 16:05:43 +01:00
void DirectExecute ( PreparedStatement * stmt )
{
T * t = GetFreeConnection ();
t -> Execute ( stmt );
t -> Unlock ();
}
/**
2011-12-19 11:11:25 +01:00
Synchronous query (with resultset) methods.
2010-12-23 16:05:43 +01:00
*/
//! Directly executes an SQL query in string format that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
2010-09-27 00:20:56 +02:00
QueryResult Query ( const char * sql , MySQLConnection * conn = NULL )
2010-09-02 17:47:50 +02:00
{
2010-09-27 00:20:56 +02:00
if ( ! conn )
conn = GetFreeConnection ();
ResultSet * result = conn -> Query ( sql );
conn -> Unlock ();
2010-09-19 12:16:29 +02:00
if ( ! result || ! result -> GetRowCount ())
return QueryResult ( NULL );
result -> NextRow ();
return QueryResult ( result );
2010-09-02 17:47:50 +02:00
}
2010-12-23 16:05:43 +01:00
//! Directly executes an SQL query in string format -with variable args- that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
2010-09-27 00:20:56 +02:00
QueryResult PQuery ( const char * sql , MySQLConnection * conn , ...)
{
if ( ! sql )
return QueryResult ( NULL );
va_list ap ;
char szQuery [ MAX_QUERY_LEN ];
va_start ( ap , sql );
vsnprintf ( szQuery , MAX_QUERY_LEN , sql , ap );
va_end ( ap );
return Query ( szQuery , conn );
}
2010-12-23 16:05:43 +01:00
//! Directly executes an SQL query in string format -with variable args- that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
2010-09-11 21:10:54 +02:00
QueryResult PQuery ( const char * sql , ...)
2010-09-02 17:47:50 +02:00
{
if ( ! sql )
2010-09-11 21:10:54 +02:00
return QueryResult ( NULL );
2010-09-02 17:47:50 +02:00
va_list ap ;
char szQuery [ MAX_QUERY_LEN ];
va_start ( ap , sql );
vsnprintf ( szQuery , MAX_QUERY_LEN , sql , ap );
va_end ( ap );
return Query ( szQuery );
}
2010-12-23 16:05:43 +01:00
//! Directly executes an SQL query in prepared format that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with CONNECTION_SYNCH flag.
2010-12-23 16:05:43 +01:00
PreparedQueryResult Query ( PreparedStatement * stmt )
{
T * t = GetFreeConnection ();
PreparedResultSet * ret = t -> Query ( stmt );
t -> Unlock ();
if ( ! ret || ! ret -> GetRowCount ())
return PreparedQueryResult ( NULL );
return PreparedQueryResult ( ret );
}
2011-01-26 00:41:55 +01:00
/**
2010-12-23 16:05:43 +01:00
Asynchronous query (with resultset) methods.
*/
//! Enqueues a query in string format that will set the value of the QueryResultFuture return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
QueryResultFuture AsyncQuery ( const char * sql )
2010-09-02 17:47:50 +02:00
{
QueryResultFuture res ;
BasicStatementTask * task = new BasicStatementTask ( sql , res );
Enqueue ( task );
return res ; //! Actual return value has no use yet
}
2010-12-23 16:05:43 +01:00
//! Enqueues a query in string format -with variable args- that will set the value of the QueryResultFuture return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
QueryResultFuture AsyncPQuery ( const char * sql , ...)
2010-09-02 17:47:50 +02:00
{
va_list ap ;
char szQuery [ MAX_QUERY_LEN ];
va_start ( ap , sql );
vsnprintf ( szQuery , MAX_QUERY_LEN , sql , ap );
va_end ( ap );
return AsyncQuery ( szQuery );
}
2010-12-23 16:05:43 +01:00
//! Enqueues a query in prepared format that will set the value of the PreparedQueryResultFuture return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with CONNECTION_ASYNC flag.
2010-12-23 16:05:43 +01:00
PreparedQueryResultFuture AsyncQuery ( PreparedStatement * stmt )
{
PreparedQueryResultFuture res ;
PreparedStatementTask * task = new PreparedStatementTask ( stmt , res );
Enqueue ( task );
return res ;
}
//! Enqueues a vector of SQL operations (can be both adhoc and prepared) that will set the value of the QueryResultHolderFuture
//! return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
2011-12-19 11:11:25 +01:00
//! Any prepared statements added to this holder need to be prepared with the CONNECTION_ASYNC flag.
2010-09-02 17:47:50 +02:00
QueryResultHolderFuture DelayQueryHolder ( SQLQueryHolder * holder )
{
QueryResultHolderFuture res ;
SQLQueryHolderTask * task = new SQLQueryHolderTask ( holder , res );
Enqueue ( task );
return res ; //! Fool compiler, has no use yet
}
2010-09-12 01:40:27 +02:00
2010-12-23 16:05:43 +01:00
/**
Transaction context methods.
*/
//! Begins an automanaged transaction pointer that will automatically rollback if not commited. (Autocommit=0)
2010-09-02 17:47:50 +02:00
SQLTransaction BeginTransaction ()
{
return SQLTransaction ( new Transaction );
}
2010-12-23 16:05:43 +01:00
//! Enqueues a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations
//! were appended to the transaction will be respected during execution.
2010-09-02 17:47:50 +02:00
void CommitTransaction ( SQLTransaction transaction )
{
2010-12-23 23:25:44 +01:00
if ( sLog -> GetSQLDriverQueryLogging ())
2010-09-02 17:47:50 +02:00
{
2010-12-06 19:52:37 +01:00
switch ( transaction -> GetSize ())
2010-11-19 13:13:07 +01:00
{
2010-12-06 19:52:37 +01:00
case 0 :
2010-12-23 23:25:44 +01:00
sLog -> outSQLDriver ( "Transaction contains 0 queries. Not executing." );
2010-12-06 19:52:37 +01:00
return ;
case 1 :
2010-12-23 23:25:44 +01:00
sLog -> outSQLDriver ( "Warning: Transaction only holds 1 query, consider removing Transaction context in code." );
2010-12-06 19:52:37 +01:00
break ;
default :
break ;
2010-11-19 13:13:07 +01:00
}
2010-09-02 17:47:50 +02:00
}
2010-12-06 19:52:37 +01:00
2010-09-02 17:47:50 +02:00
Enqueue ( new TransactionTask ( transaction ));
}
2010-08-18 02:25:52 +02:00
2011-01-13 20:07:09 +01:00
//! Directly executes a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations
//! were appended to the transaction will be respected during execution.
void DirectCommitTransaction ( SQLTransaction & transaction )
{
MySQLConnection * con = GetFreeConnection ();
if ( con -> ExecuteTransaction ( transaction ))
{
con -> Unlock (); // OK, operation succesful
return ;
}
2011-01-26 00:41:55 +01:00
2011-01-13 20:07:09 +01:00
if ( con -> GetLastError () == 1213 )
{
uint8 loopBreaker = 5 ; // Handle MySQL Errno 1213 without extending deadlock to the core itself
for ( uint8 i = 0 ; i < loopBreaker ; ++ i )
{
if ( con -> ExecuteTransaction ( transaction ))
break ;
}
}
2011-05-23 16:33:33 +02:00
// Clean up now.
transaction -> Cleanup ();
2011-01-13 20:07:09 +01:00
con -> Unlock ();
}
2010-12-13 16:27:14 +01:00
//! Method used to execute prepared statements in a diverse context.
//! Will be wrapped in a transaction if valid object is present, otherwise executed standalone.
void ExecuteOrAppend ( SQLTransaction & trans , PreparedStatement * stmt )
{
if ( trans . null ())
Execute ( stmt );
2010-12-13 22:37:56 +01:00
else
2010-12-13 16:27:14 +01:00
trans -> Append ( stmt );
}
//! Method used to execute ad-hoc statements in a diverse context.
//! Will be wrapped in a transaction if valid object is present, otherwise executed standalone.
void ExecuteOrAppend ( SQLTransaction & trans , const char * sql )
{
if ( trans . null ())
2010-12-13 17:05:01 +01:00
Execute ( sql );
2010-12-13 22:37:56 +01:00
else
2010-12-13 16:27:14 +01:00
trans -> Append ( sql );
}
2010-12-23 16:05:43 +01:00
/**
Other
*/
//! Automanaged (internally) pointer to a prepared statement object for usage in upper level code.
//! This object is not tied to the prepared statement on the MySQL context yet until execution.
2010-09-02 20:54:43 +02:00
PreparedStatement * GetPreparedStatement ( uint32 index )
{
return new PreparedStatement ( index );
}
2010-12-23 16:05:43 +01:00
//! Apply escape string'ing for current collation. (utf8)
2011-06-30 14:52:44 +02:00
void EscapeString ( std :: string & str )
2010-08-18 02:25:52 +02:00
{
if ( str . empty ())
return ;
char * buf = new char [ str . size () * 2 + 1 ];
2011-06-30 14:52:44 +02:00
EscapeString ( buf , str . c_str (), str . size ());
2010-08-18 02:25:52 +02:00
str = buf ;
delete [] buf ;
}
2010-12-23 16:05:43 +01:00
//! Keeps all our MySQL connections alive, prevent the server from disconnecting us.
2010-09-25 01:05:24 +02:00
void KeepAlive ()
{
2010-12-13 09:18:49 +01:00
/// Ping synchronous connections
2010-12-13 16:13:32 +01:00
for ( uint8 i = 0 ; i < m_connectionCount [ IDX_SYNCH ]; ++ i )
2010-10-31 10:55:29 +01:00
{
2010-12-13 09:18:49 +01:00
T * t = m_connections [ IDX_SYNCH ][ i ];
2010-10-31 10:55:29 +01:00
if ( t -> LockIfReady ())
{
t -> Ping ();
t -> Unlock ();
}
}
2010-12-13 22:37:56 +01:00
2010-12-13 09:18:49 +01:00
/// Assuming all worker threads are free, every worker thread will receive 1 ping operation request
/// If one or more worker threads are busy, the ping operations will not be split evenly, but this doesn't matter
/// as the sole purpose is to prevent connections from idling.
for ( size_t i = 0 ; i < m_connections [ IDX_ASYNC ]. size (); ++ i )
Enqueue ( new PingOperation );
2010-09-25 22:03:57 +02:00
}
2010-09-25 01:05:24 +02:00
2010-09-03 10:52:32 +02:00
private :
2011-06-30 14:52:44 +02:00
unsigned long EscapeString ( char * to , const char * from , unsigned long length )
2010-08-18 02:25:52 +02:00
{
if ( ! to || ! from || ! length )
return 0 ;
2010-12-13 22:37:56 +01:00
2011-06-22 15:04:13 +02:00
return mysql_real_escape_string ( m_connections [ IDX_SYNCH ][ 0 ] -> GetHandle (), to , from , length );
2010-08-18 02:25:52 +02:00
}
2010-09-12 01:40:27 +02:00
2010-08-18 02:25:52 +02:00
void Enqueue ( SQLOperation * op )
{
m_queue -> enqueue ( op );
}
2010-12-13 09:18:49 +01:00
T * GetFreeConnection ()
{
uint8 i = 0 ;
2010-12-13 16:13:32 +01:00
size_t num_cons = m_connectionCount [ IDX_SYNCH ];
2010-12-13 09:18:49 +01:00
for (;;) /// Block forever until a connection is free
{
T * t = m_connections [ IDX_SYNCH ][ ++ i % num_cons ];
if ( t -> LockIfReady ()) /// Must be matched with t->Unlock() or you will get deadlocks
return t ;
}
2010-12-04 21:50:36 +01:00
2010-12-13 09:18:49 +01:00
// This will be called when Celine Dion learns to sing
return NULL ;
}
private :
enum
{
IDX_ASYNC ,
IDX_SYNCH ,
IDX_SIZE ,
};
ACE_Activation_Queue * m_queue ; //! Queue shared by async worker threads.
std :: vector < std :: vector < T *> > m_connections ;
2010-12-13 16:13:32 +01:00
uint32 m_connectionCount [ 2 ]; //! Counter of MySQL connections;
2010-09-29 15:29:57 +02:00
MySQLConnectionInfo m_connectionInfo ;
2010-08-18 02:25:52 +02:00
};
2010-08-18 07:17:04 +02:00
#endif