本文整理汇总了PHP中Drupal\Core\Database\Database::getConnectionInfo方法的典型用法代码示例。如果您正苦于以下问题:PHP Database::getConnectionInfo方法的具体用法?PHP Database::getConnectionInfo怎么用?PHP Database::getConnectionInfo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Database\Database
的用法示例。
在下文中一共展示了Database::getConnectionInfo方法的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: 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;
}
}
}
示例3: 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);
}
示例4: getOrderIds
/**
* 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;
}
示例5: testMaxAllowedPacketQueryTruncating
/**
* 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.');
}
}
示例6: 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'];
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;
}
示例7: setUp
/**
* {@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();
}
示例8: 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']);
}
示例9: 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);
}
示例10: checkConnectionInfo
/**
* @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;
}
}
示例11: buildForm
/**
* {@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;
}
示例12: getRedBeanConnection
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;
}
示例13: isConnectionInfo
/**
* @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;
}
示例14: get_db_spec
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;
}
示例15: getObject
/**
* 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;
}