本文整理汇总了PHP中Drupal\Core\Database\Database类的典型用法代码示例。如果您正苦于以下问题:PHP Database类的具体用法?PHP Database怎么用?PHP Database使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Database类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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');
}
示例2: 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;
}
示例3: handle
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
{
foreach (Database::getAllConnectionInfo() as $key => $info) {
Database::startLog('webprofiler', $key);
}
return $this->httpKernel->handle($request, $type, $catch);
}
示例4: 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();
}
示例5: 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;
}
示例6: 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;
}
示例7: 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;
}
}
}
示例8: 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;
}
示例9: 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);
}
示例10: 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);
}
示例11: checkReplicaServer
/**
* Checks and disables the replica database server if appropriate.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The Event to process.
*/
public function checkReplicaServer(GetResponseEvent $event)
{
// Ignore replica database servers for this request.
//
// In Drupal's distributed database structure, new data is written to the
// master and then propagated to the replica servers. This means there is a
// lag between when data is written to the master and when it is available
// on the replica. At these times, we will want to avoid using a replica server
// temporarily. For example, if a user posts a new node then we want to
// disable the replica server for that user temporarily to allow the replica
// server to catch up.
// That way, that user will see their changes immediately while for other
// users we still get the benefits of having a replica server, just with
// slightly stale data. Code that wants to disable the replica server should
// use the db_set_ignore_replica() function to set
// $_SESSION['ignore_replica_server'] to the timestamp after which the replica
// can be re-enabled.
if (isset($_SESSION['ignore_replica_server'])) {
if ($_SESSION['ignore_replica_server'] >= REQUEST_TIME) {
Database::ignoreTarget('default', 'replica');
} else {
unset($_SESSION['ignore_replica_server']);
}
}
}
示例12: 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());
}
示例13: 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.');
}
}
示例14: 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;
}
示例15: countNodesPerType
/**
* Cont how many nodes we have of each type.
*/
protected function countNodesPerType()
{
$result = Database::getConnection()->query("SELECT type, COUNT(*) AS num FROM {node} GROUP BY type")->fetchAllAssoc('type');
foreach ($result as $data) {
$this->count[$data->type] = $data->num;
}
}