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 ( )
55 :
59{
60 WPFatal(mysql_thread_safe(), "Used MySQL library isn't thread-safe.");
61
62 bool isSupportClientDB = mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION;
63 bool isSameClientDB = mysql_get_client_version() == MYSQL_VERSION_ID;
64
65 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).",
66 mysql_get_client_info(), mysql_get_client_version(), MYSQL_VERSION_ID);
67 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).",
68 mysql_get_client_info(), mysql_get_client_version(), MYSQL_VERSION_ID);
69}
#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 ( )
73{
74 _queue->Cancel();
75}

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.

282{
283#ifdef ACORE_DEBUG
287 switch (transaction->GetSize())
288 {
289 case 0:
290 LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing.");
291 break;
292 case 1:
293 LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code.");
294 break;
295 default:
296 break;
297 }
298#endif // ACORE_DEBUG
299
301 TransactionFuture result = task->GetFuture();
302 Enqueue(task);
303 return TransactionCallback(std::move(result));
304}
std::future< bool > TransactionFuture
Definition DatabaseEnvFwd.h:58
#define LOG_DEBUG(filterType__,...)
Definition Log.h:157
void Enqueue(SQLOperation *op)
Definition DatabaseWorkerPool.cpp:474
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.

233{
234 PreparedStatementTask* task = new PreparedStatementTask(stmt, true);
235 // Store future result before enqueueing - task might get already processed and deleted before returning from this method
236 PreparedQueryResultFuture result = task->GetFuture();
237 Enqueue(task);
238 return QueryCallback(std::move(result));
239}
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.

223{
224 BasicStatementTask* task = new BasicStatementTask(sql, true);
225 // Store future result before enqueueing - task might get already processed and deleted before returning from this method
226 QueryResultFuture result = task->GetFuture();
227 Enqueue(task);
228 return QueryCallback(std::move(result));
229}
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.

253{
254 return std::make_shared<Transaction<T>>();
255}

◆ 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.

119{
120 LOG_INFO("sql.driver", "Closing down DatabasePool '{}'. Waiting for {} queries to finish...", GetDatabaseName(), _queue->Size());
121
122 // Gracefully close async query queue, worker threads will block when the destructor
123 // is called from the .clear() functions below until the queue is empty
124 _queue->Shutdown();
125
127 _connections[IDX_ASYNC].clear();
128
129 LOG_INFO("sql.driver", "Asynchronous connections on DatabasePool '{}' terminated. Proceeding with synchronous connections.",
131
136 _connections[IDX_SYNCH].clear();
137
138 LOG_INFO("sql.driver", "All connections on DatabasePool '{}' closed.", GetDatabaseName());
139}
#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:514

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.

259{
260#ifdef ACORE_DEBUG
264 switch (transaction->GetSize())
265 {
266 case 0:
267 LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing.");
268 return;
269 case 1:
270 LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code.");
271 break;
272 default:
273 break;
274 }
275#endif // ACORE_DEBUG
276
277 Enqueue(new TransactionTask(transaction));
278}
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.

243{
244 SQLQueryHolderTask* task = new SQLQueryHolderTask(holder);
245 // Store future result before enqueueing - task might get already processed and deleted before returning from this method
246 QueryResultHolderFuture result = task->GetFuture();
247 Enqueue(task);
248 return { std::move(holder), std::move(result) };
249}
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.

308{
309 T* connection = GetFreeConnection();
310 int errorCode = connection->ExecuteTransaction(transaction);
311
312 if (!errorCode)
313 {
314 connection->Unlock(); // OK, operation succesful
315 return;
316 }
317
320 if (errorCode == ER_LOCK_DEADLOCK)
321 {
322 //todo: handle multiple sync threads deadlocking in a similar way as async threads
323 uint8 loopBreaker = 5;
324
325 for (uint8 i = 0; i < loopBreaker; ++i)
326 {
327 if (!connection->ExecuteTransaction(transaction))
328 break;
329 }
330 }
331
333 transaction->Cleanup();
334
335 connection->Unlock();
336}
std::uint8_t uint8
Definition Define.h:109
T * GetFreeConnection()
Definition DatabaseWorkerPool.cpp:486

◆ 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

549{
550 T* connection = GetFreeConnection();
551 connection->Execute(stmt);
552 connection->Unlock();
553
555 delete stmt;
556}

◆ 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.

538{
539 if (sql.empty())
540 return;
541
542 T* connection = GetFreeConnection();
543 connection->Execute(sql);
544 connection->Unlock();
545}

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:537
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
475{
476 _queue->Push(op);
477}

◆ EscapeString() [1/2]

template<class T >
unsigned long DatabaseWorkerPool< T >::EscapeString ( char *  to,
char const *  from,
unsigned long  length 
)
private
466{
467 if (!to || !from || !length)
468 return 0;
469
470 return _connections[IDX_SYNCH].front()->EscapeString(to, from, length);
471}

◆ EscapeString() [2/2]

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

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

346{
347 if (str.empty())
348 return;
349
350 char* buf = new char[str.size() * 2 + 1];
351 EscapeString(buf, str.c_str(), uint32(str.size()));
352 str = buf;
353 delete[] buf;
354}
std::uint32_t uint32
Definition Define.h:107
void EscapeString(std::string &str)
Apply escape string'ing for current collation. (utf8)
Definition DatabaseWorkerPool.cpp:345

◆ 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.

531{
533 Enqueue(task);
534}

◆ 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.

521{
522 if (sql.empty())
523 return;
524
525 BasicStatementTask* task = new BasicStatementTask(sql);
526 Enqueue(task);
527}

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:520

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.

569{
570 if (!trans)
571 Execute(stmt);
572 else
573 trans->Append(stmt);
574}

◆ 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.

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

◆ 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
515{
516 return std::string_view{ _connectionInfo->database };
517}

◆ 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

487{
488#ifdef ACORE_DEBUG
489 if (_warnSyncQueries)
490 {
491 std::ostringstream ss;
492 ss << boost::stacktrace::stacktrace();
493 LOG_WARN("sql.performances", "Sync query at:\n{}", ss.str());
494 }
495#endif
496
497 uint8 i = 0;
498 auto const num_cons = _connections[IDX_SYNCH].size();
499 T* connection = nullptr;
500
502 for (;;)
503 {
504 connection = _connections[IDX_SYNCH][++i % num_cons].get();
506 if (connection->LockIfReady())
507 break;
508 }
509
510 return connection;
511}
#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.

340{
341 return new PreparedStatement<T>(index, _preparedStatementSize[index]);
342}
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.

358{
360 for (auto& connection : _connections[IDX_SYNCH])
361 {
362 if (connection->LockIfReady())
363 {
364 connection->Ping();
365 connection->Unlock();
366 }
367 }
368
372 auto const count = _connections[IDX_ASYNC].size();
373
374 for (uint8 i = 0; i < count; ++i)
376}
Definition DatabaseWorkerPool.cpp:45

◆ Open()

template<class T >
uint32 DatabaseWorkerPool< T >::Open ( )
88{
89 WPFatal(_connectionInfo.get(), "Connection info was not set!");
90
91 LOG_INFO("sql.driver", "Opening DatabasePool '{}'. Asynchronous connections: {}, synchronous connections: {}.",
93
94 _queue->Cancel();
95 _connections[IDX_ASYNC].clear();
96 _connections[IDX_SYNCH].clear();
97 _queue->Reset();
98
100
101 if (error)
102 return error;
103
105
106 if (!error)
107 {
108 LOG_INFO("sql.driver", "DatabasePool '{}' opened successfully. {} total connections running.",
110 }
111
112 LOG_INFO("sql.driver", " ");
113
114 return error;
115}
uint32 OpenConnections(InternalIndex type, uint8 numConnections)
Definition DatabaseWorkerPool.cpp:423

References LOG_INFO, and WPFatal.

Referenced by DatabaseLoader::AddDatabase().

◆ OpenConnections()

template<class T >
uint32 DatabaseWorkerPool< T >::OpenConnections ( InternalIndex  type,
uint8  numConnections 
)
private
424{
425 for (uint8 i = 0; i < numConnections; ++i)
426 {
427 // Create the connection
428 auto connection = [&]
429 {
430 switch (type)
431 {
432 case IDX_ASYNC:
433 return std::make_unique<T>(_queue.get(), *_connectionInfo);
434 case IDX_SYNCH:
435 return std::make_unique<T>(*_connectionInfo);
436 default:
437 ABORT();
438 }
439 }();
440
441 if (uint32 error = connection->Open())
442 {
443 // Failed to open a connection or invalid version, abort and cleanup
444 _queue->Cancel();
445 _connections[type].clear();
446 return error;
447 }
448 else if (DatabaseIncompatibleVersion(connection->GetServerInfo()))
449 {
450 LOG_ERROR("sql.driver", "AzerothCore does not support MySQL versions below 8.0\n\nFound server version: {}. Server compiled with: {}.",
451 connection->GetServerInfo(), MYSQL_VERSION_ID);
452 return 1;
453 }
454 else
455 {
456 _connections[type].push_back(std::move(connection));
457 }
458 }
459
460 // Everything is fine
461 return 0;
462}
bool DatabaseIncompatibleVersion(std::string const mysqlVersion)
Returns true if the version string given is incompatible.
Definition DatabaseWorkerPool.cpp:392
#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.

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

204{
205 auto connection = GetFreeConnection();
206 PreparedResultSet* ret = connection->Query(stmt);
207 connection->Unlock();
208
210 delete stmt;
211
212 if (!ret || !ret->GetRowCount())
213 {
214 delete ret;
215 return PreparedQueryResult(nullptr);
216 }
217
218 return PreparedQueryResult(ret);
219}
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.

187{
188 auto connection = GetFreeConnection();
189
190 ResultSet* result = connection->Query(sql);
191 connection->Unlock();
192
193 if (!result || !result->GetRowCount() || !result->NextRow())
194 {
195 delete result;
196 return QueryResult(nullptr);
197 }
198
199 return QueryResult(result);
200}
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:186

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

◆ QueueSize()

template<class T >
std::size_t DatabaseWorkerPool< T >::QueueSize ( ) const
481{
482 return _queue->Size();
483}

◆ SetConnectionInfo()

template<class T >
void DatabaseWorkerPool< T >::SetConnectionInfo ( std::string_view  infoString,
uint8 const  asyncThreads,
uint8 const  synchThreads 
)
79{
80 _connectionInfo = std::make_unique<MySQLConnectionInfo>(infoString);
81
82 _async_threads = asyncThreads;
83 _synch_threads = synchThreads;
84}

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: