Project SkyFire Core
SkyFire 5.4.8 server core API documentation
Loading...
Searching...
No Matches
MySQLConnection.cpp
Go to the documentation of this file.
1/*
2* This file is part of Project SkyFire https://www.projectskyfire.org.
3* See LICENSE.md file for Copyright information
4*/
5
6
7#include "Common.h"
8
9#ifdef _WIN32
10#include <winsock2.h>
11#endif
12#include <mysql.h>
13#include <mysqld_error.h>
14#include <errmsg.h>
15
16#include "MySQLConnection.h"
17#include "MySQLThreading.h"
18#include "Platform/TimeUtils.h"
19#include "QueryResult.h"
20#include "SQLOperation.h"
21#include "PreparedStatement.h"
22#include "DatabaseWorker.h"
23#include "Timer.h"
24#include "Log.h"
25
26MySQLConnection::MySQLConnection(MySQLConnectionInfo& connInfo) :
27 m_reconnecting(false),
28 m_prepareError(false),
29 m_queue(NULL),
30 m_worker(NULL),
31 m_Mysql(NULL),
32 m_connectionInfo(connInfo),
33 m_connectionFlags(CONNECTION_SYNCH) { }
34
35MySQLConnection::MySQLConnection(Skyfire::DatabaseQueue* queue, MySQLConnectionInfo& connInfo) :
36 m_reconnecting(false),
37 m_prepareError(false),
38 m_queue(queue),
39 m_Mysql(NULL),
40 m_connectionInfo(connInfo),
41 m_connectionFlags(CONNECTION_ASYNC)
42{
43 m_worker = new DatabaseWorker(m_queue, this);
44}
45
46MySQLConnection::~MySQLConnection()
47{
48 ASSERT(m_Mysql);
49
50 for (size_t i = 0; i < m_stmts.size(); ++i)
51 delete m_stmts[i];
52
53 mysql_close(m_Mysql);
54}
55
56void MySQLConnection::Close()
57{
59 delete this;
60}
61
62bool MySQLConnection::Open()
63{
64 MYSQL* mysqlInit;
65 mysqlInit = mysql_init(NULL);
66 if (!mysqlInit)
67 {
68 SF_LOG_ERROR("sql.sql", "Could not initialize Mysql connection to database `%s`", m_connectionInfo._database.c_str());
69 return false;
70 }
71
72 int port;
73 char const* unix_socket;
74 //unsigned int timeout = 10;
75
76 mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
77 //mysql_options(mysqlInit, MYSQL_OPT_READ_TIMEOUT, (char const*)&timeout);
78#ifdef _WIN32
79 if (m_connectionInfo._host == ".") // named pipe use option (Windows)
80 {
81 unsigned int opt = MYSQL_PROTOCOL_PIPE;
82 mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
83 port = 0;
84 unix_socket = 0;
85 }
86 else // generic case
87 {
88 port = atoi(m_connectionInfo._port_or_socket.c_str());
89 unix_socket = 0;
90 }
91#else
92 if (m_connectionInfo._host == ".") // socket use option (Unix/Linux)
93 {
94 unsigned int opt = MYSQL_PROTOCOL_SOCKET;
95 mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
96 m_connectionInfo._host = "localhost";
97 port = 0;
98 unix_socket = m_connectionInfo._port_or_socket.c_str();
99 }
100 else // generic case
101 {
102 port = atoi(m_connectionInfo._port_or_socket.c_str());
103 unix_socket = 0;
104 }
105#endif
106
107 m_Mysql = mysql_real_connect(mysqlInit, m_connectionInfo._host.c_str(), m_connectionInfo._user.c_str(),
108 m_connectionInfo._password.c_str(), m_connectionInfo._database.c_str(), port, unix_socket, 0);
109
110 if (m_Mysql)
111 {
112 if (!m_reconnecting)
113 {
114 SF_LOG_INFO("sql.sql", "MySQL client library: %s", mysql_get_client_info());
115 SF_LOG_INFO("sql.sql", "MySQL server ver: %s ", mysql_get_server_info(m_Mysql));
116 // MySQL version above 5.1 IS required in both client and server and there is no known issue with different versions above 5.1
117 // if (mysql_get_server_version(m_Mysql) != mysql_get_client_version())
118 // SF_LOG_INFO("sql.sql", "[WARNING] MySQL client/server version mismatch; may conflict with behaviour of prepared statements.");
119 }
120
121 SF_LOG_INFO("sql.sql", "Connected to MySQL database at %s", m_connectionInfo._host.c_str());
122 mysql_autocommit(m_Mysql, 1);
123
124 // set connection properties to UTF8 to properly handle locales for different
125 // server configs - core sends data in UTF8, so MySQL must expect UTF8 too
126 mysql_set_character_set(m_Mysql, "utf8");
127 return PrepareStatements();
128 }
129 else
130 {
131 SF_LOG_ERROR("sql.sql", "Could not connect to MySQL database at %s: %s\n", m_connectionInfo._host.c_str(), mysql_error(mysqlInit));
132 mysql_close(mysqlInit);
133 return false;
134 }
135}
136
137bool MySQLConnection::PrepareStatements()
138{
139 DoPrepareStatements();
140 return !m_prepareError;
141}
142
143bool MySQLConnection::Execute(const char* sql)
144{
145 if (!m_Mysql)
146 return false;
147
148 {
149 uint32 _s = getMSTime();
150
151 if (mysql_query(m_Mysql, sql))
152 {
153 uint32 lErrno = mysql_errno(m_Mysql);
154
155 SF_LOG_INFO("sql.sql", "SQL: %s", sql);
156 SF_LOG_ERROR("sql.sql", "[%u] %s", lErrno, mysql_error(m_Mysql));
157
158 if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
159 return Execute(sql); // Try again
160
161 return false;
162 }
163 else
164 SF_LOG_DEBUG("sql.sql", "[%u ms] SQL: %s", getMSTimeDiff(_s, getMSTime()), sql);
165 }
166
167 return true;
168}
169
170bool MySQLConnection::Execute(PreparedStatement* stmt)
171{
172 if (!m_Mysql)
173 return false;
174
175 uint32 index = stmt->m_index;
176 {
177 MySQLPreparedStatement* m_mStmt = GetPreparedStatement(index);
178 ASSERT(m_mStmt); // Can only be null if preparation failed, server side error or bad query
179 m_mStmt->m_stmt = stmt; // Cross reference them for debug output
180 stmt->m_stmt = m_mStmt;
181
182 stmt->BindParameters();
183
184 MYSQL_STMT* msql_STMT = m_mStmt->GetSTMT();
185 MYSQL_BIND* msql_BIND = m_mStmt->GetBind();
186
187 uint32 _s = getMSTime();
188
189#if MYSQL_VERSION_ID >= 80300
190 if (mysql_stmt_bind_named_param(msql_STMT, msql_BIND, m_mStmt->m_paramCount, nullptr))
191#else
192 if (mysql_stmt_bind_param(msql_STMT, msql_BIND))
193#endif
194 {
195 uint32 lErrno = mysql_errno(m_Mysql);
196 SF_LOG_ERROR("sql.sql", "SQL(p): %s\n [ERROR]: [%u] %s", m_mStmt->getQueryString(m_queries[index].first).c_str(), lErrno, mysql_stmt_error(msql_STMT));
197
198 if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
199 return Execute(stmt); // Try again
200
201 m_mStmt->ClearParameters();
202 return false;
203 }
204
205 if (mysql_stmt_execute(msql_STMT))
206 {
207 uint32 lErrno = mysql_errno(m_Mysql);
208 SF_LOG_ERROR("sql.sql", "SQL(p): %s\n [ERROR]: [%u] %s", m_mStmt->getQueryString(m_queries[index].first).c_str(), lErrno, mysql_stmt_error(msql_STMT));
209
210 if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
211 return Execute(stmt); // Try again
212
213 m_mStmt->ClearParameters();
214 return false;
215 }
216
217 SF_LOG_DEBUG("sql.sql", "[%u ms] SQL(p): %s", getMSTimeDiff(_s, getMSTime()), m_mStmt->getQueryString(m_queries[index].first).c_str());
218
219 m_mStmt->ClearParameters();
220 return true;
221 }
222}
223
224bool MySQLConnection::_Query(PreparedStatement* stmt, MYSQL_RES** pResult, uint64* pRowCount, uint32* pFieldCount)
225{
226 if (!m_Mysql)
227 return false;
228
229 uint32 index = stmt->m_index;
230 {
231 MySQLPreparedStatement* m_mStmt = GetPreparedStatement(index);
232 ASSERT(m_mStmt); // Can only be null if preparation failed, server side error or bad query
233 m_mStmt->m_stmt = stmt; // Cross reference them for debug output
234 stmt->m_stmt = m_mStmt;
235
236 stmt->BindParameters();
237
238 MYSQL_STMT* msql_STMT = m_mStmt->GetSTMT();
239 MYSQL_BIND* msql_BIND = m_mStmt->GetBind();
240
241 uint32 _s = getMSTime();
242
243#if MYSQL_VERSION_ID >= 80300
244 if (mysql_stmt_bind_named_param(msql_STMT, msql_BIND, m_mStmt->m_paramCount, nullptr))
245#else
246 if (mysql_stmt_bind_param(msql_STMT, msql_BIND))
247#endif
248 {
249 uint32 lErrno = mysql_errno(m_Mysql);
250 SF_LOG_ERROR("sql.sql", "SQL(p): %s\n [ERROR]: [%u] %s", m_mStmt->getQueryString(m_queries[index].first).c_str(), lErrno, mysql_stmt_error(msql_STMT));
251
252 if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
253 return _Query(stmt, pResult, pRowCount, pFieldCount); // Try again
254
255 m_mStmt->ClearParameters();
256 return false;
257 }
258
259 if (mysql_stmt_execute(msql_STMT))
260 {
261 uint32 lErrno = mysql_errno(m_Mysql);
262 SF_LOG_ERROR("sql.sql", "SQL(p): %s\n [ERROR]: [%u] %s",
263 m_mStmt->getQueryString(m_queries[index].first).c_str(), lErrno, mysql_stmt_error(msql_STMT));
264
265 if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
266 return _Query(stmt, pResult, pRowCount, pFieldCount); // Try again
267
268 m_mStmt->ClearParameters();
269 return false;
270 }
271
272 SF_LOG_DEBUG("sql.sql", "[%u ms] SQL(p): %s", getMSTimeDiff(_s, getMSTime()), m_mStmt->getQueryString(m_queries[index].first).c_str());
273
274 m_mStmt->ClearParameters();
275
276 *pResult = mysql_stmt_result_metadata(msql_STMT);
277 *pRowCount = mysql_stmt_num_rows(msql_STMT);
278 *pFieldCount = mysql_stmt_field_count(msql_STMT);
279
280 return true;
281 }
282}
283
284ResultSet* MySQLConnection::Query(const char* sql)
285{
286 if (!sql)
287 return NULL;
288
289 MYSQL_RES* result = NULL;
290 MYSQL_FIELD* fields = NULL;
291 uint64 rowCount = 0;
292 uint32 fieldCount = 0;
293
294 if (!_Query(sql, &result, &fields, &rowCount, &fieldCount))
295 return NULL;
296
297 return new ResultSet(result, fields, rowCount, fieldCount);
298}
299
300bool MySQLConnection::_Query(const char* sql, MYSQL_RES** pResult, MYSQL_FIELD** pFields, uint64* pRowCount, uint32* pFieldCount)
301{
302 if (!m_Mysql)
303 return false;
304
305 {
306 uint32 _s = getMSTime();
307
308 if (mysql_query(m_Mysql, sql))
309 {
310 uint32 lErrno = mysql_errno(m_Mysql);
311 SF_LOG_INFO("sql.sql", "SQL: %s", sql);
312 SF_LOG_ERROR("sql.sql", "[%u] %s", lErrno, mysql_error(m_Mysql));
313
314 if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
315 return _Query(sql, pResult, pFields, pRowCount, pFieldCount); // We try again
316
317 return false;
318 }
319 else
320 SF_LOG_DEBUG("sql.sql", "[%u ms] SQL: %s", getMSTimeDiff(_s, getMSTime()), sql);
321
322 *pResult = mysql_store_result(m_Mysql);
323 *pRowCount = mysql_affected_rows(m_Mysql);
324 *pFieldCount = mysql_field_count(m_Mysql);
325 }
326
327 if (!*pResult)
328 return false;
329
330 if (!*pRowCount)
331 {
332 mysql_free_result(*pResult);
333 return false;
334 }
335
336 *pFields = mysql_fetch_fields(*pResult);
337
338 return true;
339}
340
341void MySQLConnection::BeginTransaction()
342{
343 Execute("START TRANSACTION");
344}
345
346void MySQLConnection::RollbackTransaction()
347{
348 Execute("ROLLBACK");
349}
350
351void MySQLConnection::CommitTransaction()
352{
353 Execute("COMMIT");
354}
355
356bool MySQLConnection::ExecuteTransaction(SQLTransaction& transaction)
357{
358 std::list<SQLElementData> const& queries = transaction->m_queries;
359 if (queries.empty())
360 return false;
361
362 BeginTransaction();
363
364 std::list<SQLElementData>::const_iterator itr;
365 for (itr = queries.begin(); itr != queries.end(); ++itr)
366 {
367 SQLElementData const& data = *itr;
368 switch (itr->type)
369 {
371 {
372 PreparedStatement* stmt = data.element.stmt;
373 ASSERT(stmt);
374 if (!Execute(stmt))
375 {
376 SF_LOG_WARN("sql.sql", "Transaction aborted. %u queries not executed.", (uint32)queries.size());
377 RollbackTransaction();
378 return false;
379 }
380 }
381 break;
382 case SQL_ELEMENT_RAW:
383 {
384 const char* sql = data.element.query;
385 ASSERT(sql);
386 if (!Execute(sql))
387 {
388 SF_LOG_WARN("sql.sql", "Transaction aborted. %u queries not executed.", (uint32)queries.size());
389 RollbackTransaction();
390 return false;
391 }
392 }
393 break;
394 }
395 }
396
397 // we might encounter errors during certain queries, and depending on the kind of error
398 // we might want to restart the transaction. So to prevent data loss, we only clean up when it's all done.
399 // This is done in calling functions DatabaseWorkerPool<T>::DirectCommitTransaction and TransactionTask::Execute,
400 // and not while iterating over every element.
401
402 CommitTransaction();
403 return true;
404}
405
406MySQLPreparedStatement* MySQLConnection::GetPreparedStatement(uint32 index)
407{
408 ASSERT(index < m_stmts.size());
409 MySQLPreparedStatement* ret = m_stmts[index];
410 if (!ret)
411 SF_LOG_ERROR("sql.sql", "Could not fetch prepared statement %u on database `%s`, connection type: %s.",
412 index, m_connectionInfo._database.c_str(), (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous");
413
414 return ret;
415}
416
417void MySQLConnection::PrepareStatement(uint32 index, std::string sql, ConnectionFlags flags)
418{
419 m_queries.insert(PreparedStatementMap::value_type(index, std::make_pair(sql, flags)));
420
421 // For reconnection case
422 if (m_reconnecting)
423 delete m_stmts[index];
424
425 // Check if specified query should be prepared on this connection
426 // i.e. don't prepare async statements on synchronous connections
427 // to save memory that will not be used.
428 if (!(m_connectionFlags & flags))
429 {
430 m_stmts[index] = NULL;
431 return;
432 }
433
434 MYSQL_STMT* stmt = mysql_stmt_init(m_Mysql);
435 if (!stmt)
436 {
437 SF_LOG_ERROR("sql.sql", "In mysql_stmt_init() id: %u, sql: \"%s\"", index, sql.c_str());
438 SF_LOG_ERROR("sql.sql", "%s", mysql_error(m_Mysql));
439 m_prepareError = true;
440 }
441 else
442 {
443 if (mysql_stmt_prepare(stmt, sql.c_str(), sql.length()))
444 {
445 SF_LOG_ERROR("sql.sql", "In mysql_stmt_prepare() id: %u, sql: \"%s\"", index, sql.c_str());
446 SF_LOG_ERROR("sql.sql", "%s", mysql_stmt_error(stmt));
447 mysql_stmt_close(stmt);
448 m_prepareError = true;
449 }
450 else
451 {
452 MySQLPreparedStatement* mStmt = new MySQLPreparedStatement(stmt);
453 m_stmts[index] = mStmt;
454 }
455 }
456}
457
458PreparedResultSet* MySQLConnection::Query(PreparedStatement* stmt)
459{
460 MYSQL_RES* result = NULL;
461 uint64 rowCount = 0;
462 uint32 fieldCount = 0;
463
464 if (!_Query(stmt, &result, &rowCount, &fieldCount))
465 return NULL;
466
467 if (mysql_more_results(m_Mysql))
468 {
469 mysql_next_result(m_Mysql);
470 }
471 return new PreparedResultSet(stmt->m_stmt->GetSTMT(), result, rowCount, fieldCount);
472}
473
474bool MySQLConnection::_HandleMySQLErrno(uint32 errNo)
475{
476 switch (errNo)
477 {
478 case CR_SERVER_GONE_ERROR:
479 case CR_SERVER_LOST:
480 case CR_INVALID_CONN_HANDLE:
481 case CR_SERVER_LOST_EXTENDED:
482 {
483 m_reconnecting = true;
484 uint64 oldThreadId = mysql_thread_id(GetHandle());
485 mysql_close(GetHandle());
486 if (this->Open()) // Don't remove 'this' pointer unless you want to skip loading all prepared statements....
487 {
488 SF_LOG_INFO("sql.sql", "Connection to the MySQL server is active.");
489 if (oldThreadId != mysql_thread_id(GetHandle()))
490 SF_LOG_INFO("sql.sql", "Successfully reconnected to %s @%s:%s (%s).",
491 m_connectionInfo._database.c_str(), m_connectionInfo._host.c_str(), m_connectionInfo._port_or_socket.c_str(),
492 (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous");
493
494 m_reconnecting = false;
495 return true;
496 }
497
498 uint32 lErrno = mysql_errno(GetHandle()); // It's possible this attempted reconnect throws 2006 at us. To prevent crazy recursive calls, sleep here.
500 return _HandleMySQLErrno(lErrno); // Call self (recursive)
501 }
502
503 case ER_LOCK_DEADLOCK:
504 return false; // Implemented in TransactionTask::Execute and DatabaseWorkerPool<T>::DirectCommitTransaction
505 // Query related errors - skip query
506 case ER_WRONG_VALUE_COUNT:
507 case ER_DUP_ENTRY:
508 return false;
509
510 // Outdated table or database structure - terminate core
511 case ER_BAD_FIELD_ERROR:
512 case ER_NO_SUCH_TABLE:
513 SF_LOG_ERROR("sql.sql", "Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders.");
515 std::abort();
516 return false;
517 case ER_PARSE_ERROR:
518 SF_LOG_ERROR("sql.sql", "Error while parsing SQL. Core fix required.");
520 std::abort();
521 return false;
522 default:
523 SF_LOG_ERROR("sql.sql", "Unhandled MySQL errno %u. Unexpected behaviour possible.", errNo);
524 return false;
525 }
526}
std::uint32_t uint32
Definition Define.h:77
std::uint64_t uint64
Definition Define.h:76
#define ASSERT
Definition Errors.h:29
#define SF_LOG_DEBUG(filterType__,...)
Definition Log.h:134
#define SF_LOG_WARN(filterType__,...)
Definition Log.h:140
#define SF_LOG_ERROR(filterType__,...)
Definition Log.h:143
#define SF_LOG_INFO(filterType__,...)
Definition Log.h:137
@ SQL_ELEMENT_RAW
@ SQL_ELEMENT_PREPARED
uint32 getMSTime()
Definition Timer.h:12
uint32 getMSTimeDiff(uint32 oldMSTime, uint32 newMSTime)
Definition Timer.h:17
Skyfire::AutoPtr< Transaction, Skyfire::Mutex > SQLTransaction
Definition Transaction.h:42
PreparedStatement * m_stmt
std::string getQueryString(std::string const &sqlPattern) const
MySQLPreparedStatement * m_stmt
void SleepForSeconds(uint32 seconds)
Definition TimeUtils.h:47
SQLElementUnion element
const char * query
PreparedStatement * stmt