當前位置: 首頁>>代碼示例>>PHP>>正文


PHP Database::getConnection方法代碼示例

本文整理匯總了PHP中Drupal\Core\Database\Database::getConnection方法的典型用法代碼示例。如果您正苦於以下問題:PHP Database::getConnection方法的具體用法?PHP Database::getConnection怎麽用?PHP Database::getConnection使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Drupal\Core\Database\Database的用法示例。


在下文中一共展示了Database::getConnection方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。

示例1: update_body_format

function update_body_format($table, $old, $new)
{
    // Get database connection
    \Drupal\Core\Database\Database::setActiveConnection();
    $connection = \Drupal\Core\Database\Database::getConnection();
    // Update the body_format for the specified table
    $results = $connection->update($table)->fields(array('body_format' => $new))->condition('body_format', $old, '=')->execute();
    return $results;
}
開發者ID:CIGIHub,項目名稱:bsia-drupal8,代碼行數:9,代碼來源:change_body_format.php

示例2: testMenu

  /**
   * Tests the Drupal 6 menu to Drupal 8 migration.
   */
  public function testMenu() {
    $navigation_menu = Menu::load('navigation');
    $this->assertSame('navigation', $navigation_menu->id());
    $this->assertSame('Navigation', $navigation_menu->label());
    $expected = <<<EOT
The navigation menu is provided by Drupal and is the main interactive menu for any site. It is usually the only menu that contains personalized links for authenticated users, and is often not even visible to anonymous users.
EOT;
    $this->assertSame($expected, $navigation_menu->getDescription());

    // Test that we can re-import using the ConfigEntityBase destination.
    Database::getConnection('default', 'migrate')
      ->update('menu_custom')
      ->fields(array('title' => 'Home Navigation'))
      ->condition('menu_name', 'navigation')
      ->execute();

    $migration = $this->getMigration('d6_menu');
    \Drupal::database()
        ->truncate($migration->getIdMap()->mapTableName())
        ->execute();
    $this->executeMigration($migration);

    $navigation_menu = Menu::load('navigation');
    $this->assertSame('Home Navigation', $navigation_menu->label());
  }
開發者ID:Greg-Boggs,項目名稱:electric-dev,代碼行數:28,代碼來源:MigrateMenuTest.php

示例3: 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);
 }
開發者ID:318io,項目名稱:318-io,代碼行數:32,代碼來源:DbCommandBase.php

示例4: testFiles

 /**
  * Tests the Drupal 6 files to Drupal 8 migration.
  */
 public function testFiles()
 {
     /** @var \Drupal\file\FileInterface $file */
     $file = entity_load('file', 1);
     $this->assertIdentical('Image1.png', $file->getFilename());
     $this->assertIdentical('39325', $file->getSize());
     $this->assertIdentical('public://image-1.png', $file->getFileUri());
     $this->assertIdentical('image/png', $file->getMimeType());
     // It is pointless to run the second half from MigrateDrupal6Test.
     if (empty($this->standalone)) {
         return;
     }
     // Test that we can re-import and also test with file_directory_path set.
     db_truncate(entity_load('migration', 'd6_file')->getIdMap()->mapTableName())->execute();
     $migration = entity_load_unchanged('migration', 'd6_file');
     $dumps = array($this->getDumpDirectory() . '/Variable.php');
     $this->prepare($migration, $dumps);
     // Update the file_directory_path.
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute();
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('/tmp')))->condition('name', 'file_directory_temp')->execute();
     $executable = new MigrateExecutable($migration, $this);
     $executable->import();
     $file = entity_load('file', 2);
     $this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
     // Ensure that a temporary file has been migrated.
     $file = entity_load('file', 6);
     $this->assertIdentical('temporary://some-temp-file.jpg', $file->getFileUri());
 }
開發者ID:Nikola-xiii,項目名稱:d8intranet,代碼行數:31,代碼來源:MigrateFileTest.php

示例5: testInsertDuplicateData

 /**
  * Tests aborting of traditional SQL database systems with invalid data.
  */
 function testInsertDuplicateData()
 {
     // Try to insert multiple records where at least one has bad data.
     try {
         db_insert('test')->fields(array('name', 'age', 'job'))->values(array('name' => 'Elvis', 'age' => 63, 'job' => 'Singer'))->values(array('name' => 'John', 'age' => 17, 'job' => 'Consultant'))->values(array('name' => 'Frank', 'age' => 75, 'job' => 'Singer'))->execute();
         $this->fail('Insert succeeded when it should not have.');
     } catch (IntegrityConstraintViolationException $e) {
         // Check if the first record was inserted.
         $name = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 63))->fetchField();
         if ($name == 'Elvis') {
             if (!Database::getConnection()->supportsTransactions()) {
                 // This is an expected fail.
                 // Database engines that don't support transactions can leave partial
                 // inserts in place when an error occurs. This is the case for MySQL
                 // when running on a MyISAM table.
                 $this->pass("The whole transaction has not been rolled-back when a duplicate key insert occurs, this is expected because the database doesn't support transactions");
             } else {
                 $this->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
             }
         } else {
             $this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
         }
         // Ensure the other values were not inserted.
         $record = db_select('test')->fields('test', array('name', 'age'))->condition('age', array(17, 75), 'IN')->execute()->fetchObject();
         $this->assertFalse($record, 'The rest of the insert aborted as expected.');
     }
 }
開發者ID:318io,項目名稱:318-io,代碼行數:30,代碼來源:InvalidDataTest.php

示例6: __construct

 public function __construct($database)
 {
     global $ss_client;
     $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
     require_once DRUPAL_ROOT . '/core/includes/database.inc';
     Database::setMultipleConnectionInfo($database);
     $this->connection = Database::getConnection();
     $this->ss_client =& $ss_client;
     $this->database = $database;
     $query = db_select('config', 'n')->fields('n')->condition('name', $this->options, 'IN');
     $result = $query->execute();
     if ($result && is_object($result)) {
         foreach ($result as $key => $row) {
             $values = unserialize($row->data);
             foreach ($values[key($values)] as $value_key => $value) {
                 $this->data_options[$value_key] = $value;
             }
         }
     }
     if (defined('STACKSIGHT_SETTINGS_IN_DB') && STACKSIGHT_SETTINGS_IN_DB === true) {
         if (isset($this->data_options['token'])) {
             $this->ready = true;
         }
     } else {
         $this->ready = true;
     }
     define('STACKSIGHT_PHP_SDK_INCLUDE', TRUE);
 }
開發者ID:stacksight,項目名稱:stacksight-php-sdk,代碼行數:28,代碼來源:bootstrap-drupal-8.php

示例7: getDatabase

 /**
  * Get the database connection object.
  *
  * @return \Drupal\Core\Database\Connection
  *   The database connection.
  */
 public function getDatabase()
 {
     if (!isset($this->database)) {
         $this->database = Database::getConnection('default', 'migrate');
     }
     return $this->database;
 }
開發者ID:anatalsceo,項目名稱:en-classe,代碼行數:13,代碼來源:SqlBase.php

示例8: testNode

 /**
  * Test node migration from Drupal 6 to 8.
  */
 public function testNode()
 {
     $node = node_load(1);
     $this->assertEqual($node->id(), 1, 'Node 1 loaded.');
     $this->assertEqual($node->body->value, 'test');
     $this->assertEqual($node->body->format, 'filtered_html');
     $this->assertEqual($node->getType(), 'story', 'Node has the correct bundle.');
     $this->assertEqual($node->getTitle(), 'Test title', 'Node has the correct title.');
     $this->assertEqual($node->getCreatedTime(), 1388271197, 'Node has the correct created time.');
     $this->assertEqual($node->isSticky(), FALSE);
     $this->assertEqual($node->getOwnerId(), 1);
     //$this->assertEqual($node->getRevisionCreationTime(), 1390095701, 'Node has the correct revision timestamp.');
     // It is pointless to run the second half from MigrateDrupal6Test.
     if (empty($this->standalone)) {
         return;
     }
     // Test that we can re-import using the EntityContentBase destination.
     $connection = Database::getConnection('default', 'migrate');
     $connection->update('node_revisions')->fields(array('title' => 'New node title', 'format' => 2))->condition('vid', 1)->execute();
     $connection->delete('content_field_test_two')->condition('delta', 1)->execute();
     /** @var \Drupal\migrate\entity\Migration $migration */
     $migration = entity_load('migration', 'd6_node');
     $executable = new MigrateExecutable($migration, $this);
     $executable->import();
     $node = node_load(1);
     $this->assertEqual($node->getTitle(), 'New node title');
     // Test a multi-column fields are correctly upgraded.
     $this->assertEqual($node->body->value, 'test');
     $this->assertEqual($node->body->format, 'full_html');
 }
開發者ID:anatalsceo,項目名稱:en-classe,代碼行數:33,代碼來源:MigrateNodeTest.php

示例9: deleteAllUsers

 public static function deleteAllUsers($roles = NULL)
 {
     $count = 0;
     $db_connection = Database::getConnection();
     if (!$roles) {
         $result = $db_connection->query('SELECT uid FROM {users} WHERE uid > 1')->fetchAllAssoc('uid');
         foreach ($result as $data) {
             $user = User::load($data->uid);
             $user->delete();
             $count++;
         }
         // Delete the URL aliases
         $db_connection->query("DELETE FROM {url_alias} WHERE source LIKE 'user/%%'");
     } else {
         if (is_array($roles)) {
             $result = array();
             foreach ($roles as $role) {
                 $result = array_merge($result, db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $role, '=')->execute()->fetchCol('entity_id'));
             }
         } else {
             $result = db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $roles, '=')->execute()->fetchCol('entity_id');
         }
         foreach ($result as $data) {
             $user = User::load($data);
             $user->delete();
             $count++;
         }
         // @TODO Delete individual aliases
     }
     return $count;
 }
開發者ID:blakefrederick,項目名稱:sas-backend,代碼行數:31,代碼來源:DeleteUsersForm.php

示例10: setUpFixtures

  /**
   * Sets up the configuration and schema of views and views_test_data modules.
   *
   * Because the schema of views_test_data.module is dependent on the test
   * using it, it cannot be enabled normally.
   */
  protected function setUpFixtures() {
    // First install the system module. Many Views have Page displays have menu
    // links, and for those to work, the system menus must already be present.
    $this->installConfig(['system']);

    /** @var \Drupal\Core\State\StateInterface $state */
    $state = $this->container->get('state');
    // Define the schema and views data variable before enabling the test module.
    $state->set('views_test_data_schema', $this->schemaDefinition());
    $state->set('views_test_data_views_data', $this->viewsData());

    $this->installConfig(['views', 'views_test_config', 'views_test_data']);
    foreach ($this->schemaDefinition() as $table => $schema) {
      $this->installSchema('views_test_data', $table);
    }

    $this->container->get('router.builder')->rebuild();

    // Load the test dataset.
    $data_set = $this->dataSet();
    $query = Database::getConnection()->insert('views_test_data')
      ->fields(array_keys($data_set[0]));
    foreach ($data_set as $record) {
      $query->values($record);
    }
    $query->execute();
  }
開發者ID:jthoresen,項目名稱:PladsenDrupal,代碼行數:33,代碼來源:ViewsKernelTestBase.php

示例11: validateEntityStrings

  /**
   * {@inheritdoc}
   */
  protected function validateEntityStrings(array &$form, array $values, FormStateInterface $form_state) {
    $uids = array();
    $missing = array();
    foreach ($values as $value) {
      if (Unicode::strtolower($value) === Unicode::strtolower(\Drupal::config('user.settings')->get('anonymous'))) {
        $uids[] = 0;
      }
      else {
        $missing[strtolower($value)] = $value;
      }
    }

    if (!$missing) {
      return $uids;
    }

    $result = Database::getConnection()->query("SELECT * FROM {users} WHERE name IN (:names)", array(':names' => array_values($missing)));
    foreach ($result as $account) {
      unset($missing[strtolower($account->name)]);
      $uids[] = $account->uid;
    }

    if ($missing) {
      $form_state->setError($form, $this->formatPlural(count($missing), 'Unable to find user: @users', 'Unable to find users: @users', array('@users' => implode(', ', $missing))));
    }

    return $uids;
  }
開發者ID:jkyto,項目名稱:agolf,代碼行數:31,代碼來源:SearchApiUser.php

示例12: 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;
         }
     }
 }
開發者ID:ddrozdik,項目名稱:dmaps,代碼行數:36,代碼來源:DbLog.php

示例13: 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.');
     }
 }
開發者ID:dmyerson,項目名稱:d8ecs,代碼行數:35,代碼來源:LargeQueryTest.php

示例14: setUp

 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('node');
     $this->installEntitySchema('comment');
     $this->installEntitySchema('taxonomy_term');
     CommentType::create(['id' => 'comment_node_page', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_article', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_blog', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_book', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_forum', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_test_content_type', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'page', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'article', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'blog', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'book', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'forum', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'test_content_type', 'label' => $this->randomMachineName()])->save();
     Vocabulary::create(['vid' => 'test_vocabulary'])->save();
     // Give one unfortunate field instance invalid display settings to ensure
     // that the migration provides an empty array as a default (thus avoiding
     // an "unsupported operand types" fatal).
     Database::getConnection('default', 'migrate')->update('field_config_instance')->fields(array('data' => serialize(array('label' => 'Body', 'widget' => array('type' => 'text_textarea_with_summary', 'settings' => array('rows' => 20, 'summary_rows' => 5), 'weight' => -4, 'module' => 'text'), 'settings' => array('display_summary' => TRUE, 'text_processing' => 1, 'user_register_form' => FALSE), 'display' => array('default' => array('label' => 'hidden', 'type' => 'text_default', 'settings' => array(), 'module' => 'text', 'weight' => 0), 'teaser' => array('label' => 'hidden', 'type' => 'text_summary_or_trimmed', 'settings' => NULL, 'module' => 'text', 'weight' => 0)), 'required' => FALSE, 'description' => ''))))->condition('entity_type', 'node')->condition('bundle', 'article')->condition('field_name', 'body')->execute();
     $this->executeMigrations(['d7_field', 'd7_field_instance', 'd7_view_modes', 'd7_field_formatter_settings']);
 }
開發者ID:DrupalCamp-NYC,項目名稱:dcnyc16,代碼行數:28,代碼來源:MigrateFieldFormatterSettingsTest.php

示例15: testInvalidCropValues

 /**
  * Test that missing action's causes failures.
  */
 public function testInvalidCropValues()
 {
     Database::getConnection('default', 'migrate')->insert("imagecache_action")->fields(['presetid', 'weight', 'module', 'action', 'data'])->values(['presetid' => '1', 'weight' => '0', 'module' => 'imagecache', 'action' => 'imagecache_crop', 'data' => serialize(['xoffset' => '10', 'yoffset' => '10'])])->execute();
     $this->startCollectingMessages();
     $this->executeMigration('d6_imagecache_presets');
     $this->assertEqual(['error' => ['The Drupal 8 image crop effect does not support numeric values for x and y offsets. Use keywords to set crop effect offsets instead.']], $this->migrateMessages);
 }
開發者ID:sojo,項目名稱:d8_friendsofsilence,代碼行數:10,代碼來源:MigrateImageCacheTest.php


注:本文中的Drupal\Core\Database\Database::getConnection方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。