/** * 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); }
/** * {@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); }
/** * Queries database for the order ids of the most recently modified billing * addresses. It assumes the billing address on the most recent order are * the most current. */ public function getOrderIds() { // This query wouldn't work so used the raw MySQL query below. Not sure // if the limitation is Drupal's database framework or my understanding // of it. //$query = $this->select('uc_orders', 'uo') // ->fields('uo', ['order_id']); //$query->addExpression('MAX(uo.modified)', 'newest_entry'); //$query->groupBy('uo.uid'); //$query->execute(); //drush_print($query->__toString()); // Ugly and somewhat hackish. A neater, more Drupal 8 method would be // nice. If anyone knows of a better way to do it as I attempted above, // I'd love to see it. $connection = Database::getConnectionInfo('migrate'); $mysql_connection = mysqli_connect($connection['default']['host'], $connection['default']['username'], $connection['default']['password'], $connection['default']['database']); // Only imports the most recently modified orders for each shopper. $result = mysqli_query($mysql_connection, 'SELECT uo.order_id AS order_id, MAX(uo.modified) AS newest_entry FROM uc_orders uo GROUP BY uo.uid'); $order_ids = array(); foreach ($result as $row) { $order_ids[] = $row['order_id']; } return $order_ids; }
/** * Tests truncation of messages when max_allowed_packet exception occurs. */ function testMaxAllowedPacketQueryTruncating() { // This test only makes sense if we are running on a MySQL database. // Test if we are. $database = Database::getConnectionInfo('default'); if ($database['default']['driver'] == 'mysql') { // The max_allowed_packet value is configured per database instance. // Retrieve the max_allowed_packet value from the current instance and // check if PHP is configured with sufficient allowed memory to be able // to generate a query larger than max_allowed_packet. $max_allowed_packet = db_query('SELECT @@global.max_allowed_packet')->fetchField(); if (Environment::checkMemoryLimit($max_allowed_packet + 16 * 1024 * 1024)) { $long_name = str_repeat('a', $max_allowed_packet + 1); try { db_query('SELECT name FROM {test} WHERE name = :name', array(':name' => $long_name)); $this->fail("An exception should be thrown for queries larger than 'max_allowed_packet'"); } catch (DatabaseException $e) { // Close and re-open the connection. Otherwise we will run into error // 2006 "MySQL server had gone away" afterwards. Database::closeConnection(); Database::getConnection(); $this->assertEqual($e->getPrevious()->errorInfo[1], 1153, "Got a packet bigger than 'max_allowed_packet' bytes exception thrown."); // Use strlen() to count the bytes exactly, not the unicode chars. $this->assertTrue(strlen($e->getMessage()) <= $max_allowed_packet, "'max_allowed_packet' exception message truncated."); } } else { $this->verbose('The configured max_allowed_packet exceeds the php memory limit. Therefore the test is skipped.'); } } else { $this->verbose('The test requires MySQL. Therefore the test is skipped.'); } }
/** * {@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']; 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']); // 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()))); return FALSE; } catch (\PDOException $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()))); return FALSE; } } 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; }
/** * {@inheritdoc} */ protected function setUp() { // 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) array('value' => $connection_info, 'required' => TRUE); parent::setUp(); }
/** * {@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); }
/** * @return void */ private function checkConnectionInfo() { $settingsPath = sprintf('%s/%s', $this->root, self::DEFAULT_SETTINGS_PHP); if (!file_exists($settingsPath)) { return; } if (Database::getConnectionInfo()) { $this->installed = true; } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $conf_path = './' . conf_path(FALSE); $settings_file = $conf_path . '/settings.php'; $form['#title'] = $this->t('Database configuration'); $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']; if (isset($prefix) && is_array($prefix)) { $prefix = $prefix['default']; } $default_options = $input[$default_driver]; } else { $default_driver = current($drivers_keys); $default_options = array(); } $form['driver'] = array('#type' => 'radios', '#title' => $this->t('Database type'), '#required' => TRUE, '#default_value' => $default_driver); if (count($drivers) == 1) { $form['driver']['#disabled'] = TRUE; } // Add driver specific configuration options. foreach ($drivers as $key => $driver) { $form['driver']['#options'][$key] = $driver->name(); $form['settings'][$key] = $driver->getFormOptions($default_options); $form['settings'][$key]['#prefix'] = '<h2 class="js-hide">' . $this->t('@driver_name settings', array('@driver_name' => $driver->name())) . '</h2>'; $form['settings'][$key]['#type'] = 'container'; $form['settings'][$key]['#tree'] = TRUE; $form['settings'][$key]['advanced_options']['#parents'] = array($key); $form['settings'][$key]['#states'] = array('visible' => array(':input[name=driver]' => array('value' => $key))); } $form['actions'] = array('#type' => 'actions'); $form['actions']['save'] = array('#type' => 'submit', '#value' => $this->t('Save and continue'), '#button_type' => 'primary', '#limit_validation_errors' => array(array('driver'), array($default_driver)), '#submit' => array('::submitForm')); $form['errors'] = array(); $form['settings_file'] = array('#type' => 'value', '#value' => $settings_file); return $form; }
public function getRedBeanConnection($database = 'default') { $connectionInfo = Database::getConnectionInfo(); $databaseConnection = $connectionInfo[$database]; if ($databaseConnection['driver'] == 'mysql') { $dsn = sprintf('mysql:host=%s;dbname=%s', $databaseConnection['host'], $databaseConnection['database']); $this->redBean->setup($dsn, $databaseConnection['username'], $databaseConnection['password'], true); return $this->redBean; } return null; }
/** * @return bool */ public function isConnectionInfo() { $settingsPath = sprintf('%s/%s', $this->root, self::DEFAULT_SETTINGS_PHP); if (!file_exists($settingsPath)) { return false; } if (Database::getConnectionInfo()) { return true; } return false; }
public function get_db_spec() { $db_spec = NULL; if (drush_bootstrap_max(DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION)) { $database = drush_get_option('database', 'default'); $target = drush_get_option('target', 'default'); if ($info = Database::getConnectionInfo($database)) { return $info[$target]; } } return $db_spec; }
/** * Get the Backup and Migrate plugin object. * * @return BackupMigrate\Core\Plugin\PluginInterface; */ public function getObject() { // Add the default database. $info = \Drupal\Core\Database\Database::getConnectionInfo('default', 'default'); $info = $info['default']; if ($info['driver'] == 'mysql') { $conf = $this->getConfig(); $conf->set('directory', DRUPAL_ROOT); $db = new MySQLiSource(new Config($info)); return new DrupalSiteArchiveSource($conf, $db); } return null; }
/** * Get the Backup and Migrate plugin object. * * @return BackupMigrate\Core\Plugin\PluginInterface; */ public function getObject() { // Add the default database. $info = \Drupal\Core\Database\Database::getConnectionInfo('default', 'default'); $info = $info['default']; if ($info['driver'] == 'mysql') { $conf = $this->getConfig(); foreach ($info as $key => $value) { $conf->set($key, $value); } return new MySQLiSource($conf); } return null; }
protected function getConnectionData() { $connectionInfo = Database::getConnectionInfo(); $connectionData = []; foreach ($this->connectionInfoKeys as $connectionInfoKey) { if ("password" == $connectionInfoKey) { continue; } $connectionKey = $this->trans('commands.site.status.messages.' . $connectionInfoKey); $connectionData['database'][$connectionKey] = $connectionInfo['default'][$connectionInfoKey]; } $connectionData['database'][$this->trans('commands.site.status.messages.connection')] = sprintf('%s//%s:%s@%s%s/%s', $connectionInfo['default']['driver'], $connectionInfo['default']['username'], $connectionInfo['default']['password'], $connectionInfo['default']['host'], $connectionInfo['default']['port'] ? ':' . $connectionInfo['default']['port'] : '', $connectionInfo['default']['database']); return $connectionData; }
/** * {@inheritdoc} * * Configures a preexisting settings.php file without an install_profile * setting before invoking the interactive installer. */ protected function setUp() { // Pre-configure hash salt. // Any string is valid, so simply use the class name of this test. $this->settings['settings']['hash_salt'] = (object) array('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) array('value' => $connection_info, 'required' => TRUE); // Pre-configure config directories. $this->settings['config_directories'] = array(CONFIG_SYNC_DIRECTORY => (object) array('value' => DrupalKernel::findSitePath(Request::createFromGlobals()) . '/files/config_sync', 'required' => TRUE)); mkdir($this->settings['config_directories'][CONFIG_SYNC_DIRECTORY]->value, 0777, TRUE); parent::setUp(); }
/** * {@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']); }
/** * Get information about the table and database name from the prefix. * * @return * A keyed array with information about the database, table name and prefix. */ protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) { $info = array('prefix' => $this->connection->tablePrefix($table)); if ($add_prefix) { $table = $info['prefix'] . $table; } if (($pos = strpos($table, '.')) !== FALSE) { $info['database'] = substr($table, 0, $pos); $info['table'] = substr($table, ++$pos); } else { $db_info = Database::getConnectionInfo(); $info['database'] = $db_info[$this->connection->getTarget()]['database']; $info['table'] = $table; } return $info; }
/** * {@inheritdoc} * * Configures a preexisting settings.php file without an install_profile * setting before invoking the interactive installer. */ protected function setUp() { // Pre-configure hash salt. // Any string is valid, so simply use the class name of this test. $this->settings['settings']['hash_salt'] = (object) array('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) array('value' => $connection_info, 'required' => TRUE); // Pre-configure config directories. $this->settings['config_directories'] = array(CONFIG_ACTIVE_DIRECTORY => (object) array('value' => conf_path() . '/files/config_active', 'required' => TRUE), CONFIG_STAGING_DIRECTORY => (object) array('value' => conf_path() . '/files/config_staging', 'required' => TRUE)); mkdir($this->settings['config_directories'][CONFIG_ACTIVE_DIRECTORY]->value, 0777, TRUE); mkdir($this->settings['config_directories'][CONFIG_STAGING_DIRECTORY]->value, 0777, TRUE); parent::setUp(); }
/** * 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.'); }
/** * 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()); }
/** * @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); }
/** * {@inheritdoc} * * Fully configures a preexisting settings.php file before invoking the * interactive installer. */ protected function setUp() { // Pre-configure hash salt. // Any string is valid, so simply use the class name of this test. $this->settings['settings']['hash_salt'] = (object) array('value' => __CLASS__, 'required' => TRUE); // Actually the install profile should be skipped to because it is written // to settings.php. // @todo https://www.drupal.org/node/2451369 Fix install_profile so that it // is written to an existing settings.php if possible or if set used. $this->settings['settings']['install_profile'] = (object) array('value' => 'testing', '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) array('value' => $connection_info, 'required' => TRUE); // Pre-configure config directories. $this->settings['config_directories'] = array(CONFIG_ACTIVE_DIRECTORY => (object) array('value' => conf_path() . '/files/config_active', 'required' => TRUE), CONFIG_STAGING_DIRECTORY => (object) array('value' => conf_path() . '/files/config_staging', 'required' => TRUE)); mkdir($this->settings['config_directories'][CONFIG_ACTIVE_DIRECTORY]->value, 0777, TRUE); mkdir($this->settings['config_directories'][CONFIG_STAGING_DIRECTORY]->value, 0777, TRUE); parent::setUp(); }
/** * {@inheritdoc} * * Fully configures a preexisting settings.php file before invoking the * interactive installer. */ protected function setUp() { // Pre-configure hash salt. // Any string is valid, so simply use the class name of this test. $this->settings['settings']['hash_salt'] = (object) array('value' => __CLASS__, 'required' => TRUE); // During interactive install we'll change this to a different profile and // this test will ensure that the new value is written to settings.php. $this->settings['settings']['install_profile'] = (object) array('value' => 'minimal', '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) array('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()); // Pre-configure config directories. $this->settings['config_directories'] = array(CONFIG_SYNC_DIRECTORY => (object) array('value' => $site_path . '/files/config_sync', 'required' => TRUE)); mkdir($this->settings['config_directories'][CONFIG_SYNC_DIRECTORY]->value, 0777, TRUE); parent::setUp(); }
/** * 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'); }
/** * Returns the parameters that will be used when Simpletest installs Drupal. * * @see install_drupal() * @see install_state_defaults() * * @return array * Array of parameters for use in install_drupal(). */ protected function installParameters() { $connection_info = Database::getConnectionInfo(); $driver = $connection_info['default']['driver']; $connection_info['default']['prefix'] = $connection_info['default']['prefix']['default']; unset($connection_info['default']['driver']); unset($connection_info['default']['namespace']); unset($connection_info['default']['pdo']); unset($connection_info['default']['init_commands']); // Remove database connection info that is not used by SQLite. if ($driver == 'sqlite') { unset($connection_info['default']['username']); unset($connection_info['default']['password']); unset($connection_info['default']['host']); unset($connection_info['default']['port']); } $parameters = array('interactive' => FALSE, 'parameters' => array('profile' => $this->profile, 'langcode' => 'en'), 'forms' => array('install_settings_form' => array('driver' => $driver, $driver => $connection_info['default']), 'install_configure_form' => array('site_name' => 'Drupal', 'site_mail' => '*****@*****.**', 'account' => array('name' => $this->rootUser->name, 'mail' => $this->rootUser->getEmail(), 'pass' => array('pass1' => $this->rootUser->pass_raw, 'pass2' => $this->rootUser->pass_raw)), 'update_status_module' => array(1 => NULL, 2 => NULL)))); // If we only have one db driver available, we cannot set the driver. include_once DRUPAL_ROOT . '/core/includes/install.inc'; if (count($this->getDatabaseTypes()) == 1) { unset($parameters['forms']['install_settings_form']['driver']); } return $parameters; }