From 0211e97b9802aa3e52e1934f925e9f6d758b3b84 Mon Sep 17 00:00:00 2001 From: Oskar van Velden Date: Wed, 4 Sep 2024 14:27:23 +0200 Subject: [PATCH] Clear Doctrine cache after connection switch Fix bug described in RamyHakam/multi_tenancy_bundle#50 --- src/EventListener/DbSwitchEventListener.php | 9 ++++++++- src/Resources/config/services.xml | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/EventListener/DbSwitchEventListener.php b/src/EventListener/DbSwitchEventListener.php index 87b593b..f5f80f5 100644 --- a/src/EventListener/DbSwitchEventListener.php +++ b/src/EventListener/DbSwitchEventListener.php @@ -2,6 +2,7 @@ namespace Hakam\MultiTenancyBundle\EventListener; +use Hakam\MultiTenancyBundle\Doctrine\ORM\TenantEntityManager; use Hakam\MultiTenancyBundle\Event\SwitchDbEvent; use Hakam\MultiTenancyBundle\Services\DbConfigService; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -16,7 +17,8 @@ class DbSwitchEventListener implements EventSubscriberInterface public function __construct( private ContainerInterface $container, private DbConfigService $dbConfigService, - private string $databaseURL + private TenantEntityManager $tenantEntityManager, + private string $databaseURL, ) { } @@ -33,6 +35,7 @@ public function onHakamMultiTenancyBundleEventSwitchDbEvent(SwitchDbEvent $switc { $dbConfig = $this->dbConfigService->findDbConfig($switchDbEvent->getDbIndex()); $tenantConnection = $this->container->get('doctrine')->getConnection('tenant'); + $params = [ 'dbname' => $dbConfig->getDbName(), 'user' => $dbConfig->getDbUsername() ?? $this->parseDatabaseUrl($this->databaseURL)['user'], @@ -40,7 +43,11 @@ public function onHakamMultiTenancyBundleEventSwitchDbEvent(SwitchDbEvent $switc 'host' => $dbConfig->getDbHost() ?? $this->parseDatabaseUrl($this->databaseURL)['host'], 'port' => $dbConfig->getDbPort() ?? $this->parseDatabaseUrl($this->databaseURL)['port'], ]; + $tenantConnection->switchConnection($params); + + //clear the entity manager to avoid Doctrine cache issues + $this->tenantEntityManager->clear(); } private function parseDatabaseUrl(string $databaseURL): array diff --git a/src/Resources/config/services.xml b/src/Resources/config/services.xml index ad36a51..b992c03 100644 --- a/src/Resources/config/services.xml +++ b/src/Resources/config/services.xml @@ -17,6 +17,7 @@ + %env(DATABASE_URL)% @@ -58,4 +59,4 @@ - \ No newline at end of file +