(Running on Homestead)
On running more than 100 tests that use DatabaseMigrations the following error appears:
Illuminate\Database\QueryException: SQLSTATE[08006] [7] FATAL: sorry, too many clients already
Run more than 100 tests (methods) using DatabaseMigrations on Postgree (default max connections is 100).
I have created a repository to ease reproduce it: https://github.com/mariomka/laravel-pgsql-too-many-clients-test
While tests are running you can see Postgre connections count with:
select count(*) from pg_stat_activity;
Or full info with:
select * from pg_stat_activity;
I am experiencing the same error with one difference, not making use of DatabaseMigrations in my tests.
I have the fix for lumen above
here is PR for Laravel #18752
Yep, same here, see my post on the PR for details.
I believe this was fixed (for Laravel) in 5.5 and at least backported to 5.4 (or it was introduced in 5.4, don't remember); I know this issue well because I had the same problem in the past.
It's all connected to this trait \Illuminate\Foundation\Testing\DatabaseTransactions.
See the code in 5.3:
public function beginDatabaseTransaction()
{
$database = $this->app->make('db');
foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->beginTransaction();
}
$this->beforeApplicationDestroyed(function () use ($database) {
foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->rollBack();
}
});
}
Now compare it to 5.4/5.5
public function beginDatabaseTransaction()
{
$database = $this->app->make('db');
foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->beginTransaction();
}
$this->beforeApplicationDestroyed(function () use ($database) {
foreach ($this->connectionsToTransact() as $name) {
$connection = $database->connection($name);
$connection->rollBack();
$connection->disconnect();
}
});
}
This contains the needed ->disconect() call.
It works for us (we've >2k tests, lots of them using this trait) and before this fix I basically had a copy of the trait doing exactly this and could remove it once we upgraded to 5.4/5.5
Most helpful comment
here is PR for Laravel #18752