RamyHakam / multi_tenancy_bundle

Symfony 5 /6 bundle to support multi-tenants
MIT License
70 stars 24 forks source link

Error connecting to Database Host when triggering DbSwitchEvent #26

Closed HugoIrachetaZenix closed 7 months ago

HugoIrachetaZenix commented 8 months ago

I'm getting an error when triggering the DbSwitchEvent for a Tenant id. I'm not sure if there anything wrong with my configuration but when the MySQL driver tries to connect to the db the params variable only include : dbname, user and password but no host at all. I have the configuration for the hakam_multi_tenancy.yaml it the same of the one in the example (with the difference of the host since i'm connecting to database in cloud).

I made it work by adding the next lines of code to DbSwitchEventListener.php: `public function onHakamMultiTenancyBundleEventSwitchDbEvent(SwitchDbEvent $switchDbEvent): void { $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'], 'password' => $dbConfig->getDbPassword() ?? $this->parseDatabaseUrl($this->databaseURL)['password'], 'host' => $this->parseDatabaseUrl($this->databaseURL)['host'], 'port' => $this->parseDatabaseUrl($this->databaseURL)['port'], ]; $tenantConnection->switchConnection($params); }

private function parseDatabaseUrl(string $databaseURL): array
{
    $url = parse_url($databaseURL);
    return [
        'dbname' => substr($url['path'], 1),
        'user' => $url['user'],
        'password' => $url['pass'],
        'host' => $url['host'],
        'port' => $url['port']
    ];
}`

I also have code to add a dbHost property to the TenantDbConfigurationInterface in case any tenant has a different host than others.

I'm sure I'm doing something wrong configuration wise so any help would be appreciated and also let me know if you want me do do a PR with this changes to how the host is managed.

akrobate67 commented 7 months ago

Thank you for finding the solution to my problem. I just created a pull request correcting the problem. I also added the port and the host in the tenant #27