Skip to content

Commit

Permalink
MySql automatic reconnection on error 2006 (Mysql has gone away)
Browse files Browse the repository at this point in the history
  • Loading branch information
rotamike committed Feb 26, 2018
1 parent e982a5b commit d9850ca
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
13 changes: 12 additions & 1 deletion src/Db/MySqliDb.php
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,18 @@ protected function _query($query, $isSystemQuery)
Debugger::addQuery($query, $isSystemQuery);
}

return @mysqli_query($this->m_link_id, $query);
$result = @mysqli_query($this->m_link_id, $query);
if(!$result && mysqli_errno($this->m_link_id) === 2006) {
Tools::atkdebug('DB has gone away, try to reconnect');
$this->disconnect();
if ($this->connect() !== Db::DB_SUCCESS) {
Tools::atkerror('Cannot connect to database.');
}else {
$result = @mysqli_query($this->m_link_id, $query);
}
}

return $result;
}

/**
Expand Down
20 changes: 17 additions & 3 deletions src/Db/Statement/MySqliStatement.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,27 @@ class MySqliStatement extends Statement
*/
protected function _prepare()
{
if ($this->getDb()->connect() != Db::DB_SUCCESS) {
if ($this->getDb()->connect() !== Db::DB_SUCCESS) {
throw new StatementException('Cannot connect to database.', StatementException::NO_DATABASE_CONNECTION);
}

$query = $this->_getParsedQuery();
$conn = $this->getDb()->link_id();
Tools::atkdebug('Prepare query: '.$this->_getParsedQuery());
$this->m_stmt = $conn->prepare($this->_getParsedQuery());
Tools::atkdebug('Prepare query: '.$query);
$this->m_stmt = mysqli_prepare($conn, $query);

if(!$this->m_stmt && $conn->errno === 2006) {
// retry
Tools::atkdebug('DB has gone away, try to reconnect');
$this->getDb()->disconnect();
if ($this->getDb()->connect() !== Db::DB_SUCCESS) {
throw new StatementException('Cannot connect to database.', StatementException::NO_DATABASE_CONNECTION);
}
$conn = $this->getDb()->link_id();
Tools::atkdebug('Prepare query after reconnection: '.$query);
$this->m_stmt = mysqli_prepare($conn, $query);
}

if (!$this->m_stmt || $conn->errno) {
throw new StatementException("Cannot prepare statement (ERROR: {$conn->errno} - {$conn->error}).", StatementException::PREPARE_STATEMENT_ERROR);
}
Expand Down

0 comments on commit d9850ca

Please sign in to comment.