addConnectionInfo example

$this->assertStringNotContainsString("'isolation_level' => 'REPEATABLE READ'", $contents);

    // Change the default database connection to use the isolation level from     // 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';
    }

  public function testPrepareStatementFailOnPreparation() {
    $connection_info = Database::getConnectionInfo('default');
    $connection_info['default']['pdo'][\PDO::ATTR_EMULATE_PREPARES] = FALSE;
    Database::addConnectionInfo('default', 'foo', $connection_info['default']);
    $foo_connection = Database::getConnection('foo', 'default');
    $this->expectException(DatabaseExceptionWrapper::class);
    $stmt = $foo_connection->prepareStatement('bananas', []);
  }

  /** * Tests Connection::prepareStatement exception on execution. */
  public function testPrepareStatementFailOnExecution() {
    $this->expectException(\PDOException::class);
    $stmt = $this->connection->prepareStatement('bananas', []);
    

  protected function setUpDatabase(array $database_info) {
    // If there is no explicit database configuration at all, fall back to a     // connection named 'migrate'.     $key = $database_info['key'] ?? 'migrate';
    $target = $database_info['target'] ?? 'default';
    if (isset($database_info['database'])) {
      Database::addConnectionInfo($key$target$database_info['database']);
    }
    try {
      $connection = Database::getConnection($target$key);
    }
    catch (ConnectionNotDefinedException $e) {
      // If we fell back to the magic 'migrate' connection and it doesn't exist,       // treat the lack of the connection as a RequirementsException.       if ($key == 'migrate') {
        throw new RequirementsException("No database connection configured for source plugin " . $this->pluginId, [], 0, $e);
      }
      else {
        
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');
      foreach ($connection_info as $target => $value) {
        // Replace the full table prefix definition to ensure that no table
    $this->assertStringContainsString("'isolation_level' => 'READ COMMITTED',", $contents);

    // Change the default database connection to use the isolation level from     // 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';
    }

class DbCommandBaseTest extends KernelTestBase {

  /** * Tests specifying a database key. */
  public function testSpecifyDatabaseKey() {
    $command = new DbCommandBaseTester();
    $command_tester = new CommandTester($command);

    Database::addConnectionInfo('magic_db', 'default', Database::getConnectionInfo('default')['default']);

    $command_tester->execute([
      '--database' => 'magic_db',
    ]);
    $this->assertEquals('magic_db', $command->getDatabaseConnection($command_tester->getInput())->getKey(),
       'Special db key is returned');
  }

  /** * Invalid database names will throw a useful exception. */
  
/** * Gets the database connection for the source Drupal database. * * @param array $database * Database array representing the source Drupal database. * * @return \Drupal\Core\Database\Connection * The database connection for the source Drupal database. */
  protected function getConnection(array $database) {
    // Set up the connection.     Database::addConnectionInfo('upgrade', 'default', $database);
    $connection = Database::getConnection('default', 'upgrade');
    return $connection;
  }

  /** * Gets the system data from the system table of the source Drupal database. * * @param \Drupal\Core\Database\Connection $connection * Database connection to the source Drupal database. * * @return array * The system data from the system table of the source Drupal database. */

  final public static function setMultipleConnectionInfo(array $databases$class_loader = NULL, $app_root = NULL) {
    foreach ($databases as $key => $targets) {
      foreach ($targets as $target => $info) {
        self::addConnectionInfo($key$target$info$class_loader$app_root);
      }
    }
  }

  /** * Rename a connection and its corresponding connection information. * * @param string $old_key * The old connection key. * @param string $new_key * The new connection key. * * @return bool * TRUE in case of success, FALSE otherwise. */

  protected function addTestDatabase($db_prefix) {
    $database = Database::convertDbUrlToConnectionInfo(getenv('SIMPLETEST_DB')$this->root);
    $database['prefix'] = $db_prefix;
    $target = __CLASS__ . $db_prefix;
    Database::addConnectionInfo($target, 'default', $database);
    return $target;
  }

  /** * Gets the lock file path. * * @param string $db_prefix * The prefix of the installed test site. * * @return string * The lock file path. */
// Assert that the module "driver_test" has been installed.     $this->assertEquals(\Drupal::service('module_handler')->getModule('driver_test')new Extension($this->root, 'module', 'core/modules/system/tests/modules/driver_test/driver_test.info.yml'));

    // Change the default database connection to use the database driver from     // the module "driver_test".     $connection_info = Database::getConnectionInfo();
    $driver_test_connection = $connection_info['default'];
    $driver_test_connection['driver'] = $this->testDriverName;
    $driver_test_connection['namespace'] = 'Drupal\\driver_test\\Driver\\Database\\' . $this->testDriverName;
    $driver_test_connection['autoload'] = "core/modules/system/tests/modules/driver_test/src/Driver/Database/{$this->testDriverName}/";
    Database::renameConnection('default', 'original_database_connection');
    Database::addConnectionInfo('default', 'default', $driver_test_connection);

    // The module "driver_test" should not be uninstallable, because it is     // providing the database driver.     try {
      $this->container->get('module_installer')->uninstall(['driver_test']);
      $this->fail('Uninstalled driver_test module.');
    }
    catch (ModuleUninstallValidatorException $e) {
      $this->assertStringContainsString("The module 'Contrib database driver test' is providing the database driver '{$this->testDriverName}'.", $e->getMessage());
    }

    

class LogTest extends UnitTestCase {

  /** * Tests that a log called by a custom database driver returns proper caller. * * @covers ::findCaller */
  public function testContribDriverLog() {
    Database::addConnectionInfo('default', 'default', [
      'driver' => 'test',
      'namespace' => 'Drupal\Tests\Core\Database\Stub',
    ]);

    $this->expectDeprecation('Drupal\Core\Database\Log::findCaller() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use Connection::findCallerFromDebugBacktrace(). See https://www.drupal.org/node/3328053');
    $this->expectDeprecation('Drupal\Core\Database\Log::getDebugBacktrace() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. There is no replacement. See https://www.drupal.org/node/3328053');
    $this->expectDeprecation('Drupal\Core\Database\Log::removeDatabaseEntries() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use Connection::removeDatabaseEntriesFromDebugBacktrace(). See https://www.drupal.org/node/3328053');
    $pdo = $this->prophesize(StubPDO::class)->reveal();
    $result = (new StubConnection($pdo[]))->testLogCaller();
    $this->assertSame([
      'file' => __FILE__,
      
'foo/bar/baz', 'bar2', "Missing scheme in URL 'foo/bar/baz'"],
      ['foo://bar:baz@test1', 'test2', "Can not convert 'foo://bar:baz@test1' to a database connection, class 'Drupal\\Driver\\Database\\foo\\Connection' does not exist"],
    ];
  }

  /** * @covers ::getConnectionInfoAsUrl * * @dataProvider providerGetConnectionInfoAsUrl */
  public function testGetConnectionInfoAsUrl(array $info$expected_url) {
    Database::addConnectionInfo('default', 'default', $info);
    $url = Database::getConnectionInfoAsUrl();
    $this->assertEquals($expected_url$url);
  }

  /** * Data provider for testGetConnectionInfoAsUrl(). * * @return array * Array of arrays with the following elements: * - An array mocking the database connection info. Possible keys are * database, username, password, prefix, host, port, namespace and driver. * - The expected URL after conversion. */
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;
          Database::addConnectionInfo('default', 'default', $connection_info['default']);

          
protected Connection $testingFakeConnection;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    // Create a connection to the non-public schema.     $info = Database::getConnectionInfo('default');
    $info['default']['schema'] = 'testing_fake';
    Database::addConnectionInfo('default', 'testing_fake', $info['default']);

    $this->testingFakeConnection = Database::getConnection('testing_fake', 'default');

    $table_specification = [
      'description' => 'Schema table description may contain "quotes" and could be long—very long indeed.',
      'fields' => [
        'id'  => [
          'type' => 'serial',
          'not null' => TRUE,
        ],
        'test_field'  => [
          
// 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;
        }
      }
Home | Imprint | This part of the site doesn't use cookies.