Linux and PHP web application support and development (Bromsgrove, UK)

PHPUnit and PDO – max_user_connections reached

We have a set of PHPUnit tests running against a Propel/PDO application.

Recently, with a recent increase in the number of tests, we’ve found that we’ve been hitting MySQL’s max_connections or max_user_connections limit (see /etc/mysql/my.cnf on the MySQL server).

Exception messages like the following would be seen :
PropelException: Unable to open PDO connection [wrapped: SQLSTATE[42000] [1203] User xxx already has more than 'max_user_connections' active connections]

One approach around this is to just increase the max_connections/max_user_connections setting/variables – but this didn’t feel right.

We investigated various approaches to trying to close the database connections – using unset($conn) or $conn = null had no effect, and nor did changing the PDO connection timeout attribute ($conn->setAttribute(PDO::ATTR_TIMEOUT, $newValue)).

Eventually we found a rather nasty solution, which is to add to the unit test’s tearDown method a call which tells the MySQL server to close the connection. A side effect of this is that PHP/PDO then raises an exception, so it doesn’t feel quite right… but nonetheless …. it does solve the connection count issue.

 

class MyTest extends PHPUnit_Framework_TestCase
{
    .....
    public function tearDown() {
        /* @var $conn PDOConnection */
        ....
        try {
            $conn->exec('KILL MY_CONNECTION();');
        }
        catch(Exception $e) { /* ignore */ }
    }
    ....
}

 

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *