/** * Parse input options decide on a database. * * @param \Symfony\Component\Console\Input\InputInterface $input * Input object. * @return \Drupal\Core\Database\Connection */ protected function getDatabaseConnection(InputInterface $input) { // Load connection from a url. if ($input->getOption('database-url')) { // @todo this could probably be refactored to not use a global connection. // Ensure database connection isn't set. if (Database::getConnectionInfo('db-tools')) { throw new \RuntimeException('Database "db-tools" is already defined. Cannot define database provided.'); } $info = Database::convertDbUrlToConnectionInfo($input->getOption('database-url'), \Drupal::root()); Database::addConnectionInfo('db-tools', 'default', $info); $key = 'db-tools'; } else { $key = $input->getOption('database'); } // If they supplied a prefix, replace it in the connection information. $prefix = $input->getOption('prefix'); if ($prefix) { $info = Database::getConnectionInfo($key)['default']; $info['prefix']['default'] = $prefix; Database::removeConnection($key); Database::addConnectionInfo($key, 'default', $info); } return Database::getConnection('default', $key); }
/** * 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; }
/** * 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 // for all test methods executed in one PHP process. if (Database::getConnectionInfo('simpletest_original_migrate')) { throw new \RuntimeException("Bad Database connection state: 'simpletest_original_migrate' connection key already exists. Broken test?"); } // Clone the current connection and replace the current prefix. $connection_info = Database::getConnectionInfo('migrate'); if ($connection_info) { Database::renameConnection('migrate', 'simpletest_original_migrate'); } $connection_info = Database::getConnectionInfo('default'); foreach ($connection_info as $target => $value) { $prefix = is_array($value['prefix']) ? $value['prefix']['default'] : $value['prefix']; // Simpletest uses 7 character prefixes at most so this can't cause // collisions. $connection_info[$target]['prefix']['default'] = $prefix . '0'; // Add the original simpletest prefix so SQLite can attach its database. // @see \Drupal\Core\Database\Driver\sqlite\Connection::init() $connection_info[$target]['prefix'][$value['prefix']['default']] = $value['prefix']['default']; } Database::addConnectionInfo('migrate', 'default', $connection_info['default']); }
/** * {@inheritdoc} */ public function log($level, $message, array $context = array()) { // Remove any backtraces since they may contain an unserializable variable. unset($context['backtrace']); // Convert PSR3-style messages to SafeMarkup::format() style, so they can be // translated too in runtime. $message_placeholders = $this->parser->parseMessagePlaceholders($message, $context); try { $this->connection->insert('watchdog')->fields(array('uid' => $context['uid'], 'type' => Unicode::substr($context['channel'], 0, 64), 'message' => $message, 'variables' => serialize($message_placeholders), 'severity' => $level, 'link' => $context['link'], 'location' => $context['request_uri'], 'referer' => $context['referer'], 'hostname' => Unicode::substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp']))->execute(); } catch (\Exception $e) { // When running Drupal on MySQL or MariaDB you can run into several errors // that corrupt the database connection. Some examples for these kind of // errors on the database layer are "1100 - Table 'xyz' was not locked // with LOCK TABLES" and "1153 - Got a packet bigger than // 'max_allowed_packet' bytes". If such an error happens, the MySQL server // invalidates the connection and answers all further requests in this // connection with "2006 - MySQL server had gone away". In that case the // insert statement above results in a database exception. To ensure that // the causal error is written to the log we try once to open a dedicated // connection and write again. if (($e instanceof DatabaseException || $e instanceof \PDOException) && $this->connection->getTarget() != self::DEDICATED_DBLOG_CONNECTION_TARGET) { // Open a dedicated connection for logging. $key = $this->connection->getKey(); $info = Database::getConnectionInfo($key); Database::addConnectionInfo($key, self::DEDICATED_DBLOG_CONNECTION_TARGET, $info['default']); $this->connection = Database::getConnection(self::DEDICATED_DBLOG_CONNECTION_TARGET, $key); // Now try once to log the error again. $this->log($level, $message, $context); } else { throw $e; } } }
/** * Test different connection types. */ public function testConnectionTypes() { $sql_base = new TestSqlBase(); // Check the default values. $this->assertIdentical($sql_base->getDatabase()->getTarget(), 'default'); $this->assertIdentical($sql_base->getDatabase()->getKey(), 'migrate'); $target = 'test_db_target'; $key = 'test_migrate_connection'; $config = array('target' => $target, 'key' => $key); $sql_base->setConfiguration($config); Database::addConnectionInfo($key, $target, Database::getConnectionInfo('default')['default']); // Validate we've injected our custom key and target. $this->assertIdentical($sql_base->getDatabase()->getTarget(), $target); $this->assertIdentical($sql_base->getDatabase()->getKey(), $key); // Now test we can have SqlBase create the connection from an info array. $sql_base = new TestSqlBase(); $target = 'test_db_target2'; $key = 'test_migrate_connection2'; $database = Database::getConnectionInfo('default')['default']; $config = array('target' => $target, 'key' => $key, 'database' => $database); $sql_base->setConfiguration($config); // Call getDatabase() to get the connection defined. $sql_base->getDatabase(); // Validate the connection has been created with the right values. $this->assertIdentical(Database::getConnectionInfo($key)[$target], $database); }
/** * @covers ::convertDbUrlToConnectionInfo * * @dataProvider providerGetConnectionInfoAsUrl */ public function testGetConnectionInfoAsUrl(array $info, $expected_url) { Database::addConnectionInfo('default', 'default', $info); $url = Database::getConnectionInfoAsUrl(); // Remove the connection to not pollute subsequent datasets being tested. Database::removeConnection('default'); $this->assertEquals($expected_url, $url); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $connection_info = Database::getConnectionInfo('default'); foreach ($connection_info as $target => $value) { $connection_info[$target]['prefix'] = array('default' => $value['prefix']['default'] . '0'); } Database::addConnectionInfo('migrate', 'default', $connection_info['default']); }
/** * Test different connection types. */ public function testConnectionTypes() { $sql_base = new TestSqlBase(); $this->assertIdentical($sql_base->getDatabase()->getTarget(), 'default'); $target = 'test_db_target'; $config = array('target' => $target); $sql_base->setConfiguration($config); Database::addConnectionInfo('migrate', $target, Database::getConnectionInfo('default')['default']); $this->assertIdentical($sql_base->getDatabase()->getTarget(), $target); }
/** * Set up the relevant migrations for import from the provided database * connection. * * @param \Drupal\Core\Database\Database $database * Database array representing the source Drupal database. * @param string $source_base_path * Address of the source Drupal site (e.g., http://example.com/). * * @return array */ protected function createMigrations(array $database, $source_base_path) { // Set up the connection. Database::addConnectionInfo('upgrade', 'default', $database); $connection = Database::getConnection('default', 'upgrade'); if (!($drupal_version = $this->getLegacyDrupalVersion($connection))) { throw new \Exception($this->t('Source database does not contain a recognizable Drupal version.')); } $database_state['key'] = 'upgrade'; $database_state['database'] = $database; $database_state_key = 'migrate_upgrade_' . $drupal_version; \Drupal::state()->set($database_state_key, $database_state); $version_tag = 'Drupal ' . $drupal_version; $template_storage = \Drupal::service('migrate.template_storage'); $migration_templates = $template_storage->findTemplatesByTag($version_tag); foreach ($migration_templates as $id => $template) { $migration_templates[$id]['source']['database_state_key'] = $database_state_key; // Configure file migrations so they can find the files. if ($template['destination']['plugin'] == 'entity:file') { if ($source_base_path) { // Make sure we have a single trailing slash. $source_base_path = rtrim($source_base_path, '/') . '/'; $migration_templates[$id]['destination']['source_base_path'] = $source_base_path; } } } // Let the builder service create our migration configuration entities from // the templates, expanding them to multiple entities where necessary. /** @var \Drupal\migrate\MigrationBuilder $builder */ $builder = \Drupal::service('migrate.migration_builder'); $migrations = $builder->createMigrations($migration_templates); $migration_ids = []; foreach ($migrations as $migration) { try { if ($migration->getSourcePlugin() instanceof RequirementsInterface) { $migration->getSourcePlugin()->checkRequirements(); } if ($migration->getDestinationPlugin() instanceof RequirementsInterface) { $migration->getDestinationPlugin()->checkRequirements(); } // Don't try to resave migrations that already exist. if (!Migration::load($migration->id())) { $migration->save(); } $migration_ids[] = $migration->id(); } catch (RequirementsException $e) { } catch (PluginNotFoundException $e) { } } // loadMultiple will sort the migrations in dependency order. return array_keys(Migration::loadMultiple($migration_ids)); }
/** * Test the command directly. * * @requires extension pdo_sqlite */ public function testDbImportCommand() { $connection_info = array('driver' => 'sqlite', 'database' => ':memory:'); Database::addConnectionInfo($this->databasePrefix, 'default', $connection_info); $command = new DbImportCommand(); $command_tester = new CommandTester($command); $command_tester->execute(['script' => __DIR__ . '/../../../fixtures/update/drupal-8.bare.standard.php.gz', '--database' => $this->databasePrefix]); // The tables should now exist. $connection = Database::getConnection('default', $this->databasePrefix); foreach ($this->tables as $table) { $this->assertTrue($connection->schema()->tableExists($table), strtr('Table @table created by the database script.', ['@table' => $table])); } }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $connection_info = Database::getConnectionInfo('default'); foreach ($connection_info as $target => $value) { $prefix = is_array($value['prefix']) ? $value['prefix']['default'] : $value['prefix']; // Simpletest uses 7 character prefixes at most so this can't cause // collisions. $connection_info[$target]['prefix']['default'] = $prefix . '0'; // Add the original simpletest prefix so SQLite can attach its database. // @see \Drupal\Core\Database\Driver\sqlite\Connection::init() $connection_info[$target]['prefix'][$value['prefix']['default']] = $value['prefix']['default']; } Database::addConnectionInfo('migrate', 'default', $connection_info['default']); }
/** * Tests \Drupal\Core\EventSubscriber\ReplicaDatabaseIgnoreSubscriber::checkReplicaServer(). */ function testSystemInitIgnoresSecondaries() { // Clone the master credentials to a replica connection. // Note this will result in two independent connection objects that happen // to point to the same place. $connection_info = Database::getConnectionInfo('default'); Database::addConnectionInfo('default', 'replica', $connection_info['default']); db_ignore_replica(); $kernel = new DrupalKernel('testing', drupal_classloader(), FALSE); $event = new GetResponseEvent($kernel, Request::create('http://example.com'), HttpKernelInterface::MASTER_REQUEST); $subscriber = new ReplicaDatabaseIgnoreSubscriber(); $subscriber->checkReplicaServer($event); $db1 = Database::getConnection('default', 'default'); $db2 = Database::getConnection('replica', 'default'); $this->assertIdentical($db1, $db2, 'System Init ignores secondaries when requested.'); }
protected function setConnection() { try { /** * @var \Drupal\Core\Config\ImmutableConfig $config */ $config = \Drupal::config('smfbridge.settings'); Database::addConnectionInfo('smfbridge', 'smfbridge', $config->get()); /** * @var \Drupal\Core\Database\Connection $this->smfConnection */ $this->smfConnection = Database::getConnection('smfbridge', 'smfbridge'); } catch (\Exception $e) { \Drupal::logger('smfbridge', $e->getMessage()); throw new NotFoundHttpException(); } }
/** * {@inheritdoc} */ protected function connect() { try { // This doesn't actually test the connection. db_set_active(); // 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 file_directory_temp() here because we haven't yet // successfully connected to the database. $connection_info['default']['database'] = drupal_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) { // Still no dice; probably a permission issue. Raise the error to the // installer. $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage()))); } } else { // Database connection failed for some other reason than the database // not existing. $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist, and have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', array('%error' => $e->getMessage()))); return FALSE; } } return TRUE; }
/** * Get the moodle database connection object. * * @return \Drupal\Core\Database\Connection * The database connection. */ public function getDatabase() { // Try and connect to the database if (NULL === $this->database) { try { // Add connection to the Moodle database. $database_settings = $this->getDatabaseSettings(); Database::addConnectionInfo('moodle', 'default', $database_settings); // Connect to the database. $this->database = Database::getConnection('default', 'moodle'); } catch (Exception $e) { $this->loggerFactory->get('Moodle connection', $this->t('Error connecting to the database: "%error".', array('%error' => $e->getMessage()))); drupal_set_message($this->t('Error connecting to the database: "%error".', array('%error' => $e->getMessage()))); return FALSE; } } return $this->database; }
/** * @covers ::getDefinitions */ public function testGetDefinitions() { // Make sure retrieving all the core migration plugins does not throw any // errors. $migration_plugins = $this->container->get('plugin.manager.migration')->getDefinitions(); // All the plugins provided by core depend on migrate_drupal. $this->assertEmpty($migration_plugins); // Enable a module that provides migrations that do not depend on // migrate_drupal. $this->enableModules(['migrate_external_translated_test']); $migration_plugins = $this->container->get('plugin.manager.migration')->getDefinitions(); // All the plugins provided by migrate_external_translated_test do not // depend on migrate_drupal. $this::assertArrayHasKey('external_translated_test_node', $migration_plugins); $this::assertArrayHasKey('external_translated_test_node_translation', $migration_plugins); // Disable the test module and the list should be empty again. $this->disableModules(['migrate_external_translated_test']); $migration_plugins = $this->container->get('plugin.manager.migration')->getDefinitions(); // All the plugins provided by core depend on migrate_drupal. $this->assertEmpty($migration_plugins); // Enable migrate_drupal to test that the plugins can now be discovered. $this->enableModules(['migrate_drupal']); // Set up a migrate database connection so that plugin discovery works. // Clone the current connection and replace the current prefix. $connection_info = Database::getConnectionInfo('migrate'); if ($connection_info) { Database::renameConnection('migrate', 'simpletest_original_migrate'); } $connection_info = Database::getConnectionInfo('default'); foreach ($connection_info as $target => $value) { $prefix = is_array($value['prefix']) ? $value['prefix']['default'] : $value['prefix']; // Simpletest uses 7 character prefixes at most so this can't cause // collisions. $connection_info[$target]['prefix']['default'] = $prefix . '0'; // Add the original simpletest prefix so SQLite can attach its database. // @see \Drupal\Core\Database\Driver\sqlite\Connection::init() $connection_info[$target]['prefix'][$value['prefix']['default']] = $value['prefix']['default']; } Database::addConnectionInfo('migrate', 'default', $connection_info['default']); $migration_plugins = $this->container->get('plugin.manager.migration')->getDefinitions(); // All the plugins provided by core depend on migrate_drupal. $this->assertNotEmpty($migration_plugins); }
/** * Test specifying a prefix for different connections. */ public function testPrefix() { if (Database::getConnection()->driver() == 'sqlite') { $this->markTestSkipped('SQLITE modifies the prefixes so we cannot effectively test it'); } Database::addConnectionInfo('magic_db', 'default', Database::getConnectionInfo('default')['default']); $command = new DbCommandBaseTester(); $command_tester = new CommandTester($command); $command_tester->execute(['--database' => 'magic_db', '--prefix' => 'extra']); $this->assertEquals('extra', $command->getDatabaseConnection($command_tester->getInput())->tablePrefix()); $connection_info = Database::getConnectionInfo('default')['default']; $command_tester->execute(['-db-url' => $connection_info['driver'] . '://' . $connection_info['username'] . ':' . $connection_info['password'] . '@' . $connection_info['host'] . '/' . $connection_info['database'], '--prefix' => 'extra2']); $this->assertEquals('extra2', $command->getDatabaseConnection($command_tester->getInput())->tablePrefix()); // This breaks simpletest cleanup. // $command_tester->execute([ // '--prefix' => 'notsimpletest', // ]); // $this->assertEquals('notsimpletest', $command->getDatabaseConnection($command_tester->getInput())->tablePrefix()); }
/** * Get the database connection object. * * @return \Drupal\Core\Database\Connection * The database connection. */ public function getDatabase() { if (!isset($this->database)) { if (isset($this->configuration['target'])) { $target = $this->configuration['target']; } else { $target = 'default'; } if (isset($this->configuration['key'])) { $key = $this->configuration['key']; } else { $key = 'migrate'; } if (isset($this->configuration['database'])) { Database::addConnectionInfo($key, $target, $this->configuration['database']); } $this->database = Database::getConnection($target, $key); } return $this->database; }
/** * Changes the database connection to the prefixed one. * * @todo Remove when we don't use global. https://www.drupal.org/node/2552791 */ protected function createMigrationConnection() { $connection_info = Database::getConnectionInfo('default')['default']; if ($connection_info['driver'] === 'sqlite') { // Create database file in the test site's public file directory so that // \Drupal\simpletest\TestBase::restoreEnvironment() will delete this once // the test is complete. $file = $this->publicFilesDirectory . '/' . $this->testId . '-migrate.db.sqlite'; touch($file); $connection_info['database'] = $file; $connection_info['prefix'] = ''; } else { $prefix = is_array($connection_info['prefix']) ? $connection_info['prefix']['default'] : $connection_info['prefix']; // Simpletest uses fixed length prefixes. Create a new prefix for the // source database. Adding to the end of the prefix ensures that // \Drupal\simpletest\TestBase::restoreEnvironment() will remove the // additional tables. $connection_info['prefix'] = $prefix . '0'; } Database::addConnectionInfo('migrate_upgrade', 'default', $connection_info); }
/** * Tests that DatabaseSchema::getPrefixInfo() returns the right database. * * We are testing if the return array of the method * \Drupal\Core\Database\Driver\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. */ function testGetPrefixInfo() { $connection_info = Database::getConnectionInfo('default'); if ($connection_info['default']['driver'] == 'mysql') { // 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 databse. $method = new \ReflectionMethod($db1_schema, 'getPrefixInfo'); $method->setAccessible(TRUE); $db1_info = $method->invoke($db1_schema); // We change the database after opening the connection, so as to prevent // connecting to a non-existent database. $reflection = new \ReflectionObject($db2_connection); $property = $reflection->getProperty('connectionOptions'); $property->setAccessible(TRUE); $connection_info['default']['database'] = 'foobar'; $property->setValue($db2_connection, $connection_info['default']); // For testing purposes, we also change the database info. $reflection_class = new \ReflectionClass('Drupal\\Core\\Database\\Database'); $property = $reflection_class->getProperty('databaseInfo'); $property->setAccessible(TRUE); $info = $property->getValue(); $info['extra']['default']['database'] = 'foobar'; $property->setValue(NULL, $info); $extra_info = Database::getConnectionInfo('extra'); $this->assertSame($extra_info['default']['database'], 'foobar'); $db2_schema = $db2_connection->schema(); $db2_info = $method->invoke($db2_schema); $this->assertNotSame($db2_info['database'], $db1_info['database'], 'Each target connection has a different database.'); $this->assertSame($db2_info['database'], 'foobar', 'The new profile has a different database.'); Database::removeConnection('extra'); } }
/** * Tests the findTables() method. */ public function testFindTables() { // We will be testing with three tables, two of them using the default // prefix and the third one with an individually specified prefix. // Set up a new connection with different connection info. $connection_info = Database::getConnectionInfo(); // Add per-table prefix to the second table. $new_connection_info = $connection_info['default']; $new_connection_info['prefix']['test_2_table'] = $new_connection_info['prefix']['default'] . '_shared_'; Database::addConnectionInfo('test', 'default', $new_connection_info); Database::setActiveConnection('test'); // Create the tables. $table_specification = ['description' => 'Test table.', 'fields' => ['id' => ['type' => 'int', 'default' => NULL]]]; Database::getConnection()->schema()->createTable('test_1_table', $table_specification); Database::getConnection()->schema()->createTable('test_2_table', $table_specification); Database::getConnection()->schema()->createTable('the_third_table', $table_specification); // Check the "all tables" syntax. $tables = Database::getConnection()->schema()->findTables('%'); sort($tables); $expected = ['config', 'test_1_table', 'test_2_table', 'the_third_table']; $this->assertEqual($tables, $expected, 'All tables were found.'); // Check the restrictive syntax. $tables = Database::getConnection()->schema()->findTables('test_%'); sort($tables); $expected = ['test_1_table', 'test_2_table']; $this->assertEqual($tables, $expected, 'Two tables were found.'); // Go back to the initial connection. Database::setActiveConnection('default'); }
/** * Tests the connection options of the active database. */ 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->assertEqual($connection_info['default']['driver'], $connectionOptions['driver'], 'The default connection info driver matches the current connection options driver.'); $this->assertEqual($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'); $connectionOptions2 = $db2->getConnectionOptions(); // Get a fresh copy of the default connection options. $connectionOptions = $db->getConnectionOptions(); $this->assertIdentical($connectionOptions, $connectionOptions2, 'The default and replica connection options are identical.'); // Set up a new connection with different connection info. $test = $connection_info['default']; $test['database'] .= 'test'; Database::addConnectionInfo('test', 'default', $test); $connection_info = Database::getConnectionInfo('test'); // Get a fresh copy of the default connection options. $connectionOptions = $db->getConnectionOptions(); $this->assertNotEqual($connection_info['default']['database'], $connectionOptions['database'], 'The test connection info database does not match the current connection options database.'); }
/** * Changes the database connection to the prefixed one. * * @see BrowserTestBase::prepareEnvironment() */ private 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)) { $database = Database::convertDbUrlToConnectionInfo($db_url, DRUPAL_ROOT); 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 // prefixes of the test runner leak into the test. $connection_info[$target]['prefix'] = array('default' => $value['prefix']['default'] . $this->databasePrefix); } Database::addConnectionInfo('default', 'default', $connection_info['default']); } }
/** * Tests that we can log queries separately on different connections. */ function testEnableMultiConnectionLogging() { // Clone the primary credentials to a fake connection. // That both connections point to the same physical database is irrelevant. $connection_info = Database::getConnectionInfo('default'); Database::addConnectionInfo('test2', 'default', $connection_info['default']); Database::startLog('testing1'); Database::startLog('testing1', 'test2'); db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol(); $old_key = db_set_active('test2'); db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'replica'))->fetchCol(); db_set_active($old_key); $queries1 = Database::getLog('testing1'); $queries2 = Database::getLog('testing1', 'test2'); $this->assertEqual(count($queries1), 1, 'Correct number of queries recorded for first connection.'); $this->assertEqual(count($queries2), 1, 'Correct number of queries recorded for second connection.'); }
/** * Tests pdo options override. */ public function testConnectionOpen() { $connection = Database::getConnection('default'); $reflection = new \ReflectionObject($connection); $connection_property = $reflection->getProperty('connection'); $connection_property->setAccessible(TRUE); $error_mode = $connection_property->getValue($connection)->getAttribute(\PDO::ATTR_ERRMODE); $this->assertEqual($error_mode, \PDO::ERRMODE_EXCEPTION, 'Ensure the default error mode is set to exception.'); $connection = Database::getConnectionInfo('default'); $connection['default']['pdo'][\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_SILENT; Database::addConnectionInfo('test', 'default', $connection['default']); $connection = Database::getConnection('default', 'test'); $reflection = new \ReflectionObject($connection); $connection_property = $reflection->getProperty('connection'); $connection_property->setAccessible(TRUE); $error_mode = $connection_property->getValue($connection)->getAttribute(\PDO::ATTR_ERRMODE); $this->assertEqual($error_mode, \PDO::ERRMODE_SILENT, 'Ensure PDO connection options can be overridden.'); Database::removeConnection('test'); }
protected function registerSourceDB(InputInterface $input) { $db_host = $input->getOption('db-host'); $db_name = $input->getOption('db-name'); $db_user = $input->getOption('db-user'); $db_pass = $input->getOption('db-pass'); $db_prefix = $input->getOption('db-prefix'); $db_port = $input->getOption('db-port'); $database = array('database' => $db_name, 'username' => $db_user, 'password' => $db_pass, 'prefix' => $db_prefix, 'port' => $db_port, 'host' => $db_host, 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 'driver' => 'mysql'); try { Database::addConnectionInfo('migrate', 'default', $database); } catch (\Exception $e) { $output->writeln('[+] <error>' . $this->trans('commands.migrate.execute.messages.source-error') . ': ' . $e->getMessage() . '</error>'); return; } }
/** * @param OutputInterface $output * @param string $key * @param sting $target * @param array $info */ protected function addDBConnection($output, $key, $target, $db_type, $db_name, $db_user, $db_pass, $db_prefix, $db_port, $db_host) { $databases = $this->getDatabaseTypes(); $this->database = array('database' => $db_name, 'username' => $db_user, 'password' => $db_pass, 'prefix' => $db_prefix, 'port' => $db_port, 'host' => $db_host, 'namespace' => $databases[$db_type]['namespace'], 'driver' => $db_type); try { return Database::addConnectionInfo($key, $target, $this->database); } catch (\Exception $e) { $output->writeln('[+] <error>' . $this->trans('commands.migrate.execute.messages.source-error') . ': ' . $e->getMessage() . '</error>'); return; } }
/** * @param DrupalStyle $output * @param $key * @param $target * @param $db_type * @param $db_name * @param $db_user * @param $db_pass * @param $db_prefix * @param $db_port * @param $db_host */ protected function addDBConnection(DrupalStyle $output, $key, $target, $db_type, $db_name, $db_user, $db_pass, $db_prefix, $db_port, $db_host) { $databases = $this->getDatabaseTypes(); $this->database = ['database' => $db_name, 'username' => $db_user, 'password' => $db_pass, 'prefix' => $db_prefix, 'port' => $db_port, 'host' => $db_host, 'namespace' => $databases[$db_type]['namespace'], 'driver' => $db_type]; try { return Database::addConnectionInfo($key, $target, $this->database); } catch (\Exception $e) { $output->error(sprintf('%s: %s', $this->trans('commands.migrate.execute.messages.source-error'), $e->getMessage())); return; } }
/** * Changes the database connection to the prefixed one. * * @see TestBase::prepareEnvironment() */ private function changeDatabasePrefix() { if (empty($this->databasePrefix)) { $this->prepareDatabasePrefix(); } // 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 // for all test methods executed in one PHP process. if (Database::getConnectionInfo('simpletest_original_default')) { throw new \RuntimeException("Bad Database connection state: 'simpletest_original_default' connection key already exists. Broken test?"); } // Clone the current connection and replace the current prefix. $connection_info = Database::getConnectionInfo('default'); Database::renameConnection('default', 'simpletest_original_default'); foreach ($connection_info as $target => $value) { // Replace the full table prefix definition to ensure that no table // prefixes of the test runner leak into the test. $connection_info[$target]['prefix'] = array('default' => $value['prefix']['default'] . $this->databasePrefix); } Database::addConnectionInfo('default', 'default', $connection_info['default']); }
/** * Returns the Database connection info to be used for this test. * * This method only exists for tests of the Database component itself, because * they require multiple database connections. Each SQLite :memory: connection * creates a new/separate database in memory. A shared-memory SQLite file URI * triggers PHP open_basedir/allow_url_fopen/allow_url_include restrictions. * Due to that, Database tests are running against a SQLite database that is * located in an actual file in the system's temporary directory. * * Other tests should not override this method. * * @return array * A Database connection info array. * * @internal */ protected function getDatabaseConnectionInfo() { // If the test is run with argument dburl then use it. $db_url = getenv('SIMPLETEST_DB'); if (empty($db_url)) { throw new \Exception('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. See https://www.drupal.org/node/2116263#skipped-tests for more information.'); } else { $database = Database::convertDbUrlToConnectionInfo($db_url, $this->root); 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 full table prefix definition to ensure that no table // prefixes of the test runner leak into the test. $connection_info[$target]['prefix'] = array('default' => $value['prefix']['default'] . $this->databasePrefix); } } return $connection_info; }