Unverified Commit 275c864d authored by larowlan's avatar larowlan

Issue #2875394 by voleger, erozqba, Berdir, mondrake: Replace all calls to...

Issue #2875394 by voleger, erozqba, Berdir, mondrake: Replace all calls to db_query, which is deprecated
parent 07a3820c
......@@ -44,15 +44,17 @@
* @return \Drupal\Core\Database\StatementInterface
* A prepared statement object, already executed.
*
* @deprecated as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get
* a database connection injected into your service from the container and
* call query() on it. For example,
* @deprecated in drupal:8.0.0 and will be removed from drupal:9.0.0. Instead,
* get a database connection injected into your service from the container
* and call query() on it. For example,
* $injected_database->query($query, $args, $options);
*
* @see https://www.drupal.org/node/2993033
* @see \Drupal\Core\Database\Connection::query()
* @see \Drupal\Core\Database\Connection::defaultOptions()
*/
function db_query($query, array $args = [], array $options = []) {
@trigger_error('db_query() is deprecated in drupal:8.0.0. It will be removed before drupal:9.0.0. Instead, get a database connection injected into your service from the container and call query() on it. For example, $injected_database->query($query, $args, $options). See https://www.drupal.org/node/2993033', E_USER_DEPRECATED);
return Database::getConnection(_db_get_target($options))->query($query, $args, $options);
}
......
......@@ -625,7 +625,9 @@ function template_preprocess_form_element_label(&$variables) {
* if (empty($context['sandbox'])) {
* $context['sandbox']['progress'] = 0;
* $context['sandbox']['current_id'] = 0;
* $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT id) FROM {example}')->fetchField();
* $context['sandbox']['max'] = \Drupal::database()
* ->query('SELECT COUNT(DISTINCT id) FROM {example}')
* ->fetchField();
* }
* $limit = 5;
* $result = db_select('example')
......
......@@ -1028,7 +1028,7 @@ public function escapeAlias($field) {
* For example, the following does a case-insensitive query for all rows whose
* name starts with $prefix:
* @code
* $result = db_query(
* $result = $injected_connection->query(
* 'SELECT * FROM person WHERE name LIKE :pattern',
* array(':pattern' => $injected_connection->escapeLike($prefix) . '%')
* );
......
......@@ -112,7 +112,7 @@ protected function connect() {
*/
protected function checkEncoding() {
try {
if (db_query('SHOW server_encoding')->fetchField() == 'UTF8') {
if (Database::getConnection()->query('SHOW server_encoding')->fetchField() == 'UTF8') {
$this->pass(t('Database is encoded in UTF-8'));
}
else {
......@@ -147,7 +147,7 @@ public function checkBinaryOutput() {
// value.
$query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET bytea_output = 'escape';";
try {
db_query($query);
$database_connection->query($query);
}
catch (\Exception $e) {
// Ignore possible errors when the user doesn't have the necessary
......@@ -177,7 +177,7 @@ public function checkBinaryOutput() {
* Verify that a binary data roundtrip returns the original string.
*/
protected function checkBinaryOutputSuccess() {
$bytea_output = db_query("SHOW bytea_output")->fetchField();
$bytea_output = Database::getConnection()->query("SHOW bytea_output")->fetchField();
return ($bytea_output == 'escape');
}
......
......@@ -147,16 +147,16 @@ public function findCaller() {
// If the call was made from a function, 'class' will be empty. It's
// just easier to give it a default value than to try and integrate
// that into the if statement below.
if (empty($stack[$i]['class'])) {
$stack[$i]['class'] = '';
if (empty($stack[$i + 1]['class'])) {
$stack[$i + 1]['class'] = '';
}
if (strpos($stack[$i]['class'], __NAMESPACE__) === FALSE && strpos($stack[$i + 1]['function'], 'db_') === FALSE && !empty($stack[$i]['file'])) {
if (strpos($stack[$i + 1]['class'], __NAMESPACE__) === FALSE && strpos($stack[$i + 1]['function'], 'db_') === FALSE && !empty($stack[$i]['file'])) {
$stack[$i] += ['file' => '?', 'line' => '?', 'args' => []];
return [
'file' => $stack[$i]['file'],
'line' => $stack[$i]['line'],
'function' => $stack[$i + 1]['function'],
'class' => isset($stack[$i + 1]['class']) ? $stack[$i + 1]['class'] : NULL,
'class' => $stack[$i + 1]['class'],
'type' => isset($stack[$i + 1]['type']) ? $stack[$i + 1]['type'] : NULL,
'args' => $stack[$i + 1]['args'],
];
......
......@@ -343,9 +343,9 @@ public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments =
*
* @deprecated as of Drupal 8.1.x, will be removed in Drupal 9.0.0. Instead,
* change the query to use leftJoin(). For instance:
* db_query('A')->rightJoin('B') is identical to
* db_query('B')->leftJoin('A'). This functionality has been deprecated
* because SQLite does not support it.
* $injected_connection->query('A')->rightJoin('B') is identical to
* $injected_connection->query('B')->leftJoin('A'). This functionality has
* been deprecated because SQLite does not support it.
*
* @see https://www.drupal.org/node/2765249
*/
......
......@@ -34,7 +34,7 @@ public function testIPAddressValidation() {
$edit = [];
$edit['ip'] = '1.2.3.3';
$this->drupalPostForm('admin/config/people/ban', $edit, t('Add'));
$ip = db_query("SELECT iid from {ban_ip} WHERE ip = :ip", [':ip' => $edit['ip']])->fetchField();
$ip = $connection->query("SELECT iid from {ban_ip} WHERE ip = :ip", [':ip' => $edit['ip']])->fetchField();
$this->assertTrue($ip, 'IP address found in database.');
$this->assertRaw(t('The IP address %ip has been banned.', ['%ip' => $edit['ip']]), 'IP address was banned.');
......@@ -65,7 +65,7 @@ public function testIPAddressValidation() {
// Pass an IP address as a URL parameter and submit it.
$submit_ip = '1.2.3.4';
$this->drupalPostForm('admin/config/people/ban/' . $submit_ip, [], t('Add'));
$ip = db_query("SELECT iid from {ban_ip} WHERE ip = :ip", [':ip' => $submit_ip])->fetchField();
$ip = $connection->query("SELECT iid from {ban_ip} WHERE ip = :ip", [':ip' => $submit_ip])->fetchField();
$this->assertTrue($ip, 'IP address found in database');
$this->assertRaw(t('The IP address %ip has been banned.', ['%ip' => $submit_ip]), 'IP address was banned.');
......
......@@ -8,6 +8,7 @@
use Drupal\big_pipe_test\BigPipePlaceholderTestCases;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Html;
use Drupal\Core\Database\Database;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
......@@ -146,7 +147,8 @@ public function testBigPipe() {
$this->assertSessionCookieExists(TRUE);
$this->assertBigPipeNoJsCookieExists(FALSE);
$log_count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
$connection = Database::getConnection();
$log_count = $connection->query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
// By not calling performMetaRefresh() here, we simulate JavaScript being
// enabled, because as far as the BigPipe module is concerned, JavaScript is
......@@ -184,8 +186,8 @@ public function testBigPipe() {
$this->assertTrue(in_array('big_pipe/big_pipe', explode(',', $this->getDrupalSettings()['ajaxPageState']['libraries'])), 'BigPipe asset library is present.');
// Verify that the two expected exceptions are logged as errors.
$this->assertEqual($log_count + 2, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), 'Two new watchdog entries.');
$records = db_query('SELECT * FROM {watchdog} ORDER BY wid DESC LIMIT 2')->fetchAll();
$this->assertEqual($log_count + 2, $connection->query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), 'Two new watchdog entries.');
$records = $connection->query('SELECT * FROM {watchdog} ORDER BY wid DESC LIMIT 2')->fetchAll();
$this->assertEqual(RfcLogLevel::ERROR, $records[0]->severity);
$this->assertTrue(FALSE !== strpos((string) unserialize($records[0]->variables)['@message'], 'Oh noes!'));
$this->assertEqual(RfcLogLevel::ERROR, $records[1]->severity);
......
......@@ -221,7 +221,7 @@ public function testFailedBlockCreation() {
$this->assertTrue($id, 'Transactions not supported, and block found in database.');
// Check that the failed rollback was logged.
$records = db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
$records = $connection->query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
$this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
}
}
......
......@@ -3,6 +3,7 @@
namespace Drupal\Tests\block_content\Functional;
use Drupal\block_content\Entity\BlockContent;
use Drupal\Core\Database\Database;
/**
* Tests $block_content->save() for saving content.
......@@ -32,7 +33,7 @@ protected function setUp() {
*/
public function testImport() {
// Custom block ID must be a number that is not in the database.
$max_id = db_query('SELECT MAX(id) FROM {block_content}')->fetchField();
$max_id = Database::getConnection()->query('SELECT MAX(id) FROM {block_content}')->fetchField();
$test_id = $max_id + mt_rand(1000, 1000000);
$info = $this->randomMachineName(8);
$block_array = [
......
......@@ -4,6 +4,7 @@
use Drupal\block_content\Entity\BlockContent;
use Drupal\block_content\Entity\BlockContentType;
use Drupal\Core\Database\Database;
use Drupal\Tests\content_translation\Functional\ContentTranslationUITestBase;
/**
......@@ -170,7 +171,7 @@ public function testDisabledBundle() {
$disabled_block_content = $this->createBlockContent(FALSE, $bundle->id());
// Make sure that only a single row was inserted into the block table.
$rows = db_query('SELECT * FROM {block_content_field_data} WHERE id = :id', [':id' => $enabled_block_content->id()])->fetchAll();
$rows = Database::getConnection()->query('SELECT * FROM {block_content_field_data} WHERE id = :id', [':id' => $enabled_block_content->id()])->fetchAll();
$this->assertEqual(1, count($rows));
}
......
......@@ -91,7 +91,7 @@ function dblog_cron() {
* List of uniquely defined database log message types.
*/
function _dblog_get_message_types() {
return db_query('SELECT DISTINCT(type) FROM {watchdog} ORDER BY type')
return \Drupal::database()->query('SELECT DISTINCT(type) FROM {watchdog} ORDER BY type')
->fetchAllKeyed(0, 0);
}
......
......@@ -2,6 +2,7 @@
namespace Drupal\dblog\Plugin\rest\resource;
use Drupal\Core\Database\Database;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
......@@ -38,7 +39,7 @@ class DBLogResource extends ResourceBase {
*/
public function get($id = NULL) {
if ($id) {
$record = db_query("SELECT * FROM {watchdog} WHERE wid = :wid", [':wid' => $id])
$record = Database::getConnection()->query("SELECT * FROM {watchdog} WHERE wid = :wid", [':wid' => $id])
->fetchAssoc();
if (!empty($record)) {
return new ResourceResponse($record);
......
......@@ -103,7 +103,7 @@ public function testLogEventPage() {
'timestamp' => REQUEST_TIME,
];
\Drupal::service('logger.dblog')->log(RfcLogLevel::NOTICE, 'Test message', $context);
$wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
$wid = Database::getConnection()->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
// Verify the links appear correctly.
$this->drupalGet('admin/reports/dblog/event/' . $wid);
......@@ -251,7 +251,7 @@ private function verifyReports($response = 200) {
}
// View the database log event page.
$wid = db_query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
$wid = Database::getConnection()->query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
$this->drupalGet('admin/reports/dblog/event/' . $wid);
$this->assertResponse($response);
if ($response == 200) {
......@@ -264,7 +264,7 @@ private function verifyReports($response = 200) {
*/
private function verifyBreadcrumbs() {
// View the database log event page.
$wid = db_query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
$wid = Database::getConnection()->query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
$this->drupalGet('admin/reports/dblog/event/' . $wid);
$xpath = '//nav[@class="breadcrumb"]/ol/li[last()]/a';
$this->assertEqual(current($this->xpath($xpath))->getText(), 'Recent log messages', 'DBLogs link displayed at breadcrumb in event page.');
......@@ -347,7 +347,7 @@ private function doUser() {
// Log out user.
$this->drupalLogout();
// Fetch the row IDs in watchdog that relate to the user.
$result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', [':uid' => $user->id()]);
$result = Database::getConnection()->query('SELECT wid FROM {watchdog} WHERE uid = :uid', [':uid' => $user->id()]);
foreach ($result as $row) {
$ids[] = $row->wid;
}
......@@ -517,8 +517,9 @@ private function getContentUpdate($type) {
*/
public function testDBLogAddAndClear() {
global $base_root;
$connection = Database::getConnection();
// Get a count of how many watchdog entries already exist.
$count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
$count = $connection->query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
$log = [
'channel' => 'system',
'message' => 'Log entry added to test the doClearTest clear down.',
......@@ -534,7 +535,7 @@ public function testDBLogAddAndClear() {
// Add a watchdog entry.
$this->container->get('logger.dblog')->log($log['severity'], $log['message'], $log);
// Make sure the table count has actually been incremented.
$this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('\Drupal\dblog\Logger\DbLog->log() added an entry to the dblog :count', [':count' => $count]));
$this->assertEqual($count + 1, $connection->query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('\Drupal\dblog\Logger\DbLog->log() added an entry to the dblog :count', [':count' => $count]));
// Log in the admin user.
$this->drupalLogin($this->adminUser);
// Post in order to clear the database table.
......@@ -542,7 +543,7 @@ public function testDBLogAddAndClear() {
// Confirm that the logs should be cleared.
$this->drupalPostForm(NULL, [], 'Confirm');
// Count the rows in watchdog that previously related to the deleted user.
$count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
$count = $connection->query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
$this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', [':count' => $count]));
}
......@@ -731,7 +732,7 @@ public function testTemporaryUser() {
// Generate a single watchdog entry.
$this->generateLogEntries(1, ['user' => $tempuser, 'uid' => $tempuser_uid]);
$wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
$wid = Database::getConnection()->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
// Check if the full message displays on the details page.
$this->drupalGet('admin/reports/dblog/event/' . $wid);
......@@ -761,7 +762,7 @@ public function testOverviewLinks() {
// Make sure HTML tags are filtered out in admin/reports/dblog/event/ too.
$this->generateLogEntries(1, ['message' => "<script>alert('foo');</script> <strong>Lorem ipsum</strong>"]);
$wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
$wid = Database::getConnection()->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
$this->drupalGet('admin/reports/dblog/event/' . $wid);
$this->assertNoRaw("<script>alert('foo');</script>");
$this->assertRaw("alert('foo'); <strong>Lorem ipsum</strong>");
......
......@@ -2,6 +2,7 @@
namespace Drupal\Tests\dblog\Kernel;
use Drupal\Core\Database\Database;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\dblog\Functional\FakeLogEntries;
......@@ -38,7 +39,7 @@ public function testDbLogCron() {
// Generate additional log entries.
$this->generateLogEntries($row_limit + 10);
// Verify that the database log row count exceeds the row limit.
$count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField();
$count = Database::getConnection()->query('SELECT COUNT(wid) FROM {watchdog}')->fetchField();
$this->assertGreaterThan($row_limit, $count, format_string('Dblog row count of @count exceeds row limit of @limit', ['@count' => $count, '@limit' => $row_limit]));
// Get the number of enabled modules. Cron adds a log entry for each module.
......@@ -60,16 +61,17 @@ public function testDbLogCron() {
* Number of new watchdog entries.
*/
private function runCron() {
$connection = Database::getConnection();
// Get last ID to compare against; log entries get deleted, so we can't
// reliably add the number of newly created log entries to the current count
// to measure number of log entries created by cron.
$last_id = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
$last_id = $connection->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
// Run a cron job.
$this->container->get('cron')->run();
// Get last ID after cron was run.
$current_id = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
$current_id = $connection->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
return $current_id - $last_id;
}
......
......@@ -81,7 +81,7 @@ function history_read_multiple($nids) {
return $return;
}
$result = db_query('SELECT nid, timestamp FROM {history} WHERE uid = :uid AND nid IN ( :nids[] )', [
$result = \Drupal::database()->query('SELECT nid, timestamp FROM {history} WHERE uid = :uid AND nid IN ( :nids[] )', [
':uid' => \Drupal::currentUser()->id(),
':nids[]' => array_keys($nodes_to_read),
]);
......
......@@ -820,7 +820,7 @@ function locale_translation_get_file_history() {
if (empty($history)) {
// Get file history from the database.
$result = db_query('SELECT project, langcode, filename, version, uri, timestamp, last_checked FROM {locale_file}');
$result = \Drupal::database()->query('SELECT project, langcode, filename, version, uri, timestamp, last_checked FROM {locale_file}');
foreach ($result as $file) {
$file->type = $file->timestamp ? LOCALE_TRANSLATION_CURRENT : '';
$history[$file->project][$file->langcode] = $file;
......
......@@ -3,6 +3,7 @@
namespace Drupal\Tests\locale\Functional;
use Drupal\Core\Url;
use Drupal\Core\Database\Database;
use Drupal\Tests\BrowserTestBase;
use Drupal\Core\Language\LanguageInterface;
......@@ -185,7 +186,7 @@ public function testStandalonePoFile() {
// The database should now contain 6 customized strings (two imported
// strings are not translated).
$count = db_query('SELECT COUNT(*) FROM {locales_target} WHERE customized = :custom', [':custom' => 1])->fetchField();
$count = Database::getConnection()->query('SELECT COUNT(*) FROM {locales_target} WHERE customized = :custom', [':custom' => 1])->fetchField();
$this->assertEqual($count, 6, 'Customized translations successfully imported.');
// Try importing a .po file with overriding strings, and ensure existing
......
......@@ -3,6 +3,7 @@
namespace Drupal\Tests\locale\Functional;
use Drupal\Component\Gettext\PoItem;
use Drupal\Core\Database\Database;
use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
use Drupal\Tests\BrowserTestBase;
......@@ -187,7 +188,7 @@ public function testPluralEditDateFormatter() {
// not save our source string for performance optimization if we do not ask
// specifically for a language.
\Drupal::translation()->formatPlural(1, '1 second', '@count seconds', [], ['langcode' => 'fr'])->render();
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 second" . PoItem::DELIMITER . "@count seconds"])->fetchField();
$lid = Database::getConnection()->query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 second" . PoItem::DELIMITER . "@count seconds"])->fetchField();
// Look up editing page for this plural string and check fields.
$search = [
'string' => '1 second',
......@@ -270,8 +271,9 @@ public function testPluralEditExport() {
$this->assertText('@count sata');
$this->assertText('@count sati');
$connection = Database::getConnection();
// Edit langcode hr translations and see if that took effect.
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 hour" . PoItem::DELIMITER . "@count hours"])->fetchField();
$lid = $connection->query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 hour" . PoItem::DELIMITER . "@count hours"])->fetchField();
$edit = [
"strings[$lid][translations][1]" => '@count sata edited',
];
......@@ -297,7 +299,7 @@ public function testPluralEditExport() {
// not save our source string for performance optimization if we do not ask
// specifically for a language.
\Drupal::translation()->formatPlural(1, '1 day', '@count days', [], ['langcode' => 'fr'])->render();
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 day" . PoItem::DELIMITER . "@count days"])->fetchField();
$lid = $connection->query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 day" . PoItem::DELIMITER . "@count days"])->fetchField();
// Look up editing page for this plural string and check fields.
$search = [
'string' => '1 day',
......
......@@ -301,7 +301,7 @@ protected function setCurrentTranslations() {
* (optional) A message to display with the assertion.
*/
protected function assertTranslation($source, $translation, $langcode, $message = '') {
$db_translation = db_query('SELECT translation FROM {locales_target} lt INNER JOIN {locales_source} ls ON ls.lid = lt.lid WHERE ls.source = :source AND lt.language = :langcode', [':source' => $source, ':langcode' => $langcode])->fetchField();
$db_translation = Database::getConnection()->query('SELECT translation FROM {locales_target} lt INNER JOIN {locales_source} ls ON ls.lid = lt.lid WHERE ls.source = :source AND lt.language = :langcode', [':source' => $source, ':langcode' => $langcode])->fetchField();
$db_translation = $db_translation == FALSE ? '' : $db_translation;
$this->assertEqual($translation, $db_translation, $message ? $message : format_string('Correct translation of %source (%language)', ['%source' => $source, '%language' => $langcode]));
}
......
......@@ -2,6 +2,7 @@
namespace Drupal\Tests\locale\Functional;
use Drupal\Core\Database\Database;
use Drupal\Core\Language\LanguageInterface;
/**
......@@ -346,14 +347,15 @@ public function testEnableLanguage() {
$this->assertTranslation('Extraday', 'extra dag', 'nl');
// Check if the language data is added to the database.
$result = db_query("SELECT project FROM {locale_file} WHERE langcode='nl'")->fetchField();
$connection = Database::getConnection();
$result = $connection->query("SELECT project FROM {locale_file} WHERE langcode='nl'")->fetchField();
$this->assertTrue($result, 'Files added to file history');
// Remove a language.
$this->drupalPostForm('admin/config/regional/language/delete/nl', [], t('Delete'));
// Check if the language data is removed from the database.
$result = db_query("SELECT project FROM {locale_file} WHERE langcode='nl'")->fetchField();
$result = $connection->query("SELECT project FROM {locale_file} WHERE langcode='nl'")->fetchField();
$this->assertFalse($result, 'Files removed from file history');
// Check that the Dutch translation is gone.
......
......@@ -380,7 +380,7 @@ function hook_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Se
* @ingroup entity_crud
*/
function hook_node_search_result(\Drupal\node\NodeInterface $node) {
$rating = db_query('SELECT SUM(points) FROM {my_rating} WHERE nid = :nid', ['nid' => $node->id()])->fetchField();
$rating = \Drupal::database()->query('SELECT SUM(points) FROM {my_rating} WHERE nid = :nid', ['nid' => $node->id()])->fetchField();
return ['rating' => \Drupal::translation()->formatPlural($rating, '1 point', '@count points')];
}
......@@ -400,7 +400,7 @@ function hook_node_search_result(\Drupal\node\NodeInterface $node) {
*/
function hook_node_update_index(\Drupal\node\NodeInterface $node) {
$text = '';
$ratings = db_query('SELECT title, description FROM {my_ratings} WHERE nid = :nid', [':nid' => $node->id()]);
$ratings = \Drupal::database()->query('SELECT title, description FROM {my_ratings} WHERE nid = :nid', [':nid' => $node->id()]);
foreach ($ratings as $rating) {
$text .= '<h2>' . Html::escape($rating->title) . '</h2>' . Xss::filter($rating->description);
}
......
......@@ -2,6 +2,7 @@
namespace Drupal\Tests\node\Functional;
use Drupal\Core\Database\Database;
use Drupal\node\Entity\NodeType;
/**
......@@ -122,8 +123,9 @@ public function testNodeAccessBasic() {
$this->nodesByUser[$this->webUser->id()][$node->id()] = $is_private;
}
}
$this->publicTid = db_query('SELECT tid FROM {taxonomy_term_field_data} WHERE name = :name AND default_langcode = 1', [':name' => 'public'])->fetchField();
$this->privateTid = db_query('SELECT tid FROM {taxonomy_term_field_data} WHERE name = :name AND default_langcode = 1', [':name' => 'private'])->fetchField();
$connection = Database::getConnection();
$this->publicTid = $connection->query('SELECT tid FROM {taxonomy_term_field_data} WHERE name = :name AND default_langcode = 1', [':name' => 'public'])->fetchField();
$this->privateTid = $connection->query('SELECT tid FROM {taxonomy_term_field_data} WHERE name = :name AND default_langcode = 1', [':name' => 'private'])->fetchField();
$this->assertTrue($this->publicTid, 'Public tid was found');
$this->assertTrue($this->privateTid, 'Private tid was found');
foreach ($simple_users as $this->webUser) {
......
......@@ -274,7 +274,7 @@ protected static function getWatchdogIdsForTestExceptionRollback() {
// PostgreSQL doesn't support bytea LIKE queries, so we need to unserialize
// first to check for the rollback exception message.
$matches = [];
$query = db_query("SELECT wid, variables FROM {watchdog}");
$query = Database::getConnection()->query("SELECT wid, variables FROM {watchdog}");
foreach ($query as $row) {
$variables = (array) unserialize($row->variables);
if (isset($variables['@message']) && $variables['@message'] === 'Test exception for rollback.') {
......@@ -292,7 +292,7 @@ protected static function getWatchdogIdsForTestExceptionRollback() {
* records with the explicit rollback failed exception message.
*/
protected static function getWatchdogIdsForFailedExplicitRollback() {
return db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
return Database::getConnection()->query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
}
}
......@@ -102,9 +102,10 @@ public function testNodeRevisionAccessAnyType() {
$permutations = $this->generatePermutations($parameters);
$node_revision_access = \Drupal::service('access_check.node.revision');
$connection = \Drupal::database();
foreach ($permutations as $case) {
// Skip this test if there are no revisions for the node.
if (!($revision->isDefaultRevision() && (db_query('SELECT COUNT(vid) FROM {node_field_revision} WHERE nid = :nid', [':nid' => $revision->id()])->fetchField() == 1 || $case['op'] == 'update' || $case['op'] == 'delete'))) {
if (!($revision->isDefaultRevision() && ($connection->query('SELECT COUNT(vid) FROM {node_field_revision} WHERE nid = :nid', [':nid' => $revision->id()])->fetchField() == 1 || $case['op'] == 'update' || $case['op'] == 'delete'))) {
if (!empty($case['account']->is_admin) || $case['account']->hasPermission($this->map[$case['op']])) {
$this->assertTrue($node_revision_access->checkAccess($revision, $case['account'], $case['op']), "{$this->map[$case['op']]} granted.");
}
......@@ -150,9 +151,10 @@ public function testNodeRevisionAccessPerType() {
$permutations = $this->generatePermutations($parameters);
$node_revision_access = \Drupal::service('access_check.node.revision');
$connection = \Drupal::database();
foreach ($permutations as $case) {
// Skip this test if there are no revisions for the node.
if (!($revision->isDefaultRevision() && (db_query('SELECT COUNT(vid) FROM {node_field_revision} WHERE nid = :nid', [':nid' => $revision->id()])->fetchField() == 1 || $case['op'] == 'update' || $case['op'] == 'delete'))) {
if (!($revision->isDefaultRevision() && ($connection->query('SELECT COUNT(vid) FROM {node_field_revision} WHERE nid = :nid', [':nid' => $revision->id()])->fetchField() == 1 || $case['op'] == 'update' || $case['op'] == 'delete'))) {
if (!empty($case['account']->is_admin) || $case['account']->hasPermission($this->typeMap[$case['op']])) {
$this->assertTrue($node_revision_access->checkAccess($revision, $case['account'], $case['op']), "{$this->typeMap[$case['op']]} granted.");
}
......
......@@ -179,7 +179,7 @@ public function testRevisions() {
]),
'Revision deleted.');
$connection = Database::getConnection();
$this->assertTrue(db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid and vid = :vid',
$this->assertTrue($connection->query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid and vid = :vid',
[':nid' => $node->id(), ':vid' => $nodes[1]->getRevisionId()])->fetchField() == 0,
'Revision not found.');
......
......@@ -186,8 +186,8 @@ public function testRevisions() {
'%title' => $nodes[1]->label(),
]), 'Revision deleted.');
$connection = Database::getConnection();