getConnectionOptions example

protected static $modules = ['migrate'];

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $this->createMigrationConnection();
    $this->sourceDatabase = Database::getConnection('default', 'migrate');
    // Attach the original test prefix as a database, for SQLite to attach its     // database file.     $this->sourceDatabase->attachDatabase(substr($this->sourceDatabase->getConnectionOptions()['prefix'], 0, -1));
  }

  /** * Changes the database connection to the prefixed one. * * @todo Remove when we don't use global. https://www.drupal.org/node/2552791 */
  private function createMigrationConnection() {
    // If the backup already exists, something went terribly wrong.     // This case is possible, because database connection info is a static     // global state construct on the Database class, which at least persists
    // have been returned at the same point within a monolithic query. If we     // join to the map table, the first batch is writing to the map table and     // thus affecting the results of subsequent batches. To be safe, we avoid     // joining to the map table when batching.     if ($this->batchSize > 0) {
      return FALSE;
    }
    $id_map = $this->migration->getIdMap();
    if (!$id_map instanceof Sql) {
      return FALSE;
    }
    $id_map_database_options = $id_map->getDatabase()->getConnectionOptions();
    $source_database_options = $this->getDatabase()->getConnectionOptions();

    // Special handling for sqlite which deals with files.     if ($id_map_database_options['driver'] === 'sqlite' &&
      $source_database_options['driver'] === 'sqlite' &&
      $id_map_database_options['database'] != $source_database_options['database']
    ) {
      return FALSE;
    }

    // FALSE if driver is PostgreSQL and database doesn't match.


  /** * Get a fully qualified table name. * * @param string $table * The name of the table in question. * * @return string */
  public function getFullQualifiedTableName($table) {
    $options = $this->getConnectionOptions();
    $prefix = $this->getPrefix();
    return $options['database'] . '.' . $prefix . $table;
  }

  /** * Returns a prepared statement given a SQL string. * * This method caches prepared statements, reusing them when possible. It also * prefixes tables names enclosed in curly braces and, optionally, quotes * identifiers enclosed in square brackets. * * @param string $query * The query string as SQL, with curly braces surrounding the table names, * and square brackets surrounding identifiers. * @param array $options * An associative array of options to control how the query is run. See * the documentation for self::defaultOptions() for details. The content of * the 'pdo' key will be passed to the prepared statement. * @param bool $allow_row_count * (optional) A flag indicating if row count is allowed on the statement * object. Defaults to FALSE. * * @return \Drupal\Core\Database\StatementInterface * A prepared statement ready for its execute() method. * * @throws \InvalidArgumentException * If multiple statements are included in the string, and delimiters are * not allowed in the query. * @throws \Drupal\Core\Database\DatabaseExceptionWrapper */
    $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();

    $this->query("SELECT pg_advisory_unlock(" . self::POSTGRESQL_NEXTID_LOCK . ")");

    return $id;
  }

  /** * {@inheritdoc} */
  public function getFullQualifiedTableName($table) {
    $options = $this->getConnectionOptions();
    $schema = $options['schema'] ?? 'public';

    // The fully qualified table name in PostgreSQL is in the form of     // <database>.<schema>.<table>.     return $options['database'] . '.' . $schema . '.' . $this->getPrefix() . $table;
  }

  /** * Add a new savepoint with a unique name. * * The main use for this method is to mimic InnoDB functionality, which * provides an inherent savepoint before any query in a transaction. * * @param $savepoint_name * A string representing the savepoint name. By default, * "mimic_implicit_commit" is used. * * @see Drupal\Core\Database\Connection::pushTransaction() */

          ],
        ],
      ],
    ], vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure());
  }

  /** * @covers ::getDatabaseConnectionInfo */
  public function testGetDatabaseConnectionInfoWithOutManualSetDbUrl() {
    $options = $this->container->get('database')->getConnectionOptions();
    $this->assertSame($this->databasePrefix, $options['prefix']);
  }

  /** * @covers ::setUp */
  public function testSetUp() {
    $this->assertTrue($this->container->has('request_stack'));
    $this->assertTrue($this->container->initialized('request_stack'));
    $request = $this->container->get('request_stack')->getCurrentRequest();
    $this->assertNotEmpty($request);
    
/** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    /** @var \Drupal\Core\Database\Connection $connection */
    $this->connection = \Drupal::service('database');
    if ($this->connection->databaseType() == 'pgsql') {
      $this->databaseName = 'public';
    }
    else {
      $this->databaseName = $this->connection->getConnectionOptions()['database'];
    }
  }

  /** * {@inheritdoc} */
  protected function setDatabaseDumpFiles() {
    $this->databaseDumpFiles = [
      // Start with a standard install of Drupal 9.3.0 with the following       // enabled modules: forum, language, locale, statistics and tracker.       DRUPAL_ROOT . '/core/modules/system/tests/fixtures/update/drupal-9.4.0.filled.standard.php.gz',
      
    $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');

    // Be sure we're connected to the default database.     $db = Database::getConnection('default', 'default');
    $connectionOptions = $db->getConnectionOptions();

    // In the MySQL driver, the port can be different, so check individual     // options.     $this->assertEquals($connection_info['default']['driver']$connectionOptions['driver'], 'The default connection info driver matches the current connection options driver.');
    $this->assertEquals($connection_info['default']['database']$connectionOptions['database'], 'The default connection info database matches the current connection options database.');

    // Set up identical replica and confirm connection options are identical.     Database::addConnectionInfo('default', 'replica', $connection_info['default']);
    $db2 = Database::getConnection('replica', 'default');
    // Getting a driver class ensures the namespace option is set.     $this->assertEquals($db->getDriverClass('Select')$db2->getDriverClass('Select'));
    

  protected $tempNamespaceName;

  /** * {@inheritdoc} */
  public function __construct($connection) {
    parent::__construct($connection);

    // If the schema is not set in the connection options then schema defaults     // to public.     $this->defaultSchema = $connection->getConnectionOptions()['schema'] ?? 'public';
  }

  /** * Make sure to limit identifiers according to PostgreSQL compiled in length. * * PostgreSQL allows in standard configuration identifiers no longer than 63 * chars for table/relation names, indexes, primary keys, and constraints. So * we map all identifiers that are too long to drupal_base64hash_tag, where * tag is one of: * - idx for indexes * - key for constraints * - pkey for primary keys * - seq for sequences * * @param string $table_identifier_part * The first argument used to build the identifier string. This usually * refers to a table/relation name. * @param string $column_identifier_part * The second argument used to build the identifier string. This usually * refers to one or more column names. * @param string $tag * The identifier tag. It can be one of 'idx', 'key', 'pkey' or 'seq'. * @param string $separator * (optional) The separator used to glue together the aforementioned * identifier parts. Defaults to '__'. * * @return string * The index/constraint/pkey identifier. */
/** * Check Binary Output. * * Unserializing does not work on Postgresql 9 when bytea_output is 'hex'. */
  public function checkBinaryOutput() {
    $database_connection = Database::getConnection();
    if (!$this->checkBinaryOutputSuccess()) {
      // First try to alter the database. If it fails, raise an error telling       // the user to do it themselves.       $connection_options = $database_connection->getConnectionOptions();
      // It is safe to include the database name directly here, because this       // code is only called when a connection to the database is already       // established, thus the database name is guaranteed to be a correct       // value.       $query = "ALTER DATABASE \"{$connection_options['database']}\" SET bytea_output = 'escape';";
      try {
        $database_connection->query($query);
      }
      catch (\Exception $e) {
        // Ignore possible errors when the user doesn't have the necessary         // privileges to ALTER the database.
->condition('name', 'file_private_path')
      ->execute();
    $this->sourceDatabase->update('variable')
      ->fields(['value' => serialize($file_public_path)])
      ->condition('name', 'file_public_path')
      ->execute();
    $this->sourceDatabase->update('variable')
      ->fields(['value' => serialize($file_temporary_path)])
      ->condition('name', 'file_temporary_path')
      ->execute();

    $connection_options = $this->sourceDatabase->getConnectionOptions();
    $driver = $connection_options['driver'];

    // Use the driver connection form to get the correct options out of the     // database settings. This supports all of the databases we test against.     $drivers = drupal_get_database_types();
    $form = $drivers[$driver]->getFormOptions($connection_options);
    $connection_options = array_intersect_key($connection_options$form + $form['advanced_options']);
    // Remove isolation_level since that option is not configurable in the UI.     unset($connection_options['isolation_level']);
    $edit = [
      $driver => $connection_options,
      

  protected function getFieldOrder(Connection $connection$table) {
    // @todo this is MySQL only since there are no Database API functions for     // table column data.     // @todo this code is duplicated in `core/scripts/migrate-db.sh`.     $connection_info = $connection->getConnectionOptions();
    // Order by primary keys.     $order = '';
    $query = "SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE (`TABLE_SCHEMA` = '" . $connection_info['database'] . "') AND (`TABLE_NAME` = '{" . $table . "}') AND (`COLUMN_KEY` = 'PRI') ORDER BY COLUMN_NAME";
    $results = $connection->query($query);
    while (($row = $results->fetchAssoc()) !== FALSE) {
      $order .= $row['COLUMN_NAME'] . ', ';
    }
    if (!empty($order)) {
      
$this->expectExceptionMessage('\Drupal\Core\Database\Connection::$identifierQuotes must contain 2 string values');
    $mock_pdo = $this->createMock(StubPDO::class);
    new StubConnection($mock_pdo[][0, '1']);
  }

  /** * @covers ::__construct */
  public function testNamespaceDefault() {
    $mock_pdo = $this->createMock(StubPDO::class);
    $connection = new StubConnection($mock_pdo[]);
    $this->assertSame('Drupal\Tests\Core\Database\Stub', $connection->getConnectionOptions()['namespace']);
  }

  /** * Test rtrim() of query strings. * * @dataProvider provideQueriesToTrim */
  public function testQueryTrim($expected$query$options) {
    $mock_pdo = $this->getMockBuilder(StubPdo::class)->getMock();
    $connection = new StubConnection($mock_pdo[]);

    

  protected function buildTableNameCondition($table_name$operator = '=', $add_prefix = TRUE) {
    $info = $this->connection->getConnectionOptions();

    // Retrieve the table name and schema     $table_info = $this->getPrefixInfo($table_name$add_prefix);

    $condition = $this->connection->condition('AND');
    $condition->condition('table_catalog', $info['database']);
    $condition->condition('table_schema', $table_info['schema']);
    $condition->condition('table_name', $table_info['table']$operator);
    return $condition;
  }

  

  protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
    $info = ['prefix' => $this->connection->getPrefix()];
    if ($add_prefix) {
      $table = $info['prefix'] . $table;
    }
    if (($pos = strpos($table, '.')) !== FALSE) {
      $info['database'] = substr($table, 0, $pos);
      $info['table'] = substr($table, ++$pos);
    }
    else {
      $info['database'] = $this->connection->getConnectionOptions()['database'];
      $info['table'] = $table;
    }
    return $info;
  }

  /** * Build a condition to match a table name against a standard information_schema. * * MySQL uses databases like schemas rather than catalogs so when we build * a condition to query the information_schema.tables, we set the default * database as the schema unless specified otherwise, and exclude table_catalog * from the condition criteria. */

  protected function getCredentials() {
    $connection_options = $this->sourceDatabase->getConnectionOptions();
    $version = $this->getLegacyDrupalVersion($this->sourceDatabase);
    $driver = $connection_options['driver'];

    // Use the driver connection form to get the correct options out of the     // database settings. This supports all of the databases we test against.     $drivers = drupal_get_database_types();
    $form = $drivers[$driver]->getFormOptions($connection_options);
    $connection_options = array_intersect_key($connection_options$form + $form['advanced_options']);
    // Remove isolation_level since that option is not configurable in the UI.     unset($connection_options['isolation_level']);
    $edit = [
      
Home | Imprint | This part of the site doesn't use cookies.