You are here

public function BackendTest::testNonDefaultDatabase in Search API 8

Tests whether a server on a non-default database is handled correctly.

File

modules/search_api_db/tests/src/Kernel/BackendTest.php, line 999

Class

BackendTest
Tests index and search capabilities using the Database search backend.

Namespace

Drupal\Tests\search_api_db\Kernel

Code

public function testNonDefaultDatabase() {

  // Clone the primary credentials to a replica connection.
  // Note this will result in two independent connection objects that happen
  // to point to the same place.
  // @see \Drupal\KernelTests\Core\Database\ConnectionTest::testConnectionRouting()
  $connection_info = CoreDatabase::getConnectionInfo('default');
  CoreDatabase::addConnectionInfo('default', 'replica', $connection_info['default']);
  $db1 = CoreDatabase::getConnection('default', 'default');
  $db2 = CoreDatabase::getConnection('replica', 'default');

  // Safety checks copied from the Core test, if these fail something is wrong
  // with Core.
  $this
    ->assertNotNull($db1, 'default connection is a real connection object.');
  $this
    ->assertNotNull($db2, 'replica connection is a real connection object.');
  $this
    ->assertNotSame($db1, $db2, 'Each target refers to a different connection.');

  // Create backends based on each of the two targets and verify they use the
  // right connections.
  $config = [
    'database' => 'default:default',
  ];
  $backend1 = Database::create($this->container, $config, '', []);
  $config['database'] = 'default:replica';
  $backend2 = Database::create($this->container, $config, '', []);
  $this
    ->assertSame($db1, $backend1
    ->getDatabase());
  $this
    ->assertSame($db2, $backend2
    ->getDatabase());

  // Make sure they also use different DBMS compatibility handlers, which also
  // use the correct database connections.
  $dbms_comp1 = $backend1
    ->getDbmsCompatibilityHandler();
  $dbms_comp2 = $backend2
    ->getDbmsCompatibilityHandler();
  $this
    ->assertNotSame($dbms_comp1, $dbms_comp2);
  $this
    ->assertSame($db1, $dbms_comp1
    ->getDatabase());
  $this
    ->assertSame($db2, $dbms_comp2
    ->getDatabase());

  // Finally, make sure the DBMS compatibility handlers also have the correct
  // classes (meaning we used the correct one and didn't just fall back to the
  // generic database).
  $service = $this->container
    ->get('search_api_db.database_compatibility');
  $database_type = $db1
    ->databaseType();
  $service_id = "{$database_type}.search_api_db.database_compatibility";
  $service2 = $this->container
    ->get($service_id);
  $this
    ->assertSame($service2, $service);
  $class = get_class($service);
  $this
    ->assertNotEquals(GenericDatabase::class, $class);
  $this
    ->assertSame($dbms_comp1, $service);
  $this
    ->assertEquals($class, get_class($dbms_comp2));
}