You are here

protected function ViewsSqlQueryGetConnectionTrait::getDatabaseConnection in Range 8

Gets the database connection to use for the view.

The returned database connection does not have to be the default database connection. It can also be to another database connection when the view is to an external database or a replica database.

Return value

\Drupal\Core\Database\Connection The database connection to be used for the query.

File

src/D8Compatibility/ViewsSqlQueryGetConnectionTrait.php, line 34

Class

ViewsSqlQueryGetConnectionTrait
Gets the database connection to use for the view.

Namespace

Drupal\range\D8Compatibility

Code

protected function getDatabaseConnection(Sql $query) {

  // Call the getConnection() method directly if exists (D9.1+).
  if (method_exists($query, 'getConnection')) {
    return $query
      ->getConnection();
  }
  else {

    // Set the replica target if the replica option is set for the view.
    $target = empty($query->options['replica']) ? 'default' : 'replica';

    // Use an external database when the view configured to.
    $key = $query->view->base_database ?? 'default';
    return Database::getConnection($target, $key);
  }
}