You are here

public function ConnectionUnitTest::testOpenSelectQueryClose in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Database/ConnectionUnitTest.php \Drupal\KernelTests\Core\Database\ConnectionUnitTest::testOpenSelectQueryClose()
  2. 10 core/tests/Drupal/KernelTests/Core/Database/ConnectionUnitTest.php \Drupal\KernelTests\Core\Database\ConnectionUnitTest::testOpenSelectQueryClose()

Tests Database::closeConnection() with a select query.

File

core/tests/Drupal/KernelTests/Core/Database/ConnectionUnitTest.php, line 187

Class

ConnectionUnitTest
Tests management of database connections.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testOpenSelectQueryClose() {

  // Only run this test for the 'mysql' driver.
  $driver = $this->connection
    ->driver();
  if ($driver !== 'mysql') {
    $this
      ->markTestSkipped("MySql tests can not run for driver '{$driver}'.");
  }

  // Add and open a new connection.
  $this
    ->addConnection();
  $id = $this
    ->getConnectionId();
  Database::getConnection(static::TEST_TARGET_CONNECTION);

  // Verify that there is a new connection.
  $this
    ->assertConnection($id);

  // Create a table.
  $name = 'foo';
  Database::getConnection(static::TEST_TARGET_CONNECTION)
    ->schema()
    ->createTable($name, [
    'fields' => [
      'name' => [
        'type' => 'varchar',
        'length' => 255,
      ],
    ],
  ]);

  // Execute a query.
  Database::getConnection(static::TEST_TARGET_CONNECTION)
    ->select('foo', 'f')
    ->fields('f', [
    'name',
  ])
    ->execute()
    ->fetchAll();

  // Drop the table.
  Database::getConnection(static::TEST_TARGET_CONNECTION)
    ->schema()
    ->dropTable($name);

  // Close the connection.
  Database::closeConnection(static::TEST_TARGET_CONNECTION);

  // Wait 20ms to give the database engine sufficient time to react.
  usleep(20000);

  // Verify that we are back to the original connection count.
  $this
    ->assertNoConnection($id);
}