getConnectionInfo example


  protected int $id;

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

    // Create an additional connection to monitor the connections being opened     // and closed in this test.     $connection_info = Database::getConnectionInfo();
    Database::addConnectionInfo('default', 'monitor', $connection_info['default']);
    $this->monitor = Database::getConnection('monitor');

    // Add a new target to the connection, by cloning the current connection.     $connection_info = Database::getConnectionInfo();
    Database::addConnectionInfo('default', static::TEST_TARGET_CONNECTION, $connection_info['default']);

    // Verify that the new target exists.     $info = Database::getConnectionInfo();

    // New connection info found.

  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,
        ],
        // "driver_test".         $driver = 'Drivertest' . ucfirst($database['driver']);
        $database['driver'] = $driver;
        $database['namespace'] = 'Drupal\\driver_test\\Driver\\Database\\' . $driver;
        $database['autoload'] = "core/modules/system/tests/modules/driver_test/src/Driver/Database/$driver/";
      }

      Database::addConnectionInfo('default', 'default', $database);
    }

    // Clone the current connection and replace the current prefix.     $connection_info = Database::getConnectionInfo('default');
    if (!empty($connection_info)) {
      Database::renameConnection('default', 'simpletest_original_default');
      foreach ($connection_info as $target => $value) {
        // Replace the table prefix definition to ensure that no table of the         // test runner leak into the test.         $connection_info[$target]['prefix'] = $this->databasePrefix;
      }
    }
    return $connection_info;
  }

  
public function testConcurrent() {
    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) {
        
$drivers = drupal_get_database_types();
    $drivers_keys = array_keys($drivers);

    // Unless there is input for this form (for a non-interactive installation,     // input originates from the $settings array passed into install_drupal()),     // check whether database connection settings have been prepared in     // settings.php already.     // Note: The installer even executes this form if there is a valid database     // connection already, since the submit handler of this form is responsible     // for writing all $settings to settings.php (not limited to $databases).     $input = &$form_state->getUserInput();
    if (!isset($input['driver']) && $database = Database::getConnectionInfo()) {
      $input['driver'] = $database['default']['driver'];
      $input[$database['default']['driver']] = $database['default'];
    }

    if (isset($input['driver'])) {
      $default_driver = $input['driver'];
      // In case of database connection info from settings.php, as well as for a       // programmed form submission (non-interactive installer), the table prefix       // information is usually normalized into an array already, but the form       // element only allows to configure one default prefix for all tables.       $prefix = &$input[$default_driver]['prefix'];
      
/** * Tests that DatabaseSchema::getPrefixInfo() returns the right database. * * We are testing if the return array of the method * \Drupal\mysql\Driver\Database\mysql\Schema::getPrefixInfo(). This return * array is a keyed array with info about amongst other things the database. * The other two by Drupal core supported databases do not have this variable * set in the return array. */
  public function testGetPrefixInfo() {
    $connection_info = Database::getConnectionInfo('default');

    // Copy the default connection info to the 'extra' key.     Database::addConnectionInfo('extra', 'default', $connection_info['default']);

    $db1_connection = Database::getConnection('default', 'default');
    $db1_schema = $db1_connection->schema();
    $db2_connection = Database::getConnection('default', 'extra');

    // Get the prefix info for the first database.     $method = new \ReflectionMethod($db1_schema, 'getPrefixInfo');
    $db1_info = $method->invoke($db1_schema);

    
parent::setUp();
    $this->installSchema('system', 'sequences');
  }

  /** * Tests that sequences table clear up works when a connection is closed. * * @see \Drupal\mysql\Driver\Database\mysql\Connection::__destruct() */
  public function testDbNextIdClosedConnection() {
    // Create an additional connection to test closing the connection.     $connection_info = Database::getConnectionInfo();
    Database::addConnectionInfo('default', 'next_id', $connection_info['default']);

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

    
try {
      // This doesn't actually test the connection.       Database::setActiveConnection();
      // Now actually do a check.       Database::getConnection();
      $this->pass('Drupal can CONNECT to the database ok.');
    }
    catch (\Exception $e) {
      // Attempt to create the database if it is not found.       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']);

        

  public static function getConnectionInfoAsUrl($key = 'default') {
    $db_info = static::getConnectionInfo($key);
    if (empty($db_info) || empty($db_info['default'])) {
      throw new \RuntimeException("Database connection $key not defined or missing the 'default' settings");
    }
    $namespace = $db_info['default']['namespace'];

    // If the driver namespace is within a Drupal module, add the module name     // to the connection options to make it easy for the connection class's     // createUrlFromConnectionOptions() method to add it to the URL.     if (static::isWithinModuleNamespace($namespace)) {
      $db_info['default']['module'] = explode('\\', $namespace)[1];
    }

    


    return $form;
  }

  /** * {@inheritdoc} */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $source_connection = $form_state->getValue('source_connection');
    if ($source_connection) {
      $info = Database::getConnectionInfo($source_connection);
      $database = reset($info);
    }
    else {
      // Retrieve the database driver from the form, use reflection to get the       // namespace, and then construct a valid database array the same as in       // settings.php.       $driver = $form_state->getValue('driver');
      $drivers = $this->getDatabaseTypes();
      $reflection = new \ReflectionClass($drivers[$driver]);
      $install_namespace = $reflection->getNamespaceName();

      
$expected = [
      $driver => [
        'driver' => $driver,
        'namespace' => $expected_namespace,
        'prefix' => '',
      ],
    ];
    if (!is_null($expected_autoload)) {
      $expected[$driver]['autoload'] = $expected_autoload;
    }
    $this->assertEquals($expected, Database::getConnectionInfo('mock'));
  }

  /** * Provides data for testDatabaseInfoInitialization(). */
  public function providerTestDatabaseInfoInitialization(): array {
    return [
      ['mysql', NULL, NULL, 'Drupal\\mysql\\Driver\\Database\\mysql', 'core/modules/mysql/src/Driver/Database/mysql/'],
      ['mysql', '', NULL, 'Drupal\\mysql\\Driver\\Database\\mysql', 'core/modules/mysql/src/Driver/Database/mysql/'],
      ['mysql', 'Drupal\\Core\\Database\\Driver\\mysql', NULL, 'Drupal\\mysql\\Driver\\Database\\mysql', 'core/modules/mysql/src/Driver/Database/mysql/'],
      ['mysql', 'Drupal\\mysql\\Driver\\Database\\mysql', NULL, 'Drupal\\mysql\\Driver\\Database\\mysql', 'core/modules/mysql/src/Driver/Database/mysql/'],
      [

  protected $defaultTheme = 'stark';

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

    // The isolation_level option is only available for MySQL.     $connection_info = Database::getConnectionInfo();
    if ($connection_info['default']['driver'] !== 'mysql') {
      $this->markTestSkipped("This test does not support the {$connection_info['default']['driver']} database driver.");
    }
  }

  /** * Verifies that the isolation_level was added to the database settings. */
  public function testInstaller() {
    $contents = file_get_contents($this->container->getParameter('app.root') . '/' . $this->siteDirectory . '/settings.php');

    
try {
      // This doesn't actually test the connection.       Database::setActiveConnection();
      // Now actually do a check.       Database::getConnection();
      $this->pass('Drupal can CONNECT to the database ok.');
    }
    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.
/** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * {@inheritdoc} */
  protected function prepareEnvironment() {
    parent::prepareEnvironment();
    // Pre-configure database credentials in settings.php.     $connection_info = Database::getConnectionInfo();
    unset($connection_info['default']['pdo']);
    unset($connection_info['default']['init_commands']);

    $this->settings['databases']['default'] = (object) [
      'value' => $connection_info,
      'required' => TRUE,
    ];
  }

  /** * {@inheritdoc} * * @todo The database settings form is not supposed to appear if settings.php * contains a valid database connection already (but e.g. no config * directories yet). */

  protected function prepareEnvironment() {
    parent::prepareEnvironment();
    // Pre-configure hash salt.     // Any string is valid, so simply use the class name of this test.     $this->settings['settings']['hash_salt'] = (object) [
      'value' => __CLASS__,
      'required' => TRUE,
    ];

    // Pre-configure database credentials.     $connection_info = Database::getConnectionInfo();
    unset($connection_info['default']['pdo']);
    unset($connection_info['default']['init_commands']);

    $this->settings['databases']['default'] = (object) [
      'value' => $connection_info,
      'required' => TRUE,
    ];

    // Use the kernel to find the site path because the site.path service should     // not be available at this point in the install process.     $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
    
Home | Imprint | This part of the site doesn't use cookies.