Question

I have 2 databases, the first one with Drupal and the second one with external data. In a controller I want to read data from that second database and display it.

As the external database can be available or not, is there any method to check if the connection is available or not?

My code is working, but if the DB is not available (or unset) I get the following error:

Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: schedules in Drupal\Core\Database\Database::openConnection() (line 364 of core/lib/Drupal/Core/Database/Database.php).

Code:

abstract class AbstractSchedulesRepository {

  /**
   * Schedules repository target.
   */
  public const SCHEDULES_REPOSITORY_TARGET_DATABASE = 'default';

  /**
   * Schedules repository key.
   */
  public const SCHEDULES_REPOSITORY_KEY_DATABASE = 'schedules';

  /**
   * Drupal\schedules\Repository\SchedulesCache definition.
   *
   * @var \Drupal\schedules\Cache\SchedulesCache
   */
  protected $schedulesCache;

  /**
   * Drupal\Core\Language\LanguageManager definition.
   *
   * @var \Drupal\Core\Language\LanguageManager
   */
  protected $languageManager;

  /**
   * Drupal\Core\Database\Connection definition.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * Constructor.
   *
   * @param \Drupal\schedules\Cache\SchedulesCache $schedulesCache
   *   Schedules cache.
   * @param \Drupal\Core\Language\LanguageManager $languageManager
   *   Language manager.
   */
  public function __construct(SchedulesCache $schedulesCache, LanguageManager $languageManager) {
    $this->schedulesCache  = $schedulesCache;
    $this->languageManager = $languageManager;
    $this->connection      = Database::getConnection(self::SCHEDULES_REPOSITORY_TARGET_DATABASE, self::SCHEDULES_REPOSITORY_KEY_DATABASE);
  }
Was it helpful?

Solution

is there any method to check if the connection is available or not?

If you mean class method, then no, because it wouldn’t be necessary. You can simply catch the exception, which will tell you immediately that the connection was not successful:

try {
  // Code using a database connection
} catch (ConnectionNotDefinedException $e) {
  // No database for you
}
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top