本文整理汇总了PHP中Drupal\Core\Database\Database::addConnectionInfo方法的典型用法代码示例。如果您正苦于以下问题:PHP Database::addConnectionInfo方法的具体用法?PHP Database::addConnectionInfo怎么用?PHP Database::addConnectionInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Database\Database
的用法示例。
在下文中一共展示了Database::addConnectionInfo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getDatabaseConnection
/**
* 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);
}
示例2: getConnection
/**
* 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;
}
示例3: createMigrationConnection
/**
* 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']);
}
示例4: log
/**
* {@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;
}
}
}
示例5: testConnectionTypes
/**
* 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);
}
示例6: testGetConnectionInfoAsUrl
/**
* @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);
}
示例7: 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']);
}
示例8: testConnectionTypes
/**
* 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);
}
示例9: createMigrations
/**
* 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));
}
示例10: testDbImportCommand
/**
* 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]));
}
}
示例11: 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']);
}
示例12: testSystemInitIgnoresSecondaries
/**
* 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.');
}
示例13: setConnection
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();
}
}
示例14: connect
/**
* {@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;
}
示例15: getDatabase
/**
* 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;
}