From 7d4bba32ec2496febd90c8349603d6a98c6df830 Mon Sep 17 00:00:00 2001
From: catch <6915-catch@users.noreply.drupalcode.org>
Date: Sat, 21 Sep 2024 08:45:46 +0100
Subject: [PATCH] Issue #3475512 by daffie: Replace hardcoded database queries
 with dynamic queries

---
 core/lib/Drupal/Core/Batch/BatchStorage.php            | 10 ++++++----
 core/lib/Drupal/Core/Queue/Batch.php                   |  8 +++++++-
 core/modules/dblog/src/Controller/DbLogController.php  |  7 ++++++-
 .../dblog/src/Plugin/rest/resource/DbLogResource.php   |  5 ++++-
 core/modules/dblog/tests/src/Functional/DbLogTest.php  |  4 +++-
 core/modules/history/history.module                    |  9 +++++----
 .../history/tests/src/Functional/HistoryTest.php       |  5 ++++-
 core/modules/locale/locale.module                      |  5 ++++-
 core/modules/shortcut/src/ShortcutSetStorage.php       |  6 +++++-
 .../FunctionalTests/Entity/RevisionDeleteFormTest.php  |  6 +++++-
 .../FunctionalTests/Entity/RevisionRevertFormTest.php  |  6 +++++-
 11 files changed, 54 insertions(+), 17 deletions(-)

diff --git a/core/lib/Drupal/Core/Batch/BatchStorage.php b/core/lib/Drupal/Core/Batch/BatchStorage.php
index cce0379e2d64..46f9fb97c0d6 100644
--- a/core/lib/Drupal/Core/Batch/BatchStorage.php
+++ b/core/lib/Drupal/Core/Batch/BatchStorage.php
@@ -42,10 +42,12 @@ public function load($id) {
     // Ensure that a session is started before using the CSRF token generator.
     $this->session->start();
     try {
-      $batch = $this->connection->query("SELECT [batch] FROM {batch} WHERE [bid] = :bid AND [token] = :token", [
-        ':bid' => $id,
-        ':token' => $this->csrfToken->get($id),
-      ])->fetchField();
+      $batch = $this->connection->select('batch', 'b')
+        ->fields('b', ['batch'])
+        ->condition('bid', $id)
+        ->condition('token', $this->csrfToken->get($id))
+        ->execute()
+        ->fetchField();
     }
     catch (\Exception $e) {
       $this->catchException($e);
diff --git a/core/lib/Drupal/Core/Queue/Batch.php b/core/lib/Drupal/Core/Queue/Batch.php
index 53082a04df37..1b71959ba203 100644
--- a/core/lib/Drupal/Core/Queue/Batch.php
+++ b/core/lib/Drupal/Core/Queue/Batch.php
@@ -50,7 +50,13 @@ public function claimItem($lease_time = 0) {
   public function getAllItems() {
     $result = [];
     try {
-      $items = $this->connection->query('SELECT [data] FROM {queue} q WHERE [name] = :name ORDER BY [item_id] ASC', [':name' => $this->name])->fetchAll();
+      $items = $this->connection->select('queue', 'q')
+        ->fields('q', ['data'])
+        ->condition('name', $this->name)
+        ->orderBy('item_id', 'ASC')
+        ->execute()
+        ->fetchAll();
+
       foreach ($items as $item) {
         $result[] = unserialize($item->data);
       }
diff --git a/core/modules/dblog/src/Controller/DbLogController.php b/core/modules/dblog/src/Controller/DbLogController.php
index 134bc225807a..505996b40b26 100644
--- a/core/modules/dblog/src/Controller/DbLogController.php
+++ b/core/modules/dblog/src/Controller/DbLogController.php
@@ -227,7 +227,12 @@ public function overview(Request $request) {
    *   If no event found for the given ID.
    */
   public function eventDetails($event_id) {
-    $dblog = $this->database->query('SELECT [w].*, [u].[uid] FROM {watchdog} [w] LEFT JOIN {users} [u] ON [u].[uid] = [w].[uid] WHERE [w].[wid] = :id', [':id' => $event_id])->fetchObject();
+    $query = $this->database->select('watchdog', 'w')
+      ->fields('w')
+      ->condition('w.wid', $event_id);
+    $query->leftJoin('users', 'u', '[u].[uid] = [w].[uid]');
+    $query->addField('u', 'uid', 'uid');
+    $dblog = $query->execute()->fetchObject();
 
     if (empty($dblog)) {
       throw new NotFoundHttpException();
diff --git a/core/modules/dblog/src/Plugin/rest/resource/DbLogResource.php b/core/modules/dblog/src/Plugin/rest/resource/DbLogResource.php
index c3174469e5cf..d9de3987af98 100644
--- a/core/modules/dblog/src/Plugin/rest/resource/DbLogResource.php
+++ b/core/modules/dblog/src/Plugin/rest/resource/DbLogResource.php
@@ -40,7 +40,10 @@ class DbLogResource extends ResourceBase {
    */
   public function get($id = NULL) {
     if ($id) {
-      $record = Database::getConnection()->query("SELECT * FROM {watchdog} WHERE [wid] = :wid", [':wid' => $id])
+      $record = Database::getConnection()->select('watchdog', 'w')
+        ->fields('w')
+        ->condition('wid', $id)
+        ->execute()
         ->fetchAssoc();
       if (!empty($record)) {
         return new ResourceResponse($record);
diff --git a/core/modules/dblog/tests/src/Functional/DbLogTest.php b/core/modules/dblog/tests/src/Functional/DbLogTest.php
index b71679221498..7265819cf370 100644
--- a/core/modules/dblog/tests/src/Functional/DbLogTest.php
+++ b/core/modules/dblog/tests/src/Functional/DbLogTest.php
@@ -291,7 +291,9 @@ protected function testMessageParsing(): void {
         ['foo' => 'bar', 'path' => '/baz', 'value' => 'horse']
       );
     // View the log page to verify it's correct.
-    $wid = \Drupal::database()->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
+    $query = Database::getConnection()->select('watchdog');
+    $query->addExpression('MAX([wid])');
+    $wid = $query->execute()->fetchField();
     $this->drupalGet('admin/reports/dblog/event/' . $wid);
     $this->assertSession()
       ->responseContains('Incorrect parameter {bar} in path /baz: horse');
diff --git a/core/modules/history/history.module b/core/modules/history/history.module
index f30ec39d880e..ca271da5a765 100644
--- a/core/modules/history/history.module
+++ b/core/modules/history/history.module
@@ -81,10 +81,11 @@ function history_read_multiple($nids) {
     return $return;
   }
 
-  $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),
-  ]);
+  $result = \Drupal::database()->select('history', 'h')
+    ->fields('h', ['nid', 'timestamp'])
+    ->condition('uid', \Drupal::currentUser()->id())
+    ->condition('nid', array_keys($nodes_to_read), 'IN')
+    ->execute();
   foreach ($result as $row) {
     $nodes_to_read[$row->nid] = (int) $row->timestamp;
   }
diff --git a/core/modules/history/tests/src/Functional/HistoryTest.php b/core/modules/history/tests/src/Functional/HistoryTest.php
index 6b46431826a9..b2ef520f9fd7 100644
--- a/core/modules/history/tests/src/Functional/HistoryTest.php
+++ b/core/modules/history/tests/src/Functional/HistoryTest.php
@@ -158,7 +158,10 @@ public function testHistory(): void {
     $this->assertEquals(403, $response->getStatusCode());
 
     // Additional check to ensure that we did not forget to verify anything.
-    $rows = \Drupal::database()->query('SELECT * FROM {history}')->fetchAll();
+    $rows = \Drupal::database()->select('history')
+      ->fields('history', ['nid', 'uid', 'timestamp'])
+      ->execute()
+      ->fetchAll();
     $this->assertCount(1, $rows);
     $this->assertSame($this->user->id(), $rows[0]->uid);
     $this->assertSame($this->testNode->id(), $rows[0]->nid);
diff --git a/core/modules/locale/locale.module b/core/modules/locale/locale.module
index 88fbdfe04d5b..9124aa29cc7b 100644
--- a/core/modules/locale/locale.module
+++ b/core/modules/locale/locale.module
@@ -781,7 +781,10 @@ function locale_translation_get_file_history() {
 
   if (empty($history)) {
     // Get file history from the database.
-    $result = \Drupal::database()->query('SELECT [project], [langcode], [filename], [version], [uri], [timestamp], [last_checked] FROM {locale_file}');
+    $result = \Drupal::database()->select('locale_file')
+      ->fields('locale_file', ['project', 'langcode', 'filename', 'version', 'uri', 'timestamp', 'last_checked'])
+      ->execute()
+      ->fetchAll();
     foreach ($result as $file) {
       $file->type = $file->timestamp ? LOCALE_TRANSLATION_CURRENT : '';
       $history[$file->project][$file->langcode] = $file;
diff --git a/core/modules/shortcut/src/ShortcutSetStorage.php b/core/modules/shortcut/src/ShortcutSetStorage.php
index b68bf8b469b2..c2bccb9387c7 100644
--- a/core/modules/shortcut/src/ShortcutSetStorage.php
+++ b/core/modules/shortcut/src/ShortcutSetStorage.php
@@ -138,7 +138,11 @@ public function getDisplayedToUser(AccountInterface $account): ShortcutSetInterf
    * {@inheritdoc}
    */
   public function countAssignedUsers(ShortcutSetInterface $shortcut_set) {
-    return Database::getConnection()->query('SELECT COUNT(*) FROM {shortcut_set_users} WHERE [set_name] = :name', [':name' => $shortcut_set->id()])->fetchField();
+    return Database::getConnection()->select('shortcut_set_users')
+      ->condition('set_name', $shortcut_set->id())
+      ->countQuery()
+      ->execute()
+      ->fetchField();
   }
 
   /**
diff --git a/core/tests/Drupal/FunctionalTests/Entity/RevisionDeleteFormTest.php b/core/tests/Drupal/FunctionalTests/Entity/RevisionDeleteFormTest.php
index 16ff2a0103dc..e775b358550a 100644
--- a/core/tests/Drupal/FunctionalTests/Entity/RevisionDeleteFormTest.php
+++ b/core/tests/Drupal/FunctionalTests/Entity/RevisionDeleteFormTest.php
@@ -362,7 +362,11 @@ public static function providerSubmitForm(): array {
    *   Watchdog entries.
    */
   protected function getLogs(string $channel): array {
-    $logs = \Drupal::database()->query("SELECT * FROM {watchdog} WHERE type = :type", [':type' => $channel])->fetchAll();
+    $logs = \Drupal::database()->select('watchdog')
+      ->fields('watchdog')
+      ->condition('type', $channel)
+      ->execute()
+      ->fetchAll();
     return array_map(function (object $log) {
       return (string) new FormattableMarkup($log->message, unserialize($log->variables));
     }, $logs);
diff --git a/core/tests/Drupal/FunctionalTests/Entity/RevisionRevertFormTest.php b/core/tests/Drupal/FunctionalTests/Entity/RevisionRevertFormTest.php
index 356f38cf8c86..c6ff4629fd9b 100644
--- a/core/tests/Drupal/FunctionalTests/Entity/RevisionRevertFormTest.php
+++ b/core/tests/Drupal/FunctionalTests/Entity/RevisionRevertFormTest.php
@@ -347,7 +347,11 @@ protected function testPrepareRevision(): void {
    *   Watchdog entries.
    */
   protected function getLogs(string $channel): array {
-    $logs = \Drupal::database()->query("SELECT * FROM {watchdog} WHERE type = :type", [':type' => $channel])->fetchAll();
+    $logs = \Drupal::database()->select('watchdog')
+      ->fields('watchdog')
+      ->condition('type', $channel)
+      ->execute()
+      ->fetchAll();
     return array_map(function (object $log) {
       return (string) new FormattableMarkup($log->message, unserialize($log->variables));
     }, $logs);
-- 
GitLab