Score:2

How to check if secondary database definition exists

fr flag

Can anyone please help me on how to check if secondary database is set. If not throw an error.

I am currently defining database connection as below.

Database::getConnection('default', 'sqlite')

I am trying to defining a if , else condition based the database defining.

When I try

if(Database::getConnection('default', 'sqlite')){
  echo success;
}else {
  echo fail;
}

I am getting below error. If secondary database definition is not defined in settings.php

Drupal\Core\Entity\EntityStorageException: 
The specified database connection is not defined: sqlite in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 811 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Score:2
us flag

To check if a connection has been defined, I would use code similar to the following one.

if ($connections = Database::getAllConnectionInfo() && isset($connections['default']['sqlite'])) {
  // The connection is defined.
} 

Database::getConnection() returns a connection object, and it could return the one for default/primary server, when the requested information is for an ignored connection or the requested connection isn't defined.

  // If the requested target does not exist, or if it is ignored, we fall back
  // to the default target. The target is typically either "default" or
  // "replica", indicating to use a replica SQL server if one is available. If
  // it's not available, then the default/primary server is the correct server
  // to use.
  if (!empty(self::$ignoreTargets[$key][$target]) || !isset(self::$databaseInfo[$key][$target])) {
    $target = 'default';
  }
  if (!isset(self::$connections[$key][$target])) {

    // If necessary, a new connection is opened.
    self::$connections[$key][$target] = self::openConnection($key, $target);
  }

This means that expecting an exception from Database::getConnection() when the connection isn't defined is wrong.

miststudent2011 avatar
fr flag
Thanks its better than the other answer.
Score:1
id flag
try {
    $connection = Database::getConnection('default', 'sqlite');
}
catch (Drupal\Core\Entity\EntityStorageException $e) {
    // Do something here.
}
finally {
    // Optional: do something in any case.
}
miststudent2011 avatar
fr flag
Thanks , it works. But just wondering whether we have any method in core to check if the connection exists. Something like `hasConnection()`
Score:-1
fr flag

Although cilefen pointed me in the right direction. It still throws fatal error when using cilefen's answer. I am able to resolve this issue by slightly modifying exception handling.

try {
  $connection = Database::getConnection('default', 'sqlite');
} catch (\Exception $e) {
  return new \Exception("SQLite Database configurtion is not setup.", 1);
}

Created a core issue #3282024 to add native method to check database connection.

id flag
You may need a slash before the exception, like \Drupal\Core\Entity\EntityStorageException. \Exception could be anything at all.
miststudent2011 avatar
fr flag
Adding slash produces the same error.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.