02
Feb '13

MySQL Has Gone Away Messages

I do a lot of data warehousing work these days which often means scripting a series of heavy queries to process data into a more usable format. I built a fairly simple execution framework to make it easier to cron the scripts to run at night when the load on the servers will be lightest but I found that often I would arrive at work the next morning to find that the scripts had failed to complete. After a little testing and logging it appeared that I was getting ‘MySQL has Gone Away’ errors from the Zend adapter I was using for my connection. Bugger.

Actually it turns out that fixing Zend to reconnect automatically when it loses its MySQL connection is a pretty quick hack with some careful use of the ping function.

Zend has a _connect() function in Zend/Db/Adapter/Mysqli.php that begins with a check to see if it has a connection object already created:

if ($this->_connection) {
    return;
}

Unfortunately if ‘MySQL has Gone Away’ this check is too basic to realise. All you need to do to improve this situation is to add a ping to this check:

if ($this->_connection && $this->_connection->ping()) {
    return;
}

And you’re good to go! Zend will automatically reconnect whenever it loses its connection. Winner.

Leave a Reply