removeConnection example

parent::tearDown();
    $this->collectMessages = FALSE;
    unset($this->migration, $this->migrateMessages);
  }

  /** * Cleans up the test migrate connection. * * @todo Remove when we don't use global. https://www.drupal.org/node/2552791 */
  private function cleanupMigrateConnection() {
    Database::removeConnection('migrate');
    $original_connection_info = Database::getConnectionInfo('simpletest_original_migrate');
    if ($original_connection_info) {
      Database::renameConnection('simpletest_original_migrate', 'migrate');
    }
  }

  /** * Prepare any dependent migrations. * * @param array $id_mappings * A list of ID mappings keyed by migration IDs. Each ID mapping is a list * of two arrays, the first are source IDs and the second are destination * IDs. */
      // additional tables.       $connection_info['prefix'] = $prefix . '0';
    }

    Database::addConnectionInfo('migrate_drupal_ui', 'default', $connection_info);
  }

  /** * {@inheritdoc} */
  protected function tearDown(): void {
    Database::removeConnection('migrate_drupal_ui');
    parent::tearDown();
  }

  /** * Gets the source base path for the concrete test. * * @return string * The source base path. */
  abstract protected function getSourceBasePath();

  
'hash_salt' => static::class,
      'file_public_path' => $this->siteDirectory . '/files',
      // Disable Twig template caching/dumping.       'twig_cache' => FALSE,
      // @see \Drupal\KernelTests\KernelTestBase::register()     ];
    new Settings($settings);

    $this->setUpFilesystem();

    foreach (Database::getAllConnectionInfo() as $key => $targets) {
      Database::removeConnection($key);
    }
    Database::addConnectionInfo('default', 'default', $this->getDatabaseConnectionInfo()['default']);
  }

  /** * Sets up the filesystem, so things like the file directory. */
  protected function setUpFilesystem() {
    $test_db = new TestDatabase($this->databasePrefix);
    $test_site_path = $test_db->getTestSitePath();

    
// This while loop holds the parent process until all the child threads     // are complete - at which point the script continues to execute.     while (pcntl_waitpid(0, $status) != -1);

    foreach ($directories as $directory) {
      $this->assertDirectoryExists($directory);
    }

    // Remove the database connection because it will have been destroyed when     // the forks exited. This allows     // \Drupal\KernelTests\KernelTestBase::tearDown() to reopen it.     Database::removeConnection('default');
  }

}
protected function installParameters() {
    $parameters = $this->installParametersTrait();
    $parameters['parameters']['langcode'] = $this->langcode;
    return $parameters;
  }

  /** * {@inheritdoc} */
  protected function changeDatabasePrefix() {
    // Ensure that we use the database from SIMPLETEST_DB environment variable.     Database::removeConnection('default');
    $this->changeDatabasePrefixTrait();
  }

  /** * {@inheritdoc} */
  protected function prepareDatabasePrefix() {
    // Override this method so that we can force a lock to be created.     $test_db = new TestDatabase(NULL, TRUE);
    $this->siteDirectory = $test_db->getTestSitePath();
    $this->databasePrefix = $test_db->getDatabasePrefix();
  }
catch (\Exception $e) {
        // Detect utf8mb4 incompatibility.         if ($e->getCode() == Connection::UNSUPPORTED_CHARSET || ($e->getCode() == Connection::SQLSTATE_SYNTAX_ERROR && $e->errorInfo[1] == Connection::UNKNOWN_CHARSET)) {
          $this->fail(t('Your MySQL server and PHP MySQL driver must support utf8mb4 character encoding. Make sure to use a database system that supports this (such as MySQL/MariaDB/Percona 5.5.3 and up), and that the utf8mb4 character set is compiled in. See the <a href=":documentation" target="_blank">MySQL documentation</a> for more information.', [':documentation' => 'https://dev.mysql.com/doc/refman/5.0/en/cannot-initialize-character-set.html']));
          $info = Database::getConnectionInfo();
          $info_copy = $info;
          // Set a flag to fall back to utf8. Note: this flag should only be           // used here and is for internal use only.           $info_copy['default']['_dsn_utf8_fallback'] = TRUE;
          // In order to change the Database::$databaseInfo array, we need to           // remove the active connection, then re-add it with the new info.           Database::removeConnection('default');
          Database::addConnectionInfo('default', 'default', $info_copy['default']);
          // Connect with the new database info, using the utf8 character set so           // that we can run the checkEngineVersion test.           Database::getConnection();
          // Revert to the old settings.           Database::removeConnection('default');
          Database::addConnectionInfo('default', 'default', $info['default']);
        }
        else {
          // Rethrow the exception.           throw $e;
        }
/** * Tests supplying database connection as a URL. */
  public function testSpecifyDbUrl() {
    $command = new DbCommandBaseTester();
    $command_tester = new CommandTester($command);
    $command_tester->execute([
      '-db-url' => Database::getConnectionInfoAsUrl(),
    ]);
    $this->assertEquals('db-tools', $command->getDatabaseConnection($command_tester->getInput())->getKey());

    Database::removeConnection('db-tools');
    $command_tester->execute([
      '--database-url' => Database::getConnectionInfoAsUrl(),
    ]);
    $this->assertEquals('db-tools', $command->getDatabaseConnection($command_tester->getInput())->getKey());
  }

  /** * Tests specifying a prefix for different connections. */
  public function testPrefix() {
    if (Database::getConnection()->driver() == 'sqlite') {
      

    catch (\Exception $e) {
      // Attempt to create the database if it is not found.       if ($e instanceof DatabaseNotFoundException) {
        // Remove the database string from connection info.         $connection_info = Database::getConnectionInfo();
        $database = $connection_info['default']['database'];
        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;
          
// We overwrite this function because the regular teardown will not drop the     // tables from a specified schema.     $tables = $this->testingFakeConnection->schema()->findTables('%');
    foreach ($tables as $table) {
      if ($this->testingFakeConnection->schema()->dropTable($table)) {
        unset($tables[$table]);
      }
    }

    $this->assertEmpty($this->testingFakeConnection->schema()->findTables('%'));

    Database::removeConnection('testing_fake');

    parent::tearDown();
  }

  /** * @covers ::extensionExists * @covers ::tableExists */
  public function testExtensionExists(): void {
    // Check if PG_trgm extension is present.     $this->assertTrue($this->testingFakeConnection->schema()->extensionExists('pg_trgm'));
    
if (!function_exists('pcntl_fork')) {
      $this->markTestSkipped('Requires the pcntl_fork() function');
    }

    $functions = [];
    for ($i = 1; $i <= 10; $i++) {
      $functions[] = 'set';
      $functions[] = 'getAll';
    }

    $default_connection = Database::getConnectionInfo();
    Database::removeConnection('default');

    $time_to_start = microtime(TRUE) + 0.1;

    // This loop creates a new fork to set or get key values keys.     foreach ($functions as $i => $function) {
      $pid = pcntl_fork();
      if ($pid == -1) {
        $this->fail("Error forking");
      }
      elseif ($pid == 0) {
        Database::addConnectionInfo('default' . $i, 'default', $default_connection['default']);
        

  protected function changeDatabasePrefix() {
    if (empty($this->databasePrefix)) {
      $this->prepareDatabasePrefix();
    }

    // If the test is run with argument dburl then use it.     $db_url = getenv('SIMPLETEST_DB');
    if (!empty($db_url)) {
      // Ensure no existing database gets in the way. If a default database       // exists already it must be removed.       Database::removeConnection('default');
      $database = Database::convertDbUrlToConnectionInfo($db_url$this->root ?? DRUPAL_ROOT, TRUE);
      Database::addConnectionInfo('default', 'default', $database);
    }

    // Clone the current connection and replace the current prefix.     $connection_info = Database::getConnectionInfo('default');
    if (is_null($connection_info)) {
      throw new \InvalidArgumentException('There is no database connection so no tests can be run. You must provide a SIMPLETEST_DB environment variable to run PHPUnit based functional tests outside of run-tests.sh.');
    }
    else {
      Database::renameConnection('default', 'simpletest_original_default');
      
/** * Execute the non-interactive installer. * * @see install_drupal() */
  protected function doInstall() {
    require_once DRUPAL_ROOT . '/core/includes/install.core.inc';
    $parameters = $this->installParameters();
    // Simulate a real install which does not start with the any connections set     // in \Drupal\Core\Database\Database::$connections.     Database::removeConnection('default');
    install_drupal($this->classLoader, $parameters);
  }

  /** * Initialize settings created during install. */
  protected function initSettings() {
    Settings::initialize(DRUPAL_ROOT, $this->siteDirectory, $this->classLoader);

    // After writing settings.php, the installer removes write permissions     // from the site directory. To allow drupal_generate_test_ua() to write
      if ($e->getCode() == Connection::DATABASE_NOT_FOUND) {
        // Remove the database string from connection info.         $connection_info = Database::getConnectionInfo();
        $database = $connection_info['default']['database'];

        // 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']);

          
$extra_info = Database::getConnectionInfo('extra');
    $this->assertSame('foobar', $extra_info['default']['database']);
    $db2_schema = $db2_connection->schema();
    $db2_info = $method->invoke($db2_schema);

    // Each target connection has a different database.     $this->assertNotSame($db2_info['database']$db1_info['database']);
    // The new profile has a different database.     $this->assertSame('foobar', $db2_info['database']);

    Database::removeConnection('extra');
  }

}
$connection_info['default']['pdo'][\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_SILENT;
    Database::addConnectionInfo('test', 'default', $connection_info['default']);
    $test_connection = Database::getConnection('default', 'test');

    $reflection = new \ReflectionObject($test_connection);
    $connection_property = $reflection->getProperty('connection');
    $error_mode = $connection_property->getValue($test_connection)
      ->getAttribute(\PDO::ATTR_ERRMODE);
    // Ensure PDO connection options can be overridden.     $this->assertSame(\PDO::ERRMODE_SILENT, $error_mode);

    Database::removeConnection('test');
  }

}
Home | Imprint | This part of the site doesn't use cookies.