Database::setActiveConnection()
just sets as active connection a connection defined in the settings.php file, or added from a previous call to Database::addConnectionInfo()
.
The correct code would be the following one.
$postgis_database = [
'database' => $drugis_postgis_connection->getdatabase(),
'username' => $drugis_postgis_connection->getusername(),
'password' => $drugis_postgis_connection->getpassword(),
'host' => $drugis_postgis_connection->gethost(),
'driver' => 'pgsql',
];
// $key $target
Database::addConnectionInfo('postgis','default', $postgis_database);
// $target $key
Database::setActiveConnection('default', 'postgis');
Notice the parameters order in the last two method calls. Notice also the array index order used in the $database
array set in the settings.php file.
// $key $target
$databases['default']['default'] = [
'database' => 'databasename',
'username' => 'sqlusername',
'password' => 'sqlpassword',
'host' => 'localhost',
'port' => '3306',
'driver' => 'mysql',
'prefix' => '',
'collation' => 'utf8mb4_general_ci',
];
The connections added with Database::addConnectionInfo()
aren't permanent; they are added to the static property of the Database
class. All the functions/methods that want to use the connection defined in $postgis_database
needs to execute the code I showed before querying the database or saving values in the database.
It's probably better to add the extra connections in the settings.
An error to avoid is calling Drupal functions that query a specific Drupal database table after calling Database::setActiveConnection('default', 'postgis')
. For example, calling taxonomy_term_load_multiple_by_name()
after Database::setActiveConnection('default', 'postgis')
won't work, except in the case the postgis/default database contains a copy of the tables used from Drupal. (Usually, that isn't the case, as a module using a different database isn't going to make a copy of the tables Drupal expects to find, in that database.)
Before calling functions like taxonomy_term_load_multiple_by_name()
, the code should call Database::setActiveConnection()
, which restores the active connection to the default one used by Drupal, which is for a database containing all the tables used from Drupal.