Index: mysql.cpp =================================================================== RCS file: /Source/Programs/nwnx4/nwnx4/src/plugins/mysql/mysql.cpp,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- mysql.cpp 3 Jan 2008 08:02:01 -0000 1.1 +++ mysql.cpp 27 Feb 2008 01:24:04 -0000 1.2 @@ -23,6 +23,14 @@ NWNX and DLL specific functions ***************************************************************************/ +/* + * Ugh, we need the actual header. + */ + +#define CR_SERVER_GONE_ERROR 2006 +#define CR_SERVER_LOST 2013 + + MySQL* plugin; DLLEXPORT Plugin* GetPluginPointerV2() @@ -149,6 +157,8 @@ bool MySQL::Execute(char* query) { MYSQL_RES *newResult; + unsigned long tries; + bool success; if (!connection) { @@ -164,24 +174,65 @@ mysql_free_result(newResult); } - // execute the query - if (logLevel == 2) - wxLogMessage(wxT("* Executing: %s"), query); - if (mysql_query(connection, (const char *)query) != 0) - { - if (logLevel > 0) - wxLogMessage(wxT("! SQL Error: %s."), mysql_error(&mysql)); + success = false; - // throw away last resultset if a SELECT statement failed - if (_strnicmp(query, wxT("SELECT"), 6) == 0) + for (tries = 0; + tries < 3; + tries += 1) + { + // execute the query + if (logLevel == 2) + wxLogMessage(wxT("* Executing: %s"), query); + if (mysql_query(connection, (const char *)query) != 0) { - mysql_free_result(result); - result = NULL; - row = NULL; - num_fields = 0; + unsigned int sqlerr; + + sqlerr = mysql_errno( &mysql ); + + if (logLevel > 0) + wxLogMessage(wxT("! SQL Error: %s (%lu)."), mysql_error(&mysql), sqlerr); + + // throw away last resultset if a SELECT statement failed + if (_strnicmp(query, wxT("SELECT"), 6) == 0) + { + mysql_free_result(result); + result = NULL; + row = NULL; + num_fields = 0; + } + + // + // Let's disconnect and reconnect the connection if we failed to + // query. This is so that if the server connection went away, we + // aren't permanently broken. + // + + wxLogMessage( wxT("! Reconnecting to database..." ) ); + + Disconnect(); + + if (!Connect()) + wxLogMessage( wxT( "! Failed to reconnect to database." ) ); + + // + // We only retry queries if we got CR_SERVER_GONE_ERROR. Otherwise + // we might have initiated the query already and could be in an + // indeterminate state if we repeat it. + // + if ((sqlerr != CR_SERVER_GONE_ERROR)) + break; + + wxLogMessage( wxT( "! Retrying query..." ) ); + } + else + { + success = true; + break; } - return FALSE; } + + if (!success) + return FALSE; // store the resultset in local memory newResult = mysql_store_result(&mysql);