closeConnection example

// Note that resetAll() does not reset the kernel module list so we         // have to do that manually.         $this->kernel->updateModules($module_handler_list$module_handler_list);
      }

      // Close any open database connections. This allows DB drivers that store       // static information to refresh it in the update runner.       // @todo https://drupal.org/i/3222121 consider doing this in       // \Drupal\Core\DrupalKernel::initializeContainer() for container       // rebuilds.       foreach (Database::getAllConnectionInfo() as $key => $info) {
        Database::closeConnection(NULL, $key);
      }

      // If we have successfully clicked 'Apply pending updates' then we need to       // clear the caches in the update test runner as this has occurred as part       // of the updates.       $this->resetAll();

      // The config schema can be incorrect while the update functions are being       // executed. But once the update has been completed, it needs to be valid       // again. Assert the schema of all configuration objects now.       $names = $this->container->get('config.storage')->listAll();

      
$view->base_database = 'corefake';
    $this->assertSame('corefake', $view->getQuery()->getConnection()->getKey());
    $this->assertSame('default', $view->getQuery()->getConnection()->getTarget());

    // Test the database connection with the view 'base_database' set and the     // option 'replica' set to TRUE.     $view->getQuery()->options['replica'] = TRUE;
    $this->assertSame('corefake', $view->getQuery()->getConnection()->getKey());
    $this->assertSame('replica', $view->getQuery()->getConnection()->getTarget());

    // Clean up the created database connections.     Database::closeConnection('replica', 'default');
    Database::closeConnection('default', 'corefake');
    Database::closeConnection('replica', 'corefake');
  }

}
protected function assertNoConnection(int $id): void {
    $this->assertArrayNotHasKey($id$this->monitor->query($this->getQuery()['processlist'])->fetchAllKeyed(0, 0));
  }

  /** * Tests Database::closeConnection() without query. * * @todo getConnectionId() executes a query. */
  public function testOpenClose(): void {
    // 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($this->id);
  }

  /** * Tests Database::closeConnection() with a query. */
  public function testOpenQueryClose(): void {
    
/** * Remove a connection and its corresponding connection information. * * @param string $key * The connection key. * * @return bool * TRUE in case of success, FALSE otherwise. */
  final public static function removeConnection($key) {
    if (isset(self::$databaseInfo[$key])) {
      self::closeConnection(NULL, $key);
      unset(self::$databaseInfo[$key]);
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /** * Opens a connection to the server specified by the given key and target. * * @param string $key * The database connection key, as specified in settings.php. The default is * "default". * @param string $target * The database target to open. * * @throws \Drupal\Core\Database\ConnectionNotDefinedException * @throws \Drupal\Core\Database\DriverNotSpecifiedException */
$this->assertSame($db1$db2, 'Both targets refer to the same connection.');
  }

  /** * Tests the closing of a database connection. */
  public function testConnectionClosing() {
    // Open the default target so we have an object to compare.     $db1 = Database::getConnection('default', 'default');

    // Try to close the default connection, then open a new one.     Database::closeConnection('default', 'default');
    $db2 = Database::getConnection('default', 'default');

    // Opening a connection after closing it should yield an object different than the original.     $this->assertNotSame($db1$db2, 'Opening the default connection after it is closed returns a new object.');
  }

  /** * Tests the connection options of the active database. */
  public function testConnectionOptions() {
    $connection_info = Database::getConnectionInfo('default');

    
    // the test.     $connection_info = Database::getConnectionInfo();
    $driver_test_connection = $connection_info['default'];
    // We have asserted that the isolation level was not set.     unset($driver_test_connection['isolation_level']);
    unset($driver_test_connection['init_commands']);

    Database::renameConnection('default', 'original_database_connection');
    Database::addConnectionInfo('default', 'default', $driver_test_connection);
    // Close and reopen the database connection, so the database init commands     // get executed.     Database::closeConnection('default', 'default');
    $connection = Database::getConnection('default', 'default');

    $query = 'SELECT @@SESSION.tx_isolation';
    // The database variable "tx_isolation" has been removed in MySQL v8.0 and     // has been replaced by "transaction_isolation".     // @see https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_tx_isolation     if (!$connection->isMariaDb() && version_compare($connection->version(), '8.0.0-AnyName', '>')) {
      $query = 'SELECT @@SESSION.transaction_isolation';
    }

    // Test that transaction level is REPEATABLE READ.
unset($connection_info['default']['database']);

        // In order to change the Database::$databaseInfo array, need to remove         // the active connection, then re-add it with the new info.         Database::removeConnection('default');
        Database::addConnectionInfo('default', 'default', $connection_info['default']);

        try {
          // Now, attempt the connection again; if it's successful, attempt to           // create the database.           Database::getConnection()->createDatabase($database);
          Database::closeConnection();

          // Now, restore the database config.           Database::removeConnection('default');
          $connection_info['default']['database'] = $database;
          Database::addConnectionInfo('default', 'default', $connection_info['default']);

          // Check the database connection.           Database::getConnection();
          $this->pass('Drupal can CONNECT to the database ok.');
        }
        catch (DatabaseNotFoundException $e) {
          
// We cannot use \Drupal::service('file_system')->getTempDirectory()         // here because we haven't yet successfully connected to the database.         $connection_info['default']['database'] = \Drupal::service('file_system')->tempnam(sys_get_temp_dir(), 'sqlite');

        // In order to change the Database::$databaseInfo array, need to remove         // the active connection, then re-add it with the new info.         Database::removeConnection('default');
        Database::addConnectionInfo('default', 'default', $connection_info['default']);

        try {
          Database::getConnection()->createDatabase($database);
          Database::closeConnection();

          // Now, restore the database config.           Database::removeConnection('default');
          $connection_info['default']['database'] = $database;
          Database::addConnectionInfo('default', 'default', $connection_info['default']);

          // Check the database connection.           Database::getConnection();
          $this->pass('Drupal can CONNECT to the database ok.');
        }
        catch (DatabaseNotFoundException $e) {
          
public function testConnectionFailureLogging() {
    $this->installSchema('dblog', ['watchdog']);

    // MySQL errors like "1153 - Got a packet bigger than 'max_allowed_packet'     // bytes" or "1100 - Table 'xyz' was not locked with LOCK TABLES" lead to a     // database connection unusable for further requests. All further request     // will result in a "2006 - MySQL server had gone away" error. As a     // consequence it's impossible to use this connection to log the causing     // initial error itself. Using Database::closeConnection() we simulate such     // a corrupted connection. In this case dblog has to establish a different     // connection by itself to be able to write the log entry.     Database::closeConnection();

    // Create a log entry.     $this->container->get('logger.factory')->get('php')->error('testConnectionFailureLogging');

    // Re-establish the default database connection.     $database = Database::getConnection();

    $query = $database->select('watchdog')
      ->condition('message', 'testConnectionFailureLogging');
    $query->addExpression('MAX([wid])');
    $wid = $query->execute()->fetchField();
    
unset($connection_info['default']['database']);

        // In order to change the Database::$databaseInfo array, need to remove         // the active connection, then re-add it with the new info.         Database::removeConnection('default');
        Database::addConnectionInfo('default', 'default', $connection_info['default']);

        try {
          // Now, attempt the connection again; if it's successful, attempt to           // create the database.           Database::getConnection()->createDatabase($database);
          Database::closeConnection();

          // Now, restore the database config.           Database::removeConnection('default');
          $connection_info['default']['database'] = $database;
          Database::addConnectionInfo('default', 'default', $connection_info['default']);

          // Check the database connection.           Database::getConnection();
          $this->pass('Drupal can CONNECT to the database ok.');
        }
        catch (DatabaseNotFoundException $e) {
          
$this->markTestSkipped('The configured max_allowed_packet exceeds the php memory limit. Therefore the test is skipped.');
    }

    $long_name = str_repeat('a', $max_allowed_packet + 1);
    try {
      $this->connection->query('SELECT [name] FROM {test} WHERE [name] = :name', [':name' => $long_name]);
      $this->fail("An exception should be thrown for queries larger than 'max_allowed_packet'");
    }
    catch (DatabaseException $e) {
      // Close and re-open the connection. Otherwise we will run into error       // 2006 "MySQL server had gone away" afterwards.       Database::closeConnection();
      Database::getConnection();
      // Got a packet bigger than 'max_allowed_packet' bytes exception thrown.       $this->assertEquals(1153, $e->getPrevious()->errorInfo[1]);
      // 'max_allowed_packet' exception message truncated.       // Use strlen() to count the bytes exactly, not the unicode chars.       $this->assertLessThanOrEqual($max_allowed_packetstrlen($e->getMessage()));
    }
  }

}
// Get a few IDs to ensure there the clean up needs to run and there is more     // than one row.     Database::getConnection('next_id')->nextId();
    Database::getConnection('next_id')->nextId();

    // At this point the sequences table should contain unnecessary rows.     $count = $this->connection->select('sequences')->countQuery()->execute()->fetchField();
    $this->assertGreaterThan(1, $count);

    // Close the connection.     Database::closeConnection('next_id');

    // Test that \Drupal\mysql\Driver\Database\mysql\Connection::__destruct()     // successfully trims the sequences table if the connection is closed.     $count = $this->connection->select('sequences')->countQuery()->execute()->fetchField();
    $this->assertEquals(1, $count);
  }

}
    // the test.     $connection_info = Database::getConnectionInfo();
    $driver_test_connection = $connection_info['default'];
    // We have asserted that the isolation level was set to 'READ COMMITTED'.     $driver_test_connection['isolation_level'] = 'READ COMMITTED';
    unset($driver_test_connection['init_commands']);

    Database::renameConnection('default', 'original_database_connection');
    Database::addConnectionInfo('default', 'default', $driver_test_connection);
    // Close and reopen the database connection, so the database init commands     // get executed.     Database::closeConnection('default', 'default');
    $connection = Database::getConnection('default', 'default');

    $query = 'SELECT @@SESSION.tx_isolation';
    // The database variable "tx_isolation" has been removed in MySQL v8.0 and     // has been replaced by "transaction_isolation".     // @see https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_tx_isolation     if (!$connection->isMariaDb() && version_compare($connection->version(), '8.0.0-AnyName', '>')) {
      $query = 'SELECT @@SESSION.transaction_isolation';
    }

    // Test that transaction level is READ-COMMITTED.
Home | Imprint | This part of the site doesn't use cookies.