Files
TCPlayerbotCore/src/server/database/Database/DatabaseWorkerPool.h
T

301 lines
11 KiB
C++
Raw Normal View History

2010-10-07 15:54:07 +02:00
/*
2017-01-01 16:21:30 +01:00
* Copyright (C) 2008-2017 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
2010-09-03 00:04:14 +02:00
#include "Common.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"
#include "Log.h"
2010-09-11 21:10:54 +02:00
#include "QueryResult.h"
#include "QueryHolder.h"
#include "AdhocStatement.h"
#include "StringFormat.h"
2010-08-18 02:25:52 +02:00
2015-02-04 19:44:34 +00:00
#include <mysqld_error.h>
#include <memory>
#include <array>
2015-02-04 19:44:34 +00:00
class QueryCallback;
2010-09-25 01:05:24 +02:00
class PingOperation : public SQLOperation
{
//! Operation for idle delaythreads
2014-08-09 20:17:40 +01:00
bool Execute() override
2010-09-25 01:05:24 +02:00
{
m_conn->Ping();
return true;
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
{
private:
enum InternalIndex
{
IDX_ASYNC,
IDX_SYNCH,
IDX_SIZE
};
2010-08-18 02:25:52 +02:00
public:
/* Activity state */
DatabaseWorkerPool();
2010-09-02 17:47:50 +02:00
~DatabaseWorkerPool()
{
_queue->Cancel();
}
void SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads);
2010-12-04 21:50:36 +01:00
uint32 Open();
2010-09-02 17:47:50 +02:00
void Close();
2010-09-02 17:47:50 +02:00
//! Prepares all prepared statements
bool PrepareStatements();
inline MySQLConnectionInfo const* GetConnectionInfo() const
{
return _connectionInfo.get();
}
/**
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 (Trinity::IsFormatEmptyOrNull(sql))
2010-09-02 17:47:50 +02:00
return;
BasicStatementTask* task = new BasicStatementTask(sql);
Enqueue(task);
}
//! 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.
template<typename Format, typename... Args>
void PExecute(Format&& sql, Args&&... args)
2010-09-02 17:47:50 +02:00
{
if (Trinity::IsFormatEmptyOrNull(sql))
2010-09-02 17:47:50 +02:00
return;
Execute(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str());
2010-09-02 17:47:50 +02: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.
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.
*/
//! 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)
{
2016-04-22 13:45:23 +02:00
if (Trinity::IsFormatEmptyOrNull(sql))
2010-09-27 00:20:56 +02:00
return;
T* connection = GetFreeConnection();
connection->Execute(sql);
connection->Unlock();
2010-09-02 17:47:50 +02: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.
template<typename Format, typename... Args>
void DirectPExecute(Format&& sql, Args&&... args)
2010-09-02 17:47:50 +02:00
{
if (Trinity::IsFormatEmptyOrNull(sql))
2010-09-02 17:47:50 +02:00
return;
DirectExecute(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str());
2010-09-02 17:47:50 +02: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.
void DirectExecute(PreparedStatement* stmt)
{
T* connection = GetFreeConnection();
connection->Execute(stmt);
connection->Unlock();
//! Delete proxy-class. Not needed anymore
delete stmt;
}
/**
2011-12-19 11:11:25 +01:00
Synchronous query (with resultset) methods.
*/
//! 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.
QueryResult Query(const char* sql, T* connection = nullptr);
2010-09-02 17:47:50 +02: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.
template<typename Format, typename... Args>
QueryResult PQuery(Format&& sql, T* conn, Args&&... args)
2010-09-27 00:20:56 +02:00
{
if (Trinity::IsFormatEmptyOrNull(sql))
return QueryResult(nullptr);
2010-09-27 00:20:56 +02:00
return Query(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str(), conn);
2010-09-27 00:20:56 +02: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.
template<typename Format, typename... Args>
QueryResult PQuery(Format&& sql, Args&&... args)
2010-09-02 17:47:50 +02:00
{
2016-04-22 13:45:23 +02:00
if (Trinity::IsFormatEmptyOrNull(sql))
return QueryResult(nullptr);
2010-09-02 17:47:50 +02:00
return Query(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str());
2010-09-02 17:47:50 +02: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.
PreparedQueryResult Query(PreparedStatement* stmt);
/**
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.
QueryCallback AsyncQuery(const char* sql);
2010-09-02 17:47:50 +02: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.
QueryCallback AsyncQuery(PreparedStatement* stmt);
//! 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.
QueryResultHolderFuture DelayQueryHolder(SQLQueryHolder* holder);
2010-09-12 01:40:27 +02: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);
}
//! 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.
void CommitTransaction(SQLTransaction 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);
2011-01-13 20:07:09 +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)
{
2014-07-01 00:54:09 +02:00
if (!trans)
Execute(stmt);
else
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)
{
2014-07-01 00:54:09 +02:00
if (!trans)
2010-12-13 17:05:01 +01:00
Execute(sql);
else
trans->Append(sql);
}
/**
Other
*/
typedef typename T::Statements PreparedStatementIndex;
//! Automanaged (internally) pointer to a prepared statement object for usage in upper level code.
//! Pointer is deleted in this->DirectExecute(PreparedStatement*), this->Query(PreparedStatement*) or PreparedStatementTask::~PreparedStatementTask.
//! This object is not tied to the prepared statement on the MySQL context yet until execution.
PreparedStatement* GetPreparedStatement(PreparedStatementIndex index)
2010-09-02 20:54:43 +02:00
{
return new PreparedStatement(index);
}
//! Apply escape string'ing for current collation. (utf8)
void EscapeString(std::string& str);
2010-08-18 02:25:52 +02:00
//! Keeps all our MySQL connections alive, prevent the server from disconnecting us.
void KeepAlive();
2010-09-25 01:05:24 +02:00
2010-09-03 10:52:32 +02:00
private:
uint32 OpenConnections(InternalIndex type, uint8 numConnections);
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;
return mysql_real_escape_string(
_connections[IDX_SYNCH].front()->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)
{
_queue->Push(op);
2010-08-18 02:25:52 +02:00
}
//! Gets a free connection in the synchronous connection pool.
//! Caller MUST call t->Unlock() after touching the MySQL context to prevent deadlocks.
T* GetFreeConnection();
2010-12-13 09:18:49 +01:00
char const* GetDatabaseName() const
{
2014-04-20 16:48:35 +02:00
return _connectionInfo->database.c_str();
}
//! Queue shared by async worker threads.
std::unique_ptr<ProducerConsumerQueue<SQLOperation*>> _queue;
std::array<std::vector<std::unique_ptr<T>>, IDX_SIZE> _connections;
std::unique_ptr<MySQLConnectionInfo> _connectionInfo;
uint8 _async_threads, _synch_threads;
2010-08-18 02:25:52 +02:00
};
#endif