Skip to content

Commit

Permalink
Merge pull request #3 from optiman/master
Browse files Browse the repository at this point in the history
Updated RefreshDatabase trait (fixes "Too many connections" error)
  • Loading branch information
albertcht authored Jul 15, 2018
2 parents cdeceb9 + 201e53d commit 8829069
Showing 1 changed file with 33 additions and 9 deletions.
42 changes: 33 additions & 9 deletions src/Concerns/RefreshDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ trait RefreshDatabase
public function refreshDatabase()
{
$this->usingInMemoryDatabase()
? $this->refreshInMemoryDatabase()
: $this->refreshTestDatabase();
? $this->refreshInMemoryDatabase()
: $this->refreshTestDatabase();
}

/**
Expand All @@ -26,8 +26,8 @@ public function refreshDatabase()
protected function usingInMemoryDatabase()
{
return config('database.connections')[
config('database.default')
]['database'] == ':memory:';
config('database.default')
]['database'] == ':memory:';
}

/**
Expand All @@ -48,7 +48,9 @@ protected function refreshInMemoryDatabase()
protected function refreshTestDatabase()
{
if (! RefreshDatabaseState::$migrated) {
$this->artisan('migrate:fresh');
$this->artisan('migrate:fresh', $this->shouldDropViews() ? [
'--drop-views' => true,
] : []);

RefreshDatabaseState::$migrated = true;
}
Expand All @@ -66,12 +68,23 @@ public function beginDatabaseTransaction()
$database = $this->app->make('db');

foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->beginTransaction();
$connection = $database->connection($name);
$dispatcher = $connection->getEventDispatcher();

$connection->unsetEventDispatcher();
$connection->beginTransaction();
$connection->setEventDispatcher($dispatcher);
}

$this->beforeApplicationDestroyed(function () use ($database) {
foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->rollBack();
$connection = $database->connection($name);
$dispatcher = $connection->getEventDispatcher();

$connection->unsetEventDispatcher();
$connection->rollback();
$connection->setEventDispatcher($dispatcher);
$connection->disconnect();
}
});
}
Expand All @@ -84,6 +97,17 @@ public function beginDatabaseTransaction()
protected function connectionsToTransact()
{
return property_exists($this, 'connectionsToTransact')
? $this->connectionsToTransact : [null];
? $this->connectionsToTransact : [null];
}

/**
* Determine if views should be dropped when refreshing the database.
*
* @return bool
*/
protected function shouldDropViews()
{
return property_exists($this, 'dropViews')
? $this->dropViews : false;
}
}
}

0 comments on commit 8829069

Please sign in to comment.