Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated RefreshDatabase trait (fixes "Too many connections" error) #3

Merged
merged 1 commit into from
Jul 15, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}
}