From 479df83027f75209343f02164978aabcea8fa0d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20=C5=A0tancl?= Date: Sat, 19 Oct 2019 23:52:13 +0200 Subject: [PATCH] [2.x] Don't purge central connections (#189) * Make sure central connections aren't ever purged * Extract setDefaultConnection() * Regression test w/ markTestIncomplete() * Apply fixes from StyleCI --- src/DatabaseManager.php | 16 +++++++++++++++- tests/DatabaseManagerTest.php | 17 +++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/DatabaseManager.php b/src/DatabaseManager.php index f480e4b7..3a42d3b0 100644 --- a/src/DatabaseManager.php +++ b/src/DatabaseManager.php @@ -39,6 +39,7 @@ class DatabaseManager public function connect(Tenant $tenant) { $this->createTenantConnection($tenant->getDatabaseName(), $tenant->getConnectionName()); + $this->setDefaultConnection($tenant->getConnectionName()); $this->switchConnection($tenant->getConnectionName()); } @@ -49,9 +50,23 @@ class DatabaseManager */ public function reconnect() { + // Opposite order to connect() because we don't + // want to ever purge the central connection + $this->setDefaultConnection($this->originalDefaultConnectionName); $this->switchConnection($this->originalDefaultConnectionName); } + /** + * Change the default database connection config. + * + * @param string $connection + * @return void + */ + public function setDefaultConnection(string $connection) + { + $this->app['config']['database.default'] = $connection; + } + /** * Create the tenant database connection. * @@ -102,7 +117,6 @@ class DatabaseManager */ public function switchConnection(string $connection) { - $this->app['config']['database.default'] = $connection; $this->database->purge(); $this->database->reconnect($connection); $this->database->setDefaultConnection($connection); diff --git a/tests/DatabaseManagerTest.php b/tests/DatabaseManagerTest.php index cbd976e8..9195ef69 100644 --- a/tests/DatabaseManagerTest.php +++ b/tests/DatabaseManagerTest.php @@ -45,4 +45,21 @@ class DatabaseManagerTest extends TestCase $this->assertSame('tenant', config('database.default')); $this->assertSame('bar', config('database.connections.' . config('database.default') . '.foo')); } + + /** @test */ + public function ending_tenancy_doesnt_purge_the_central_connection() + { + $this->markTestIncomplete('Seems like this only happens on MySQL?'); + + // regression test for https://github.com/stancl/tenancy/pull/189 + // config(['tenancy.migrate_after_creation' => true]); + + tenancy()->create(['foo.localhost']); + tenancy()->init('foo.localhost'); + tenancy()->end(); + + $this->assertNotEmpty(tenancy()->all()); + + tenancy()->all()->each->delete(); + } }