AzerothCore 3.3.5a
OpenSource WoW Emulator
Loading...
Searching...
No Matches
DatabaseWorkerPool< T > Class Template Reference

#include "DatabaseWorkerPool.h"

Public Types

typedef T::Statements PreparedStatementIndex
 

Public Member Functions

 DatabaseWorkerPool ()
 
 ~DatabaseWorkerPool ()
 
void SetConnectionInfo (std::string_view infoString, uint8 const asyncThreads, uint8 const synchThreads)
 
uint32 Open ()
 
void Close ()
 
bool PrepareStatements ()
 Prepares all prepared statements.
 
MySQLConnectionInfo const * GetConnectionInfo () const
 
void Execute (std::string_view sql)
 
template<typename... Args>
void Execute (std::string_view sql, Args &&... args)
 
void Execute (PreparedStatement< T > *stmt)
 
void DirectExecute (std::string_view sql)
 
template<typename... Args>
void DirectExecute (std::string_view sql, Args &&... args)
 
void DirectExecute (PreparedStatement< T > *stmt)
 
QueryResult Query (std::string_view sql)
 
template<typename... Args>
QueryResult Query (std::string_view sql, Args &&... args)
 
PreparedQueryResult Query (PreparedStatement< T > *stmt)
 
QueryCallback AsyncQuery (std::string_view sql)
 
QueryCallback AsyncQuery (PreparedStatement< T > *stmt)
 
SQLQueryHolderCallback DelayQueryHolder (std::shared_ptr< SQLQueryHolder< T > > holder)
 
SQLTransaction< T > BeginTransaction ()
 Begins an automanaged transaction pointer that will automatically rollback if not commited. (Autocommit=0)
 
void CommitTransaction (SQLTransaction< T > transaction)
 
TransactionCallback AsyncCommitTransaction (SQLTransaction< T > transaction)
 
void DirectCommitTransaction (SQLTransaction< T > &transaction)
 
void ExecuteOrAppend (SQLTransaction< T > &trans, std::string_view sql)
 
void ExecuteOrAppend (SQLTransaction< T > &trans, PreparedStatement< T > *stmt)
 
PreparedStatement< T > * GetPreparedStatement (PreparedStatementIndex index)
 
void EscapeString (std::string &str)
 Apply escape string'ing for current collation. (utf8)
 
void KeepAlive ()
 Keeps all our MySQL connections alive, prevent the server from disconnecting us.
 
void WarnAboutSyncQueries (bool warn)
 
std::size_t QueueSize () const
 

Private Types

enum  InternalIndex {
  IDX_ASYNC ,
  IDX_SYNCH ,
  IDX_SIZE
}
 

Private Member Functions

uint32 OpenConnections (InternalIndex type, uint8 numConnections)
 
unsigned long EscapeString (char *to, char const *from, unsigned long length)
 
void Enqueue (SQLOperation *op)
 
T * GetFreeConnection ()
 
std::string_view GetDatabaseName () const
 

Private Attributes

std::unique_ptr< ProducerConsumerQueue< SQLOperation * > > _queue
 Queue shared by async worker threads.
 
std::array< std::vector< std::unique_ptr< T > >, IDX_SIZE > _connections
 
std::unique_ptr< MySQLConnectionInfo > _connectionInfo
 
std::vector< uint8 > _preparedStatementSize
 
uint8 _async_threads
 
uint8 _synch_threads
 

Detailed Description

template<class T>
class DatabaseWorkerPool< T >

Member Typedef Documentation

◆ PreparedStatementIndex

template<class T >
typedef T::Statements DatabaseWorkerPool< T >::PreparedStatementIndex

Other

Member Enumeration Documentation

◆ InternalIndex

template<class T >
enum DatabaseWorkerPool::InternalIndex
private
Enumerator
IDX_ASYNC 
IDX_SYNCH 
IDX_SIZE 
52 {
56 };
@ IDX_ASYNC
Definition DatabaseWorkerPool.h:53
@ IDX_SIZE
Definition DatabaseWorkerPool.h:55
@ IDX_SYNCH
Definition DatabaseWorkerPool.h:54

Constructor & Destructor Documentation

◆ DatabaseWorkerPool()

template<class T >
DatabaseWorkerPool< T >::DatabaseWorkerPool ( )
45 :
49{
50 WPFatal(mysql_thread_safe(), "Used MySQL library isn't thread-safe.");
51
52 bool isSupportClientDB = mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION;
53 bool isSameClientDB = mysql_get_client_version() == MYSQL_VERSION_ID;
54
55 WPFatal(isSupportClientDB, "AzerothCore does not support MySQL versions below 8.0\n\nFound version: {} / {}. Server compiled with: {}.\nSearch the wiki for ACE00043 in Common Errors (https://www.azerothcore.org/wiki/common-errors#ace00043).",
56 mysql_get_client_info(), mysql_get_client_version(), MYSQL_VERSION_ID);
57 WPFatal(isSameClientDB, "Used MySQL library version ({} id {}) does not match the version id used to compile AzerothCore (id {}).\nSearch the wiki for ACE00046 in Common Errors (https://www.azerothcore.org/wiki/common-errors#ace00046).",
58 mysql_get_client_info(), mysql_get_client_version(), MYSQL_VERSION_ID);
59}
#define MIN_MYSQL_CLIENT_VERSION
Definition DatabaseWorkerPool.h:33
#define WPFatal(cond,...)
Definition Errors.h:59
uint8 _synch_threads
Definition DatabaseWorkerPool.h:236
uint8 _async_threads
Definition DatabaseWorkerPool.h:236
std::unique_ptr< ProducerConsumerQueue< SQLOperation * > > _queue
Queue shared by async worker threads.
Definition DatabaseWorkerPool.h:232
Definition PCQueue.h:28

References MIN_MYSQL_CLIENT_VERSION, and WPFatal.

◆ ~DatabaseWorkerPool()

template<class T >
DatabaseWorkerPool< T >::~DatabaseWorkerPool ( )
63{
64 _queue->Cancel();
65}

Member Function Documentation

◆ AsyncCommitTransaction()

template<class T >
TransactionCallback DatabaseWorkerPool< T >::AsyncCommitTransaction ( SQLTransaction< T >  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.

272{
273#ifdef ACORE_DEBUG
277 switch (transaction->GetSize())
278 {
279 case 0:
280 LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing.");
281 break;
282 case 1:
283 LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code.");
284 break;
285 default:
286 break;
287 }
288#endif // ACORE_DEBUG
289
291 TransactionFuture result = task->GetFuture();
292 Enqueue(task);
293 return TransactionCallback(std::move(result));
294}
std::future< bool > TransactionFuture
Definition DatabaseEnvFwd.h:58
#define LOG_DEBUG(filterType__,...)
Definition Log.h:157
void Enqueue(SQLOperation *op)
Definition DatabaseWorkerPool.cpp:464
Definition Transaction.h:110
Definition Transaction.h:97
TransactionFuture GetFuture()
Definition Transaction.h:101

References TransactionWithResultTask::GetFuture(), and LOG_DEBUG.

◆ AsyncQuery() [1/2]

template<class T >
QueryCallback DatabaseWorkerPool< T >::AsyncQuery ( PreparedStatement< T > *  stmt)

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. Statement must be prepared with CONNECTION_ASYNC flag.

223{
224 PreparedStatementTask* task = new PreparedStatementTask(stmt, true);
225 // Store future result before enqueueing - task might get already processed and deleted before returning from this method
226 PreparedQueryResultFuture result = task->GetFuture();
227 Enqueue(task);
228 return QueryCallback(std::move(result));
229}
std::future< PreparedQueryResult > PreparedQueryResultFuture
Definition DatabaseEnvFwd.h:46
Definition PreparedStatement.h:170
PreparedQueryResultFuture GetFuture()
Definition PreparedStatement.h:176
Definition QueryCallback.h:29

References PreparedStatementTask::GetFuture().

◆ AsyncQuery() [2/2]

template<class T >
QueryCallback DatabaseWorkerPool< T >::AsyncQuery ( std::string_view  sql)

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.

213{
214 BasicStatementTask* task = new BasicStatementTask(sql, true);
215 // Store future result before enqueueing - task might get already processed and deleted before returning from this method
216 QueryResultFuture result = task->GetFuture();
217 Enqueue(task);
218 return QueryCallback(std::move(result));
219}
std::future< QueryResult > QueryResultFuture
Definition DatabaseEnvFwd.h:28
Definition AdhocStatement.h:27
QueryResultFuture GetFuture() const
Definition AdhocStatement.h:33

References BasicStatementTask::GetFuture().

◆ BeginTransaction()

template<class T >
SQLTransaction< T > DatabaseWorkerPool< T >::BeginTransaction ( )

Begins an automanaged transaction pointer that will automatically rollback if not commited. (Autocommit=0)

Transaction context methods.

243{
244 return std::make_shared<Transaction<T>>();
245}

◆ Close()

template<class T >
void DatabaseWorkerPool< T >::Close ( )

Closes the actualy MySQL connection.

Shut down the synchronous connections There's no need for locking the connection, because DatabaseWorkerPool<>::Close should only be called after any other thread tasks in the core have exited, meaning there can be no concurrent access at this point.

109{
110 LOG_INFO("sql.driver", "Closing down DatabasePool '{}'. Waiting for {} queries to finish...", GetDatabaseName(), _queue->Size());
111
112 // Gracefully close async query queue, worker threads will block when the destructor
113 // is called from the .clear() functions below until the queue is empty
114 _queue->Shutdown();
115
117 _connections[IDX_ASYNC].clear();
118
119 LOG_INFO("sql.driver", "Asynchronous connections on DatabasePool '{}' terminated. Proceeding with synchronous connections.",
121
126 _connections[IDX_SYNCH].clear();
127
128 LOG_INFO("sql.driver", "All connections on DatabasePool '{}' closed.", GetDatabaseName());
129}
#define LOG_INFO(filterType__,...)
Definition Log.h:153
std::array< std::vector< std::unique_ptr< T > >, IDX_SIZE > _connections
Definition DatabaseWorkerPool.h:233
std::string_view GetDatabaseName() const
Definition DatabaseWorkerPool.cpp:504

References LOG_INFO.

Referenced by DatabaseLoader::AddDatabase().

◆ CommitTransaction()

template<class T >
void DatabaseWorkerPool< T >::CommitTransaction ( SQLTransaction< T >  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.

249{
250#ifdef ACORE_DEBUG
254 switch (transaction->GetSize())
255 {
256 case 0:
257 LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing.");
258 return;
259 case 1:
260 LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code.");
261 break;
262 default:
263 break;
264 }
265#endif // ACORE_DEBUG
266
267 Enqueue(new TransactionTask(transaction));
268}
Definition Transaction.h:76

References LOG_DEBUG.

◆ DelayQueryHolder()

template<class T >
SQLQueryHolderCallback DatabaseWorkerPool< T >::DelayQueryHolder ( std::shared_ptr< SQLQueryHolder< T > >  holder)

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. Any prepared statements added to this holder need to be prepared with the CONNECTION_ASYNC flag.

233{
234 SQLQueryHolderTask* task = new SQLQueryHolderTask(holder);
235 // Store future result before enqueueing - task might get already processed and deleted before returning from this method
236 QueryResultHolderFuture result = task->GetFuture();
237 Enqueue(task);
238 return { std::move(holder), std::move(result) };
239}
std::future< void > QueryResultHolderFuture
Definition DatabaseEnvFwd.h:74
Definition QueryHolder.h:53
QueryResultHolderFuture GetFuture()
Definition QueryHolder.h:61

References SQLQueryHolderTask::GetFuture().

◆ DirectCommitTransaction()

template<class T >
void DatabaseWorkerPool< T >::DirectCommitTransaction ( SQLTransaction< T > &  transaction)

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.

Handle MySQL Errno 1213 without extending deadlock to the core itself

Todo:
More elegant way

Clean up now.

298{
299 T* connection = GetFreeConnection();
300 int errorCode = connection->ExecuteTransaction(transaction);
301
302 if (!errorCode)
303 {
304 connection->Unlock(); // OK, operation succesful
305 return;
306 }
307
310 if (errorCode == ER_LOCK_DEADLOCK)
311 {
312 //todo: handle multiple sync threads deadlocking in a similar way as async threads
313 uint8 loopBreaker = 5;
314
315 for (uint8 i = 0; i < loopBreaker; ++i)
316 {
317 if (!connection->ExecuteTransaction(transaction))
318 break;
319 }
320 }
321
323 transaction->Cleanup();
324
325 connection->Unlock();
326}
std::uint8_t uint8
Definition Define.h:109
T * GetFreeConnection()
Definition DatabaseWorkerPool.cpp:476

◆ DirectExecute() [1/3]

template<class T >
void DatabaseWorkerPool< T >::DirectExecute ( PreparedStatement< T > *  stmt)

Directly executes a one-way SQL operation in prepared statement format, that will block the calling thread until finished. Statement must be prepared with the CONNECTION_SYNCH flag.

Delete proxy-class. Not needed anymore

539{
540 T* connection = GetFreeConnection();
541 connection->Execute(stmt);
542 connection->Unlock();
543
545 delete stmt;
546}

◆ DirectExecute() [2/3]

template<class T >
void DatabaseWorkerPool< T >::DirectExecute ( std::string_view  sql)

Direct synchronous one-way statement methods. Directly executes a one-way SQL operation in string format, that will block the calling thread until finished. This method should only be used for queries that are only executed once, e.g during startup.

528{
529 if (sql.empty())
530 return;
531
532 T* connection = GetFreeConnection();
533 connection->Execute(sql);
534 connection->Unlock();
535}

Referenced by DatabaseWorkerPool< T >::DirectExecute().

◆ DirectExecute() [3/3]

template<class T >
template<typename... Args>
void DatabaseWorkerPool< T >::DirectExecute ( std::string_view  sql,
Args &&...  args 
)
inline

Directly executes a one-way SQL operation in string format -with variable args-, that will block the calling thread until finished. This method should only be used for queries that are only executed once, e.g during startup.

111 {
112 if (sql.empty())
113 return;
114
115 DirectExecute(Acore::StringFormat(sql, std::forward<Args>(args)...));
116 }
void DirectExecute(std::string_view sql)
Definition DatabaseWorkerPool.cpp:527
std::string StringFormat(FormatStringView fmt, Args &&... args)
Default AC string format function.
Definition StringFormat.h:44

References DatabaseWorkerPool< T >::DirectExecute(), and Acore::StringFormat().

◆ Enqueue()

template<class T >
void DatabaseWorkerPool< T >::Enqueue ( SQLOperation *  op)
private
465{
466 _queue->Push(op);
467}

◆ EscapeString() [1/2]

template<class T >
unsigned long DatabaseWorkerPool< T >::EscapeString ( char *  to,
char const *  from,
unsigned long  length 
)
private
456{
457 if (!to || !from || !length)
458 return 0;
459
460 return _connections[IDX_SYNCH].front()->EscapeString(to, from, length);
461}

◆ EscapeString() [2/2]

template<class T >
void DatabaseWorkerPool< T >::EscapeString ( std::string &  str)

Apply escape string'ing for current collation. (utf8)

336{
337 if (str.empty())
338 return;
339
340 char* buf = new char[str.size() * 2 + 1];
341 EscapeString(buf, str.c_str(), uint32(str.size()));
342 str = buf;
343 delete[] buf;
344}
std::uint32_t uint32
Definition Define.h:107
void EscapeString(std::string &str)
Apply escape string'ing for current collation. (utf8)
Definition DatabaseWorkerPool.cpp:335

◆ Execute() [1/3]

template<class T >
void DatabaseWorkerPool< T >::Execute ( PreparedStatement< T > *  stmt)

Enqueues a one-way SQL operation in prepared statement format that will be executed asynchronously. Statement must be prepared with CONNECTION_ASYNC flag.

521{
523 Enqueue(task);
524}

◆ Execute() [2/3]

template<class T >
void DatabaseWorkerPool< T >::Execute ( std::string_view  sql)

Delayed one-way statement methods. Enqueues a one-way SQL operation in string format that will be executed asynchronously. This method should only be used for queries that are only executed once, e.g during startup.

511{
512 if (sql.empty())
513 return;
514
515 BasicStatementTask* task = new BasicStatementTask(sql);
516 Enqueue(task);
517}

Referenced by DatabaseWorkerPool< T >::Execute().

◆ Execute() [3/3]

template<class T >
template<typename... Args>
void DatabaseWorkerPool< T >::Execute ( std::string_view  sql,
Args &&...  args 
)
inline

Enqueues a one-way SQL operation in string format -with variable args- that will be executed asynchronously. This method should only be used for queries that are only executed once, e.g during startup.

88 {
89 if (sql.empty())
90 return;
91
92 Execute(Acore::StringFormat(sql, std::forward<Args>(args)...));
93 }
void Execute(std::string_view sql)
Definition DatabaseWorkerPool.cpp:510

References DatabaseWorkerPool< T >::Execute(), and Acore::StringFormat().

◆ ExecuteOrAppend() [1/2]

template<class T >
void DatabaseWorkerPool< T >::ExecuteOrAppend ( SQLTransaction< T > &  trans,
PreparedStatement< T > *  stmt 
)

Method used to execute prepared statements in a diverse context. Will be wrapped in a transaction if valid object is present, otherwise executed standalone.

559{
560 if (!trans)
561 Execute(stmt);
562 else
563 trans->Append(stmt);
564}

◆ ExecuteOrAppend() [2/2]

template<class T >
void DatabaseWorkerPool< T >::ExecuteOrAppend ( SQLTransaction< T > &  trans,
std::string_view  sql 
)

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.

550{
551 if (!trans)
552 Execute(sql);
553 else
554 trans->Append(sql);
555}

◆ GetConnectionInfo()

template<class T >
MySQLConnectionInfo const * DatabaseWorkerPool< T >::GetConnectionInfo ( ) const
inline
72 {
73 return _connectionInfo.get();
74 }
std::unique_ptr< MySQLConnectionInfo > _connectionInfo
Definition DatabaseWorkerPool.h:234

References DatabaseWorkerPool< T >::_connectionInfo.

◆ GetDatabaseName()

template<class T >
std::string_view DatabaseWorkerPool< T >::GetDatabaseName ( ) const
private
505{
506 return std::string_view{ _connectionInfo->database };
507}

◆ GetFreeConnection()

template<class T >
T * DatabaseWorkerPool< T >::GetFreeConnection ( )
private

Gets a free connection in the synchronous connection pool. Caller MUST call t->Unlock() after touching the MySQL context to prevent deadlocks.

Block forever until a connection is free

Must be matched with t->Unlock() or you will get deadlocks

477{
478#ifdef ACORE_DEBUG
479 if (_warnSyncQueries)
480 {
481 std::ostringstream ss;
482 ss << boost::stacktrace::stacktrace();
483 LOG_WARN("sql.performances", "Sync query at:\n{}", ss.str());
484 }
485#endif
486
487 uint8 i = 0;
488 auto const num_cons = _connections[IDX_SYNCH].size();
489 T* connection = nullptr;
490
492 for (;;)
493 {
494 connection = _connections[IDX_SYNCH][++i % num_cons].get();
496 if (connection->LockIfReady())
497 break;
498 }
499
500 return connection;
501}
#define LOG_WARN(filterType__,...)
Definition Log.h:149

References LOG_WARN.

◆ GetPreparedStatement()

template<class T >
PreparedStatement< T > * DatabaseWorkerPool< T >::GetPreparedStatement ( PreparedStatementIndex  index)

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.

330{
331 return new PreparedStatement<T>(index, _preparedStatementSize[index]);
332}
std::vector< uint8 > _preparedStatementSize
Definition DatabaseWorkerPool.h:235
Definition PreparedStatement.h:157

◆ KeepAlive()

template<class T >
void DatabaseWorkerPool< T >::KeepAlive ( )

Keeps all our MySQL connections alive, prevent the server from disconnecting us.

Ping synchronous connections

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.

348{
350 for (auto& connection : _connections[IDX_SYNCH])
351 {
352 if (connection->LockIfReady())
353 {
354 connection->Ping();
355 connection->Unlock();
356 }
357 }
358
362 auto const count = _connections[IDX_ASYNC].size();
363
364 for (uint8 i = 0; i < count; ++i)
366}
Definition SQLOperation.h:65

◆ Open()

template<class T >
uint32 DatabaseWorkerPool< T >::Open ( )
78{
79 WPFatal(_connectionInfo.get(), "Connection info was not set!");
80
81 LOG_INFO("sql.driver", "Opening DatabasePool '{}'. Asynchronous connections: {}, synchronous connections: {}.",
83
84 _queue->Cancel();
85 _connections[IDX_ASYNC].clear();
86 _connections[IDX_SYNCH].clear();
87 _queue->Reset();
88
90
91 if (error)
92 return error;
93
95
96 if (!error)
97 {
98 LOG_INFO("sql.driver", "DatabasePool '{}' opened successfully. {} total connections running.",
100 }
101
102 LOG_INFO("sql.driver", " ");
103
104 return error;
105}
uint32 OpenConnections(InternalIndex type, uint8 numConnections)
Definition DatabaseWorkerPool.cpp:413

References LOG_INFO, and WPFatal.

Referenced by DatabaseLoader::AddDatabase().

◆ OpenConnections()

template<class T >
uint32 DatabaseWorkerPool< T >::OpenConnections ( InternalIndex  type,
uint8  numConnections 
)
private
414{
415 for (uint8 i = 0; i < numConnections; ++i)
416 {
417 // Create the connection
418 auto connection = [&]
419 {
420 switch (type)
421 {
422 case IDX_ASYNC:
423 return std::make_unique<T>(_queue.get(), *_connectionInfo);
424 case IDX_SYNCH:
425 return std::make_unique<T>(*_connectionInfo);
426 default:
427 ABORT();
428 }
429 }();
430
431 if (uint32 error = connection->Open())
432 {
433 // Failed to open a connection or invalid version, abort and cleanup
434 _queue->Cancel();
435 _connections[type].clear();
436 return error;
437 }
438 else if (DatabaseIncompatibleVersion(connection->GetServerInfo()))
439 {
440 LOG_ERROR("sql.driver", "AzerothCore does not support MySQL versions below 8.0\n\nFound server version: {}. Server compiled with: {}.",
441 connection->GetServerInfo(), MYSQL_VERSION_ID);
442 return 1;
443 }
444 else
445 {
446 _connections[type].push_back(std::move(connection));
447 }
448 }
449
450 // Everything is fine
451 return 0;
452}
bool DatabaseIncompatibleVersion(std::string const mysqlVersion)
Returns true if the version string given is incompatible.
Definition DatabaseWorkerPool.cpp:382
#define ABORT
Definition Errors.h:76
#define LOG_ERROR(filterType__,...)
Definition Log.h:145

References ABORT, DatabaseIncompatibleVersion(), and LOG_ERROR.

◆ PrepareStatements()

template<class T >
bool DatabaseWorkerPool< T >::PrepareStatements ( )

Prepares all prepared statements.

133{
134 for (auto const& connections : _connections)
135 {
136 for (auto const& connection : connections)
137 {
138 connection->LockIfReady();
139 if (!connection->PrepareStatements())
140 {
141 connection->Unlock();
142 Close();
143 return false;
144 }
145 else
146 connection->Unlock();
147
148 std::size_t const preparedSize = connection->m_stmts.size();
149 if (_preparedStatementSize.size() < preparedSize)
150 _preparedStatementSize.resize(preparedSize);
151
152 for (std::size_t i = 0; i < preparedSize; ++i)
153 {
154 // already set by another connection
155 // (each connection only has prepared statements of it's own type sync/async)
156 if (_preparedStatementSize[i] > 0)
157 continue;
158
159 if (MySQLPreparedStatement* stmt = connection->m_stmts[i].get())
160 {
161 uint32 const paramCount = stmt->GetParameterCount();
162
163 // WH only supports uint8 indices.
164 ASSERT(paramCount < std::numeric_limits<uint8>::max());
165
166 _preparedStatementSize[i] = static_cast<uint8>(paramCount);
167 }
168 }
169 }
170 }
171
172 return true;
173}
#define ASSERT
Definition Errors.h:68
void Close()
Definition DatabaseWorkerPool.cpp:108
Definition MySQLPreparedStatement.h:34

References ASSERT, and Close.

Referenced by DatabaseLoader::AddDatabase().

◆ Query() [1/3]

template<class T >
PreparedQueryResult DatabaseWorkerPool< T >::Query ( PreparedStatement< T > *  stmt)

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. Statement must be prepared with CONNECTION_SYNCH flag.

Delete proxy-class. Not needed anymore

194{
195 auto connection = GetFreeConnection();
196 PreparedResultSet* ret = connection->Query(stmt);
197 connection->Unlock();
198
200 delete stmt;
201
202 if (!ret || !ret->GetRowCount())
203 {
204 delete ret;
205 return PreparedQueryResult(nullptr);
206 }
207
208 return PreparedQueryResult(ret);
209}
std::shared_ptr< PreparedResultSet > PreparedQueryResult
Definition DatabaseEnvFwd.h:45
Definition QueryResult.h:99
uint64 GetRowCount() const
Definition QueryResult.h:105

References PreparedResultSet::GetRowCount().

◆ Query() [2/3]

template<class T >
QueryResult DatabaseWorkerPool< T >::Query ( std::string_view  sql)

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.

177{
178 auto connection = GetFreeConnection();
179
180 ResultSet* result = connection->Query(sql);
181 connection->Unlock();
182
183 if (!result || !result->GetRowCount() || !result->NextRow())
184 {
185 delete result;
186 return QueryResult(nullptr);
187 }
188
189 return QueryResult(result);
190}
std::shared_ptr< ResultSet > QueryResult
Definition DatabaseEnvFwd.h:27
Definition QueryResult.h:49
uint64 GetRowCount() const
Definition QueryResult.h:55
bool NextRow()
Definition QueryResult.cpp:188

References ResultSet::GetRowCount(), and ResultSet::NextRow().

Referenced by DatabaseWorkerPool< T >::Query().

◆ Query() [3/3]

template<class T >
template<typename... Args>
QueryResult DatabaseWorkerPool< T >::Query ( std::string_view  sql,
Args &&...  args 
)
inline

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.

134 {
135 if (sql.empty())
136 return QueryResult(nullptr);
137
138 return Query(Acore::StringFormat(sql, std::forward<Args>(args)...));
139 }
QueryResult Query(std::string_view sql)
Definition DatabaseWorkerPool.cpp:176

References DatabaseWorkerPool< T >::Query(), and Acore::StringFormat().

◆ QueueSize()

template<class T >
std::size_t DatabaseWorkerPool< T >::QueueSize ( ) const
471{
472 return _queue->Size();
473}

◆ SetConnectionInfo()

template<class T >
void DatabaseWorkerPool< T >::SetConnectionInfo ( std::string_view  infoString,
uint8 const  asyncThreads,
uint8 const  synchThreads 
)
69{
70 _connectionInfo = std::make_unique<MySQLConnectionInfo>(infoString);
71
72 _async_threads = asyncThreads;
73 _synch_threads = synchThreads;
74}

Referenced by DatabaseLoader::AddDatabase().

◆ WarnAboutSyncQueries()

template<class T >
void DatabaseWorkerPool< T >::WarnAboutSyncQueries ( bool  warn)
inline
210 {
211#ifdef ACORE_DEBUG
212 _warnSyncQueries = warn;
213#endif
214 }

Member Data Documentation

◆ _async_threads

template<class T >
uint8 DatabaseWorkerPool< T >::_async_threads
private

◆ _connectionInfo

template<class T >
std::unique_ptr<MySQLConnectionInfo> DatabaseWorkerPool< T >::_connectionInfo
private

◆ _connections

template<class T >
std::array<std::vector<std::unique_ptr<T> >, IDX_SIZE> DatabaseWorkerPool< T >::_connections
private

◆ _preparedStatementSize

template<class T >
std::vector<uint8> DatabaseWorkerPool< T >::_preparedStatementSize
private

◆ _queue

template<class T >
std::unique_ptr<ProducerConsumerQueue<SQLOperation*> > DatabaseWorkerPool< T >::_queue
private

Queue shared by async worker threads.

◆ _synch_threads

template<class T >
uint8 DatabaseWorkerPool< T >::_synch_threads
private

The documentation for this class was generated from the following files: