From b48e1e7438705be775b22298eb74354a528880b5 Mon Sep 17 00:00:00 2001
From: Nathaniel Catchpole <catch@35733.no-reply.drupal.org>
Date: Fri, 21 Sep 2018 14:01:49 +0100
Subject: [PATCH] Issue #2873684 by voleger, longwave, jeetendrakumar,
 andypost, mondrake, catch: Replace all calls to db_select, which is
 deprecated

---
 core/includes/database.inc                    |  1 +
 core/lib/Drupal/Core/Entity/entity.api.php    |  4 +-
 .../src/Functional/IpAddressBlockingTest.php  |  6 +-
 .../Functional/BlockContentCreationTest.php   |  7 ++-
 core/modules/book/src/BookOutlineStorage.php  |  2 +-
 .../src/Plugin/views/filter/UserUid.php       |  3 +-
 core/modules/dblog/dblog.module               |  2 +-
 .../field/tests/src/Kernel/BulkDeleteTest.php |  3 +-
 .../tests/src/Kernel/FieldDataCountTest.php   |  3 +-
 .../file/tests/src/Kernel/UsageTest.php       |  8 +--
 .../src/Plugin/Block/ActiveTopicsBlock.php    |  4 +-
 .../forum/src/Plugin/Block/NewTopicsBlock.php |  4 +-
 core/modules/locale/locale.bulk.inc           |  2 +-
 core/modules/locale/locale.translation.inc    |  2 +-
 .../Functional/LocaleTranslationUiTest.php    |  3 +-
 .../node/src/Plugin/Search/NodeSearch.php     |  3 +-
 ...NodeAccessLanguageAwareCombinationTest.php | 15 ++---
 .../NodeAccessLanguageAwareTest.php           | 15 ++---
 .../src/Functional/NodeAccessLanguageTest.php | 10 ++--
 .../tests/src/Functional/NodeAdminTest.php    |  4 +-
 .../src/Functional/NodeQueryAlterTest.php     | 10 ++--
 .../src/Functional/NodeRevisionsTest.php      |  2 +-
 .../src/Plugin/views/argument/Search.php      |  4 +-
 .../search/src/Plugin/views/filter/Search.php |  4 +-
 core/modules/search/src/SearchQuery.php       |  5 +-
 .../SearchMultilingualEntityTest.php          |  7 ++-
 .../tests/src/Kernel/SearchMatchTest.php      |  8 ++-
 .../shortcut/src/ShortcutSetStorage.php       |  2 +-
 core/modules/statistics/statistics.module     |  2 +-
 .../src/Functional/StatisticsAdminTest.php    |  8 ++-
 .../src/Tests/Module/ModuleTestBase.php       |  2 +-
 .../src/Controller/DatabaseTestController.php | 10 ++--
 .../src/Form/DatabaseTestForm.php             |  3 +-
 .../src/Controller/PagerTestController.php    |  4 +-
 .../Database/SelectPagerDefaultTest.php       | 15 +++--
 .../Database/TemporaryQueryTest.php           |  2 +-
 .../src/Functional/Module/ModuleTestBase.php  |  2 +-
 .../Plugin/views/argument/IndexTidDepth.php   |  3 +-
 .../views/filter/TaxonomyIndexTidDepth.php    |  3 +-
 .../views/relationship/NodeTermData.php       |  3 +-
 core/modules/taxonomy/src/TermStorage.php     |  2 +-
 core/modules/taxonomy/taxonomy.tokens.inc     |  2 +-
 .../src/Functional/TaxonomyQueryAlterTest.php |  6 +-
 core/modules/tracker/tracker.pages.inc        |  5 +-
 .../tests/src/Functional/UserDeleteTest.php   |  6 +-
 .../tests/src/Kernel/Plugin/JoinTest.php      |  5 +-
 .../Core/Cache/DatabaseBackendTagTest.php     |  6 +-
 .../KernelTests/Core/Database/AlterTest.php   | 16 ++---
 .../Core/Database/BasicSyntaxTest.php         |  8 +--
 .../Core/Database/DatabaseLegacyTest.php      | 10 ++++
 .../Core/Database/DeleteTruncateTest.php      |  2 +-
 .../KernelTests/Core/Database/FetchTest.php   |  2 +-
 .../KernelTests/Core/Database/InsertTest.php  |  4 +-
 .../Core/Database/InvalidDataTest.php         |  6 +-
 .../KernelTests/Core/Database/QueryTest.php   | 10 ++--
 .../Core/Database/SelectCloneTest.php         |  4 +-
 .../Core/Database/SelectComplexTest.php       | 44 +++++++-------
 .../Core/Database/SelectOrderedTest.php       |  6 +-
 .../Core/Database/SelectSubqueryTest.php      | 42 +++++++-------
 .../KernelTests/Core/Database/SelectTest.php  | 58 +++++++++----------
 .../Core/Database/SerializeQueryTest.php      |  2 +-
 .../KernelTests/Core/Database/TaggingTest.php | 14 ++---
 .../Core/Database/UpdateComplexTest.php       |  2 +-
 .../Core/Entity/FieldSqlStorageTest.php       |  9 +--
 64 files changed, 262 insertions(+), 209 deletions(-)

diff --git a/core/includes/database.inc b/core/includes/database.inc
index 7e2fe41ef101..1b133263eb41 100644
--- a/core/includes/database.inc
+++ b/core/includes/database.inc
@@ -300,6 +300,7 @@ function db_truncate($table, array $options = []) {
  * @see \Drupal\Core\Database\Connection::defaultOptions()
  */
 function db_select($table, $alias = NULL, array $options = []) {
+  @trigger_error('db_select() is deprecated in Drupal 8.0.x and will be removed before Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call call select() on it. For example, $injected_database->db_select($table, $alias, $options); See https://www.drupal.org/node/2993033', E_USER_DEPRECATED);
   if (empty($options['target'])) {
     $options['target'] = 'default';
   }
diff --git a/core/lib/Drupal/Core/Entity/entity.api.php b/core/lib/Drupal/Core/Entity/entity.api.php
index c4e9b84e4f74..414087fbf8cc 100644
--- a/core/lib/Drupal/Core/Entity/entity.api.php
+++ b/core/lib/Drupal/Core/Entity/entity.api.php
@@ -1286,7 +1286,7 @@ function hook_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
   // upon entity deletion.
   $id = $entity->id();
   $type = $entity->getEntityTypeId();
-  $count = db_select('example_entity_data')
+  $count = \Drupal::database()->select('example_entity_data')
     ->condition('type', $type)
     ->condition('id', $id)
     ->countQuery()
@@ -1315,7 +1315,7 @@ function hook_ENTITY_TYPE_predelete(Drupal\Core\Entity\EntityInterface $entity)
   // upon entity deletion.
   $id = $entity->id();
   $type = $entity->getEntityTypeId();
-  $count = db_select('example_entity_data')
+  $count = \Drupal::database()->select('example_entity_data')
     ->condition('type', $type)
     ->condition('id', $id)
     ->countQuery()
diff --git a/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php b/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php
index 778f3dba9751..d2e75963cd81 100644
--- a/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php
+++ b/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php
@@ -28,6 +28,7 @@ public function testIPAddressValidation() {
     $admin_user = $this->drupalCreateUser(['ban IP addresses']);
     $this->drupalLogin($admin_user);
     $this->drupalGet('admin/config/people/ban');
+    $connection = Database::getConnection();
 
     // Ban a valid IP address.
     $edit = [];
@@ -78,13 +79,12 @@ public function testIPAddressValidation() {
 
     // Test duplicate ip address are not present in the 'blocked_ips' table.
     // when they are entered programmatically.
-    $connection = Database::getConnection();
     $banIp = new BanIpManager($connection);
     $ip = '1.0.0.0';
     $banIp->banIp($ip);
     $banIp->banIp($ip);
     $banIp->banIp($ip);
-    $query = db_select('ban_ip', 'bip');
+    $query = $connection->select('ban_ip', 'bip');
     $query->fields('bip', ['iid']);
     $query->condition('bip.ip', $ip);
     $ip_count = $query->execute()->fetchAll();
@@ -92,7 +92,7 @@ public function testIPAddressValidation() {
     $ip = '';
     $banIp->banIp($ip);
     $banIp->banIp($ip);
-    $query = db_select('ban_ip', 'bip');
+    $query = $connection->select('ban_ip', 'bip');
     $query->fields('bip', ['iid']);
     $query->condition('bip.ip', $ip);
     $ip_count = $query->execute()->fetchAll();
diff --git a/core/modules/block_content/tests/src/Functional/BlockContentCreationTest.php b/core/modules/block_content/tests/src/Functional/BlockContentCreationTest.php
index 46768d694b24..ba24646983a5 100644
--- a/core/modules/block_content/tests/src/Functional/BlockContentCreationTest.php
+++ b/core/modules/block_content/tests/src/Functional/BlockContentCreationTest.php
@@ -201,9 +201,10 @@ public function testFailedBlockCreation() {
       $this->pass('Expected exception has been thrown.');
     }
 
-    if (Database::getConnection()->supportsTransactions()) {
+    $connection = Database::getConnection();
+    if ($connection->supportsTransactions()) {
       // Check that the block does not exist in the database.
-      $id = db_select('block_content_field_data', 'b')
+      $id = $connection->select('block_content_field_data', 'b')
         ->fields('b', ['id'])
         ->condition('info', 'fail_creation')
         ->execute()
@@ -212,7 +213,7 @@ public function testFailedBlockCreation() {
     }
     else {
       // Check that the block exists in the database.
-      $id = db_select('block_content_field_data', 'b')
+      $id = $connection->select('block_content_field_data', 'b')
         ->fields('b', ['id'])
         ->condition('info', 'fail_creation')
         ->execute()
diff --git a/core/modules/book/src/BookOutlineStorage.php b/core/modules/book/src/BookOutlineStorage.php
index 4f61b5c00547..2224bb669e3c 100644
--- a/core/modules/book/src/BookOutlineStorage.php
+++ b/core/modules/book/src/BookOutlineStorage.php
@@ -186,7 +186,7 @@ public function countOriginalLinkChildren($original) {
    * {@inheritdoc}
    */
   public function getBookSubtree($link, $max_depth) {
-    $query = db_select('book', 'b', ['fetch' => \PDO::FETCH_ASSOC]);
+    $query = $this->connection->select('book', 'b', ['fetch' => \PDO::FETCH_ASSOC]);
     $query->fields('b');
     $query->condition('b.bid', $link['bid']);
 
diff --git a/core/modules/comment/src/Plugin/views/filter/UserUid.php b/core/modules/comment/src/Plugin/views/filter/UserUid.php
index 248b4609c32a..d1a82403506d 100644
--- a/core/modules/comment/src/Plugin/views/filter/UserUid.php
+++ b/core/modules/comment/src/Plugin/views/filter/UserUid.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\comment\Plugin\views\filter;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\Condition;
 use Drupal\views\Plugin\views\filter\FilterPluginBase;
 
@@ -18,7 +19,7 @@ class UserUid extends FilterPluginBase {
   public function query() {
     $this->ensureMyTable();
 
-    $subselect = db_select('comment_field_data', 'c');
+    $subselect = Database::getConnection()->select('comment_field_data', 'c');
     $subselect->addField('c', 'cid');
     $subselect->condition('c.uid', $this->value, $this->operator);
 
diff --git a/core/modules/dblog/dblog.module b/core/modules/dblog/dblog.module
index a32c67de013d..74cb187b80c5 100644
--- a/core/modules/dblog/dblog.module
+++ b/core/modules/dblog/dblog.module
@@ -68,7 +68,7 @@ function dblog_cron() {
   // e.g. auto_increment value > 1 or rows deleted directly from the table.
   if ($row_limit > 0) {
     $connection = \Drupal::database();
-    $min_row = db_select('watchdog', 'w')
+    $min_row = $connection->select('watchdog', 'w')
       ->fields('w', ['wid'])
       ->orderBy('wid', 'DESC')
       ->range($row_limit - 1, 1)
diff --git a/core/modules/field/tests/src/Kernel/BulkDeleteTest.php b/core/modules/field/tests/src/Kernel/BulkDeleteTest.php
index 8c3ee5f26cff..2abb61e8e500 100644
--- a/core/modules/field/tests/src/Kernel/BulkDeleteTest.php
+++ b/core/modules/field/tests/src/Kernel/BulkDeleteTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\field\Kernel;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Entity\EntityInterface;
 use Drupal\field\Entity\FieldConfig;
 use Drupal\field\Entity\FieldStorageConfig;
@@ -186,7 +187,7 @@ public function testDeleteField() {
     $table_mapping = $storage->getTableMapping();
     $table = $table_mapping->getDedicatedDataTableName($field_storage);
     $column = $table_mapping->getFieldColumnName($field_storage, 'value');
-    $result = db_select($table, 't')
+    $result = Database::getConnection()->select($table, 't')
       ->fields('t')
       ->execute();
     foreach ($result as $row) {
diff --git a/core/modules/field/tests/src/Kernel/FieldDataCountTest.php b/core/modules/field/tests/src/Kernel/FieldDataCountTest.php
index 69b84a9c1d1b..82ef6d09f0aa 100644
--- a/core/modules/field/tests/src/Kernel/FieldDataCountTest.php
+++ b/core/modules/field/tests/src/Kernel/FieldDataCountTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\field\Kernel;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
 use Drupal\entity_test\Entity\EntityTest;
 use Drupal\field\Entity\FieldConfig;
@@ -87,7 +88,7 @@ public function testEntityCountAndHasData() {
       // Count the actual number of rows in the field table.
       $table_mapping = $storage->getTableMapping();
       $field_table_name = $table_mapping->getDedicatedDataTableName($field_storage);
-      $result = db_select($field_table_name, 't')
+      $result = Database::getConnection()->select($field_table_name, 't')
         ->fields('t')
         ->countQuery()
         ->execute()
diff --git a/core/modules/file/tests/src/Kernel/UsageTest.php b/core/modules/file/tests/src/Kernel/UsageTest.php
index 1e5473b5ee4e..cc64cd810762 100644
--- a/core/modules/file/tests/src/Kernel/UsageTest.php
+++ b/core/modules/file/tests/src/Kernel/UsageTest.php
@@ -63,7 +63,7 @@ public function testAddUsage() {
     $file_usage->add($file, 'testing', 'bar', 2);
     $file_usage->add($file, 'testing', 'bar', 2);
 
-    $usage = db_select('file_usage', 'f')
+    $usage = Database::getConnection()->select('file_usage', 'f')
       ->fields('f')
       ->condition('f.fid', $file->id())
       ->execute()
@@ -119,7 +119,7 @@ public function doTestRemoveUsage() {
 
     // Normal decrement.
     $file_usage->delete($file, 'testing', 'bar', 2);
-    $count = db_select('file_usage', 'f')
+    $count = $connection->select('file_usage', 'f')
       ->fields('f', ['count'])
       ->condition('f.fid', $file->id())
       ->execute()
@@ -128,7 +128,7 @@ public function doTestRemoveUsage() {
 
     // Multiple decrement and removal.
     $file_usage->delete($file, 'testing', 'bar', 2, 2);
-    $count = db_select('file_usage', 'f')
+    $count = $connection->select('file_usage', 'f')
       ->fields('f', ['count'])
       ->condition('f.fid', $file->id())
       ->execute()
@@ -137,7 +137,7 @@ public function doTestRemoveUsage() {
 
     // Non-existent decrement.
     $file_usage->delete($file, 'testing', 'bar', 2);
-    $count = db_select('file_usage', 'f')
+    $count = $connection->select('file_usage', 'f')
       ->fields('f', ['count'])
       ->condition('f.fid', $file->id())
       ->execute()
diff --git a/core/modules/forum/src/Plugin/Block/ActiveTopicsBlock.php b/core/modules/forum/src/Plugin/Block/ActiveTopicsBlock.php
index ac8d8282fb49..921e7ed04b68 100644
--- a/core/modules/forum/src/Plugin/Block/ActiveTopicsBlock.php
+++ b/core/modules/forum/src/Plugin/Block/ActiveTopicsBlock.php
@@ -2,6 +2,8 @@
 
 namespace Drupal\forum\Plugin\Block;
 
+use Drupal\Core\Database\Database;
+
 /**
  * Provides an 'Active forum topics' block.
  *
@@ -17,7 +19,7 @@ class ActiveTopicsBlock extends ForumBlockBase {
    * {@inheritdoc}
    */
   protected function buildForumQuery() {
-    return db_select('forum_index', 'f')
+    return Database::getConnection()->select('forum_index', 'f')
       ->fields('f')
       ->addTag('node_access')
       ->addMetaData('base_table', 'forum_index')
diff --git a/core/modules/forum/src/Plugin/Block/NewTopicsBlock.php b/core/modules/forum/src/Plugin/Block/NewTopicsBlock.php
index d57628f31a3b..e1d2d1c1afbb 100644
--- a/core/modules/forum/src/Plugin/Block/NewTopicsBlock.php
+++ b/core/modules/forum/src/Plugin/Block/NewTopicsBlock.php
@@ -2,6 +2,8 @@
 
 namespace Drupal\forum\Plugin\Block;
 
+use Drupal\Core\Database\Database;
+
 /**
  * Provides a 'New forum topics' block.
  *
@@ -17,7 +19,7 @@ class NewTopicsBlock extends ForumBlockBase {
    * {@inheritdoc}
    */
   protected function buildForumQuery() {
-    return db_select('forum_index', 'f')
+    return Database::getConnection()->select('forum_index', 'f')
       ->fields('f')
       ->addTag('node_access')
       ->addMetaData('base_table', 'forum_index')
diff --git a/core/modules/locale/locale.bulk.inc b/core/modules/locale/locale.bulk.inc
index 69b465b4ae19..3feee12c5b68 100644
--- a/core/modules/locale/locale.bulk.inc
+++ b/core/modules/locale/locale.bulk.inc
@@ -55,7 +55,7 @@ function locale_translate_batch_import_files(array $options, $force = FALSE) {
   $files = locale_translate_get_interface_translation_files([], $langcodes);
 
   if (!$force) {
-    $result = db_select('locale_file', 'lf')
+    $result = \Drupal::database()->select('locale_file', 'lf')
       ->fields('lf', ['langcode', 'uri', 'timestamp'])
       ->condition('langcode', $langcodes)
       ->execute()
diff --git a/core/modules/locale/locale.translation.inc b/core/modules/locale/locale.translation.inc
index e9000d1131f7..9d7bfd6e83f8 100644
--- a/core/modules/locale/locale.translation.inc
+++ b/core/modules/locale/locale.translation.inc
@@ -333,7 +333,7 @@ function locale_cron_fill_queue() {
     return $project['status'] == 1;
   });
   $connection = \Drupal::database();
-  $files = db_select('locale_file', 'f')
+  $files = $connection->select('locale_file', 'f')
     ->condition('f.project', array_keys($projects), 'IN')
     ->condition('f.last_checked', $last, '<')
     ->fields('f', ['project', 'langcode'])
diff --git a/core/modules/locale/tests/src/Functional/LocaleTranslationUiTest.php b/core/modules/locale/tests/src/Functional/LocaleTranslationUiTest.php
index a51eb876e550..ec6a70fe2030 100644
--- a/core/modules/locale/tests/src/Functional/LocaleTranslationUiTest.php
+++ b/core/modules/locale/tests/src/Functional/LocaleTranslationUiTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\locale\Functional;
 
+use Drupal\Core\Database\Database;
 use Drupal\language\Entity\ConfigurableLanguage;
 use Drupal\Tests\BrowserTestBase;
 use Drupal\Core\Language\LanguageInterface;
@@ -232,7 +233,7 @@ public function testJavaScriptTranslation() {
 
     // Retrieve the source string of the first string available in the
     // {locales_source} table and translate it.
-    $query = db_select('locales_source', 's');
+    $query = Database::getConnection()->select('locales_source', 's');
     $query->addJoin('INNER', 'locales_location', 'l', 's.lid = l.lid');
     $source = $query->fields('s', ['source'])
       ->condition('l.type', 'javascript')
diff --git a/core/modules/node/src/Plugin/Search/NodeSearch.php b/core/modules/node/src/Plugin/Search/NodeSearch.php
index b043d63681e1..f14aac0bd410 100644
--- a/core/modules/node/src/Plugin/Search/NodeSearch.php
+++ b/core/modules/node/src/Plugin/Search/NodeSearch.php
@@ -6,6 +6,7 @@
 use Drupal\Core\Cache\CacheableMetadata;
 use Drupal\Core\Config\Config;
 use Drupal\Core\Database\Connection;
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\SelectExtender;
 use Drupal\Core\Database\StatementInterface;
 use Drupal\Core\Entity\EntityManagerInterface;
@@ -438,7 +439,7 @@ public function updateIndex() {
     // per cron run.
     $limit = (int) $this->searchSettings->get('index.cron_limit');
 
-    $query = db_select('node', 'n', ['target' => 'replica']);
+    $query = Database::getConnection('replica')->select('node', 'n');
     $query->addField('n', 'nid');
     $query->leftJoin('search_dataset', 'sd', 'sd.sid = n.nid AND sd.type = :type', [':type' => $this->getPluginId()]);
     $query->addExpression('CASE MAX(sd.reindex) WHEN NULL THEN 0 ELSE 1 END', 'ex');
diff --git a/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareCombinationTest.php b/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareCombinationTest.php
index bc78291e3f40..3aee6cb3f80f 100644
--- a/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareCombinationTest.php
+++ b/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareCombinationTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\node\Functional;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Language\LanguageInterface;
 use Drupal\field\Entity\FieldConfig;
 use Drupal\language\Entity\ConfigurableLanguage;
@@ -251,9 +252,9 @@ public function testNodeAccessLanguageAwareCombination() {
     $this->assertNodeAccess($expected_node_access_no_access, $this->nodes['private_no_language_public'], $this->webUser);
 
     // Query the node table with the node access tag in several languages.
-
+    $connection = Database::getConnection();
     // Query with no language specified. The fallback (hu or und) will be used.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addTag('node_access');
@@ -268,7 +269,7 @@ public function testNodeAccessLanguageAwareCombination() {
     $this->assertTrue(array_key_exists($this->nodes['public_no_language_public']->id(), $nids), 'Returned node ID is no language public node.');
 
     // Query with Hungarian (hu) specified.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addMetaData('langcode', 'hu')
@@ -282,7 +283,7 @@ public function testNodeAccessLanguageAwareCombination() {
     $this->assertTrue(array_key_exists($this->nodes['private_both_public']->id(), $nids), 'Returned node ID is both public non-language-aware private only node.');
 
     // Query with Catalan (ca) specified.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addMetaData('langcode', 'ca')
@@ -296,7 +297,7 @@ public function testNodeAccessLanguageAwareCombination() {
     $this->assertTrue(array_key_exists($this->nodes['private_both_public']->id(), $nids), 'Returned node ID is both public non-language-aware private only node.');
 
     // Query with German (de) specified.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addMetaData('langcode', 'de')
@@ -308,7 +309,7 @@ public function testNodeAccessLanguageAwareCombination() {
 
     // Query the nodes table as admin user (full access) with the node access
     // tag and no specific langcode.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->adminUser)
       ->addTag('node_access');
@@ -319,7 +320,7 @@ public function testNodeAccessLanguageAwareCombination() {
 
     // Query the nodes table as admin user (full access) with the node access
     // tag and langcode de.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->adminUser)
       ->addMetaData('langcode', 'de')
diff --git a/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareTest.php b/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareTest.php
index 48f9dfac36c3..996681007451 100644
--- a/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareTest.php
+++ b/core/modules/node/tests/src/Functional/NodeAccessLanguageAwareTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\node\Functional;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Language\LanguageInterface;
 use Drupal\field\Entity\FieldConfig;
 use Drupal\language\Entity\ConfigurableLanguage;
@@ -192,9 +193,9 @@ public function testNodeAccessLanguageAware() {
     $this->assertNodeAccess($expected_node_access, $this->nodes['no_language_public'], $this->webUser);
 
     // Query the node table with the node access tag in several languages.
-
+    $connection = Database::getConnection();
     // Query with no language specified. The fallback (hu) will be used.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addTag('node_access');
@@ -210,7 +211,7 @@ public function testNodeAccessLanguageAware() {
     $this->assertTrue(array_key_exists($this->nodes['no_language_public']->id(), $nids), 'The node with no language is returned.');
 
     // Query with Hungarian (hu) specified.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addMetaData('langcode', 'hu')
@@ -224,7 +225,7 @@ public function testNodeAccessLanguageAware() {
     $this->assertTrue(array_key_exists($this->nodes['ca_private']->id(), $nids), 'The node with only the Catalan translation private is returned.');
 
     // Query with Catalan (ca) specified.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addMetaData('langcode', 'ca')
@@ -238,7 +239,7 @@ public function testNodeAccessLanguageAware() {
     $this->assertTrue(array_key_exists($this->nodes['hu_private']->id(), $nids), 'The node with only the Hungarian translation private is returned.');
 
     // Query with German (de) specified.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->webUser)
       ->addMetaData('langcode', 'de')
@@ -250,7 +251,7 @@ public function testNodeAccessLanguageAware() {
 
     // Query the nodes table as admin user (full access) with the node access
     // tag and no specific langcode.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->adminUser)
       ->addTag('node_access');
@@ -261,7 +262,7 @@ public function testNodeAccessLanguageAware() {
 
     // Query the nodes table as admin user (full access) with the node access
     // tag and langcode de.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $this->adminUser)
       ->addMetaData('langcode', 'de')
diff --git a/core/modules/node/tests/src/Functional/NodeAccessLanguageTest.php b/core/modules/node/tests/src/Functional/NodeAccessLanguageTest.php
index 1af5660fe52f..a3d9c4d942c2 100644
--- a/core/modules/node/tests/src/Functional/NodeAccessLanguageTest.php
+++ b/core/modules/node/tests/src/Functional/NodeAccessLanguageTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\node\Functional;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Language\LanguageInterface;
 use Drupal\language\Entity\ConfigurableLanguage;
 use Drupal\node\Entity\NodeType;
@@ -201,9 +202,10 @@ public function testNodeAccessQueryTag() {
     ]);
     $this->assertTrue($node_no_language->language()->getId() == LanguageInterface::LANGCODE_NOT_SPECIFIED, 'Node created with not specified language.');
 
+    $connection = Database::getConnection();
     // Query the nodes table as the web user with the node access tag and no
     // specific langcode.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $web_user)
       ->addTag('node_access');
@@ -217,7 +219,7 @@ public function testNodeAccessQueryTag() {
 
     // Query the nodes table as the web user with the node access tag and
     // langcode de.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $web_user)
       ->addMetaData('langcode', 'de')
@@ -229,7 +231,7 @@ public function testNodeAccessQueryTag() {
 
     // Query the nodes table as admin user (full access) with the node access
     // tag and no specific langcode.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $admin_user)
       ->addTag('node_access');
@@ -240,7 +242,7 @@ public function testNodeAccessQueryTag() {
 
     // Query the nodes table as admin user (full access) with the node access
     // tag and langcode de.
-    $select = db_select('node', 'n')
+    $select = $connection->select('node', 'n')
       ->fields('n', ['nid'])
       ->addMetaData('account', $admin_user)
       ->addMetaData('langcode', 'de')
diff --git a/core/modules/node/tests/src/Functional/NodeAdminTest.php b/core/modules/node/tests/src/Functional/NodeAdminTest.php
index 61f7df663b11..24c62dda68b8 100644
--- a/core/modules/node/tests/src/Functional/NodeAdminTest.php
+++ b/core/modules/node/tests/src/Functional/NodeAdminTest.php
@@ -78,7 +78,7 @@ public function testContentAdminSort() {
     }
 
     // Test that the default sort by node.changed DESC actually fires properly.
-    $nodes_query = db_select('node_field_data', 'n')
+    $nodes_query = $connection->select('node_field_data', 'n')
       ->fields('n', ['title'])
       ->orderBy('changed', 'DESC')
       ->execute()
@@ -92,7 +92,7 @@ public function testContentAdminSort() {
 
     // Compare the rendered HTML node list to a query for the nodes ordered by
     // title to account for possible database-dependent sort order.
-    $nodes_query = db_select('node_field_data', 'n')
+    $nodes_query = $connection->select('node_field_data', 'n')
       ->fields('n', ['title'])
       ->orderBy('title')
       ->execute()
diff --git a/core/modules/node/tests/src/Functional/NodeQueryAlterTest.php b/core/modules/node/tests/src/Functional/NodeQueryAlterTest.php
index c26b8446c18f..6b9306703cf1 100644
--- a/core/modules/node/tests/src/Functional/NodeQueryAlterTest.php
+++ b/core/modules/node/tests/src/Functional/NodeQueryAlterTest.php
@@ -55,7 +55,7 @@ protected function setUp() {
   public function testNodeQueryAlterLowLevelWithAccess() {
     // User with access should be able to view 4 nodes.
     try {
-      $query = db_select('node', 'mytab')
+      $query = Database::getConnection()->select('node', 'mytab')
         ->fields('mytab');
       $query->addTag('node_access');
       $query->addMetaData('op', 'view');
@@ -96,7 +96,7 @@ public function testNodeQueryAlterWithRevisions() {
   public function testNodeQueryAlterLowLevelNoAccess() {
     // User without access should be able to view 0 nodes.
     try {
-      $query = db_select('node', 'mytab')
+      $query = Database::getConnection()->select('node', 'mytab')
         ->fields('mytab');
       $query->addTag('node_access');
       $query->addMetaData('op', 'view');
@@ -119,7 +119,7 @@ public function testNodeQueryAlterLowLevelNoAccess() {
   public function testNodeQueryAlterLowLevelEditAccess() {
     // User with view-only access should not be able to edit nodes.
     try {
-      $query = db_select('node', 'mytab')
+      $query = Database::getConnection()->select('node', 'mytab')
         ->fields('mytab');
       $query->addTag('node_access');
       $query->addMetaData('op', 'update');
@@ -160,7 +160,7 @@ public function testNodeQueryAlterOverride() {
     // privilege after adding the node_access record.
     drupal_static_reset('node_access_view_all_nodes');
     try {
-      $query = db_select('node', 'mytab')
+      $query = $connection->select('node', 'mytab')
         ->fields('mytab');
       $query->addTag('node_access');
       $query->addMetaData('op', 'view');
@@ -182,7 +182,7 @@ public function testNodeQueryAlterOverride() {
     \Drupal::state()->set('node_access_test.no_access_uid', $this->noAccessUser->id());
     drupal_static_reset('node_access_view_all_nodes');
     try {
-      $query = db_select('node', 'mytab')
+      $query = $connection->select('node', 'mytab')
         ->fields('mytab');
       $query->addTag('node_access');
       $query->addMetaData('op', 'view');
diff --git a/core/modules/node/tests/src/Functional/NodeRevisionsTest.php b/core/modules/node/tests/src/Functional/NodeRevisionsTest.php
index 6cd925056aac..3dc0aeacd2a2 100644
--- a/core/modules/node/tests/src/Functional/NodeRevisionsTest.php
+++ b/core/modules/node/tests/src/Functional/NodeRevisionsTest.php
@@ -224,7 +224,7 @@ public function testRevisions() {
 
     // Verify that the non-default revision vid is greater than the default
     // revision vid.
-    $default_revision = db_select('node', 'n')
+    $default_revision = $connection->select('node', 'n')
       ->fields('n', ['vid'])
       ->condition('nid', $node->id())
       ->execute()
diff --git a/core/modules/search/src/Plugin/views/argument/Search.php b/core/modules/search/src/Plugin/views/argument/Search.php
index f9cd9a14b3f3..c52a69681b54 100644
--- a/core/modules/search/src/Plugin/views/argument/Search.php
+++ b/core/modules/search/src/Plugin/views/argument/Search.php
@@ -2,7 +2,9 @@
 
 namespace Drupal\search\Plugin\views\argument;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\Condition;
+use Drupal\search\ViewsSearchQuery;
 use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
 use Drupal\views\Plugin\views\display\DisplayPluginBase;
 use Drupal\views\ViewExecutable;
@@ -48,7 +50,7 @@ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$o
    */
   protected function queryParseSearchExpression($input) {
     if (!isset($this->searchQuery)) {
-      $this->searchQuery = db_select('search_index', 'i', ['target' => 'replica'])->extend('Drupal\search\ViewsSearchQuery');
+      $this->searchQuery = Database::getConnection('replica')->select('search_index', 'i')->extend(ViewsSearchQuery::class);
       $this->searchQuery->searchExpression($input, $this->searchType);
       $this->searchQuery->publicParseSearchExpression();
     }
diff --git a/core/modules/search/src/Plugin/views/filter/Search.php b/core/modules/search/src/Plugin/views/filter/Search.php
index d387d538eaa8..41548aa10c01 100644
--- a/core/modules/search/src/Plugin/views/filter/Search.php
+++ b/core/modules/search/src/Plugin/views/filter/Search.php
@@ -2,8 +2,10 @@
 
 namespace Drupal\search\Plugin\views\filter;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\Condition;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\search\ViewsSearchQuery;
 use Drupal\views\Plugin\views\filter\FilterPluginBase;
 use Drupal\views\Plugin\views\display\DisplayPluginBase;
 use Drupal\views\ViewExecutable;
@@ -120,7 +122,7 @@ public function validateExposed(&$form, FormStateInterface $form_state) {
   protected function queryParseSearchExpression($input) {
     if (!isset($this->searchQuery)) {
       $this->parsed = TRUE;
-      $this->searchQuery = db_select('search_index', 'i', ['target' => 'replica'])->extend('Drupal\search\ViewsSearchQuery');
+      $this->searchQuery = Database::getConnection('replica')->select('search_index', 'i')->extend(ViewsSearchQuery::class);
       $this->searchQuery->searchExpression($input, $this->searchType);
       $this->searchQuery->publicParseSearchExpression();
     }
diff --git a/core/modules/search/src/SearchQuery.php b/core/modules/search/src/SearchQuery.php
index 6446fa4ed507..ebbf84d33784 100644
--- a/core/modules/search/src/SearchQuery.php
+++ b/core/modules/search/src/SearchQuery.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\search;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\Condition;
 use Drupal\Core\Database\Query\SelectExtender;
 use Drupal\Core\Database\Query\SelectInterface;
@@ -111,7 +112,7 @@ class SearchQuery extends SelectExtender {
    * This is always used for the second step in the query, but is not part of
    * the preparation step unless $this->simple is FALSE.
    *
-   * @var DatabaseCondition
+   * @var Drupal\Core\Database\Query\ConditionInterface[]
    */
   protected $conditions;
 
@@ -621,7 +622,7 @@ public function countQuery() {
     $expressions = [];
 
     // Add sid as the only field and count them as a subquery.
-    $count = db_select($inner->fields('i', ['sid']), NULL, ['target' => 'replica']);
+    $count = Database::getConnection('replica')->select($inner->fields('i', ['sid']), NULL);
 
     // Add the COUNT() expression.
     $count->addExpression('COUNT(*)');
diff --git a/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php b/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php
index 80ac1cc9c05f..17b3f06afdb6 100644
--- a/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php
+++ b/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php
@@ -216,7 +216,7 @@ public function testMultilingualSearch() {
 
     // Save the node again. Verify that the request time on it is not updated.
     $this->searchableNodes[1]->save();
-    $result = db_select('search_dataset', 'd')
+    $result = $connection->select('search_dataset', 'd')
       ->fields('d', ['reindex'])
       ->condition('type', 'node_search')
       ->condition('sid', $this->searchableNodes[1]->id())
@@ -304,7 +304,8 @@ protected function assertIndexCounts($remaining, $total, $message) {
    */
   protected function assertDatabaseCounts($count_node, $count_foo, $message) {
     // Count number of distinct nodes by ID.
-    $results = db_select('search_dataset', 'i')
+    $connection = Database::getConnection();
+    $results = $connection->select('search_dataset', 'i')
       ->fields('i', ['sid'])
       ->condition('type', 'node_search')
       ->groupBy('sid')
@@ -313,7 +314,7 @@ protected function assertDatabaseCounts($count_node, $count_foo, $message) {
     $this->assertEqual($count_node, count($results), 'Node count was ' . $count_node . ' for ' . $message);
 
     // Count number of "foo" records.
-    $results = db_select('search_dataset', 'i')
+    $results = $connection->select('search_dataset', 'i')
       ->fields('i', ['sid'])
       ->condition('type', 'foo')
       ->execute()
diff --git a/core/modules/search/tests/src/Kernel/SearchMatchTest.php b/core/modules/search/tests/src/Kernel/SearchMatchTest.php
index e9d2ac8bca5b..577028bd48ee 100644
--- a/core/modules/search/tests/src/Kernel/SearchMatchTest.php
+++ b/core/modules/search/tests/src/Kernel/SearchMatchTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\search\Kernel;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Language\LanguageInterface;
 use Drupal\KernelTests\KernelTestBase;
 
@@ -158,8 +159,9 @@ public function _testQueries() {
       'xxxxx "minim am veniam es" OR dolore' => [],
       'xx "minim am veniam es" OR dolore' => [],
     ];
+    $connection = Database::getConnection();
     foreach ($queries as $query => $results) {
-      $result = db_select('search_index', 'i')
+      $result = $connection->select('search_index', 'i')
         ->extend('Drupal\search\SearchQuery')
         ->searchExpression($query, static::SEARCH_TYPE)
         ->execute();
@@ -179,7 +181,7 @@ public function _testQueries() {
       'germany' => [11, 12],
     ];
     foreach ($queries as $query => $results) {
-      $result = db_select('search_index', 'i')
+      $result = $connection->select('search_index', 'i')
         ->extend('Drupal\search\SearchQuery')
         ->searchExpression($query, static::SEARCH_TYPE_2)
         ->execute();
@@ -202,7 +204,7 @@ public function _testQueries() {
       'ヒーキ' => [],
     ];
     foreach ($queries as $query => $results) {
-      $result = db_select('search_index', 'i')
+      $result = $connection->select('search_index', 'i')
         ->extend('Drupal\search\SearchQuery')
         ->searchExpression($query, static::SEARCH_TYPE_JPN)
         ->execute();
diff --git a/core/modules/shortcut/src/ShortcutSetStorage.php b/core/modules/shortcut/src/ShortcutSetStorage.php
index 5de5125e0368..3fdeb388c760 100644
--- a/core/modules/shortcut/src/ShortcutSetStorage.php
+++ b/core/modules/shortcut/src/ShortcutSetStorage.php
@@ -108,7 +108,7 @@ public function unassignUser($account) {
    * {@inheritdoc}
    */
   public function getAssignedToUser($account) {
-    $query = db_select('shortcut_set_users', 'ssu');
+    $query = $this->connection->select('shortcut_set_users', 'ssu');
     $query->fields('ssu', ['set_name']);
     $query->condition('ssu.uid', $account->id());
     return $query->execute()->fetchField();
diff --git a/core/modules/statistics/statistics.module b/core/modules/statistics/statistics.module
index 2c7aa011425c..683840e06ccf 100644
--- a/core/modules/statistics/statistics.module
+++ b/core/modules/statistics/statistics.module
@@ -99,7 +99,7 @@ function statistics_cron() {
 function statistics_title_list($dbfield, $dbrows) {
   @trigger_error('statistics_title_list() is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Use \Drupal\statistics\NodeStatisticsDatabaseStorage::fetchAll() instead.', E_USER_DEPRECATED);
   if (in_array($dbfield, ['totalcount', 'daycount', 'timestamp'])) {
-    $query = db_select('node_field_data', 'n');
+    $query = \Drupal::database()->select('node_field_data', 'n');
     $query->addTag('node_access');
     $query->join('node_counter', 's', 'n.nid = s.nid');
     $query->join('users_field_data', 'u', 'n.uid = u.uid');
diff --git a/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php b/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php
index 1c714dc689ac..5efc804b8826 100644
--- a/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php
+++ b/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\statistics\Functional;
 
+use Drupal\Core\Database\Database;
 use Drupal\Tests\BrowserTestBase;
 use Drupal\Tests\Traits\Core\CronRunTrait;
 
@@ -115,7 +116,8 @@ public function testDeleteNode() {
     $stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
     $this->client->post($stats_path, ['form_params' => $post]);
 
-    $result = db_select('node_counter', 'n')
+    $connection = Database::getConnection();
+    $result = $connection->select('node_counter', 'n')
       ->fields('n', ['nid'])
       ->condition('n.nid', $this->testNode->id())
       ->execute()
@@ -124,7 +126,7 @@ public function testDeleteNode() {
 
     $this->testNode->delete();
 
-    $result = db_select('node_counter', 'n')
+    $result = $connection->select('node_counter', 'n')
       ->fields('n', ['nid'])
       ->condition('n.nid', $this->testNode->id())
       ->execute()
@@ -162,7 +164,7 @@ public function testExpiredLogs() {
     $this->drupalGet('admin/reports/pages');
     $this->assertNoText('node/' . $this->testNode->id(), 'No hit URL found.');
 
-    $result = db_select('node_counter', 'nc')
+    $result = Database::getConnection()->select('node_counter', 'nc')
       ->fields('nc', ['daycount'])
       ->condition('nid', $this->testNode->id(), '=')
       ->execute()
diff --git a/core/modules/system/src/Tests/Module/ModuleTestBase.php b/core/modules/system/src/Tests/Module/ModuleTestBase.php
index 30f89a343189..8d3c8be7f0c1 100644
--- a/core/modules/system/src/Tests/Module/ModuleTestBase.php
+++ b/core/modules/system/src/Tests/Module/ModuleTestBase.php
@@ -187,7 +187,7 @@ public function assertModules(array $modules, $enabled) {
    *   A link to associate with the message.
    */
   public function assertLogMessage($type, $message, $variables = [], $severity = RfcLogLevel::NOTICE, $link = '') {
-    $count = db_select('watchdog', 'w')
+    $count = Database::getConnection()->select('watchdog', 'w')
       ->condition('type', $type)
       ->condition('message', $message)
       ->condition('variables', serialize($variables))
diff --git a/core/modules/system/tests/modules/database_test/src/Controller/DatabaseTestController.php b/core/modules/system/tests/modules/database_test/src/Controller/DatabaseTestController.php
index 809225909a04..1677f73cc323 100644
--- a/core/modules/system/tests/modules/database_test/src/Controller/DatabaseTestController.php
+++ b/core/modules/system/tests/modules/database_test/src/Controller/DatabaseTestController.php
@@ -51,7 +51,7 @@ public function dbQueryTemporary() {
     $table_name = $this->connection->queryTemporary('SELECT age FROM {test}', []);
     return new JsonResponse([
       'table_name' => $table_name,
-      'row_count' => db_select($table_name)->countQuery()->execute()->fetchField(),
+      'row_count' => $this->connection->select($table_name)->countQuery()->execute()->fetchField(),
     ]);
   }
 
@@ -64,7 +64,7 @@ public function dbQueryTemporary() {
    * @return \Symfony\Component\HttpFoundation\JsonResponse
    */
   public function pagerQueryEven($limit) {
-    $query = db_select('test', 't');
+    $query = $this->connection->select('test', 't');
     $query
       ->fields('t', ['name'])
       ->orderBy('age');
@@ -90,7 +90,7 @@ public function pagerQueryEven($limit) {
    * @return \Symfony\Component\HttpFoundation\JsonResponse
    */
   public function pagerQueryOdd($limit) {
-    $query = db_select('test_task', 't');
+    $query = $this->connection->select('test_task', 't');
     $query
       ->fields('t', ['task'])
       ->orderBy('pid');
@@ -123,7 +123,7 @@ public function testTablesort() {
       'priority' => ['data' => t('Priority'), 'field' => 'priority'],
     ];
 
-    $query = db_select('test_task', 't');
+    $query = $this->connection->select('test_task', 't');
     $query
       ->fields('t', ['tid', 'pid', 'task', 'priority']);
 
@@ -155,7 +155,7 @@ public function testTablesortFirst() {
       'priority' => ['data' => t('Priority'), 'field' => 'priority'],
     ];
 
-    $query = db_select('test_task', 't');
+    $query = $this->connection->select('test_task', 't');
     $query
       ->fields('t', ['tid', 'pid', 'task', 'priority']);
 
diff --git a/core/modules/system/tests/modules/database_test/src/Form/DatabaseTestForm.php b/core/modules/system/tests/modules/database_test/src/Form/DatabaseTestForm.php
index 63e2476319b6..afb585e24b7d 100644
--- a/core/modules/system/tests/modules/database_test/src/Form/DatabaseTestForm.php
+++ b/core/modules/system/tests/modules/database_test/src/Form/DatabaseTestForm.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\database_test\Form;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\user\Entity\User;
@@ -29,7 +30,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
       'status' => ['data' => t('Status'), 'field' => 'u.status'],
     ];
 
-    $query = db_select('users_field_data', 'u');
+    $query = Database::getConnection()->select('users_field_data', 'u');
     $query->condition('u.uid', 0, '<>');
     $query->condition('u.default_langcode', 1);
 
diff --git a/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php b/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php
index 4f1fdad6431c..4e01479f38f0 100644
--- a/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php
+++ b/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php
@@ -3,6 +3,8 @@
 namespace Drupal\pager_test\Controller;
 
 use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\Database\Database;
+use Drupal\Core\Database\Query\PagerSelectExtender;
 
 /**
  * Controller routine for testing the pager.
@@ -26,7 +28,7 @@ protected function buildTestTable($element, $limit) {
       ['data' => 'type'],
       ['data' => 'timestamp'],
     ];
-    $query = db_select('watchdog', 'd')->extend('Drupal\Core\Database\Query\PagerSelectExtender')->element($element);
+    $query = Database::getConnection()->select('watchdog', 'd')->extend(PagerSelectExtender::class)->element($element);
     $result = $query
       ->fields('d', ['wid', 'type', 'timestamp'])
       ->limit($limit)
diff --git a/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php b/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php
index 63e7e3163775..16f1074d4a3d 100644
--- a/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php
+++ b/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\system\Functional\Database;
 
+use Drupal\Core\Database\Database;
 use Symfony\Component\HttpFoundation\Request;
 
 /**
@@ -85,14 +86,15 @@ public function testOddPagerQuery() {
    * This is a regression test for #467984.
    */
   public function testInnerPagerQuery() {
-    $query = db_select('test', 't')
+    $connection = Database::getConnection();
+    $query = $connection->select('test', 't')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
     $query
       ->fields('t', ['age'])
       ->orderBy('age')
       ->limit(5);
 
-    $outer_query = db_select($query);
+    $outer_query = $connection->select($query);
     $outer_query->addField('subquery', 'age');
 
     $ages = $outer_query
@@ -107,7 +109,7 @@ public function testInnerPagerQuery() {
    * This is a regression test for #467984.
    */
   public function testHavingPagerQuery() {
-    $query = db_select('test', 't')
+    $query = Database::getConnection()->select('test', 't')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
     $query
       ->fields('t', ['name'])
@@ -133,7 +135,8 @@ public function testElementNumbers() {
     ]);
     \Drupal::getContainer()->get('request_stack')->push($request);
 
-    $name = db_select('test', 't')
+    $connection = Database::getConnection();
+    $name = $connection->select('test', 't')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
       ->element(2)
       ->fields('t', ['name'])
@@ -145,7 +148,7 @@ public function testElementNumbers() {
 
     // Setting an element smaller than the previous one
     // should not overwrite the pager $maxElement with a smaller value.
-    $name = db_select('test', 't')
+    $name = $connection->select('test', 't')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
       ->element(1)
       ->fields('t', ['name'])
@@ -155,7 +158,7 @@ public function testElementNumbers() {
       ->fetchField();
     $this->assertEqual($name, 'George', 'Pager query #2 with a specified element ID returned the correct results.');
 
-    $name = db_select('test', 't')
+    $name = $connection->select('test', 't')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
       ->fields('t', ['name'])
       ->orderBy('age')
diff --git a/core/modules/system/tests/src/Functional/Database/TemporaryQueryTest.php b/core/modules/system/tests/src/Functional/Database/TemporaryQueryTest.php
index e06cf8cc6c12..3e2cf5259b91 100644
--- a/core/modules/system/tests/src/Functional/Database/TemporaryQueryTest.php
+++ b/core/modules/system/tests/src/Functional/Database/TemporaryQueryTest.php
@@ -20,7 +20,7 @@ class TemporaryQueryTest extends DatabaseTestBase {
    * Returns the number of rows of a table.
    */
   public function countTableRows($table_name) {
-    return db_select($table_name)->countQuery()->execute()->fetchField();
+    return Database::getConnection()->select($table_name)->countQuery()->execute()->fetchField();
   }
 
   /**
diff --git a/core/modules/system/tests/src/Functional/Module/ModuleTestBase.php b/core/modules/system/tests/src/Functional/Module/ModuleTestBase.php
index e48770d49955..40ef29fcc9aa 100644
--- a/core/modules/system/tests/src/Functional/Module/ModuleTestBase.php
+++ b/core/modules/system/tests/src/Functional/Module/ModuleTestBase.php
@@ -186,7 +186,7 @@ public function assertModules(array $modules, $enabled) {
    *   A link to associate with the message.
    */
   public function assertLogMessage($type, $message, $variables = [], $severity = RfcLogLevel::NOTICE, $link = '') {
-    $count = db_select('watchdog', 'w')
+    $count = Database::getConnection()->select('watchdog', 'w')
       ->condition('type', $type)
       ->condition('message', $message)
       ->condition('variables', serialize($variables))
diff --git a/core/modules/taxonomy/src/Plugin/views/argument/IndexTidDepth.php b/core/modules/taxonomy/src/Plugin/views/argument/IndexTidDepth.php
index 8eeb1f9b6a18..57a2efabb161 100644
--- a/core/modules/taxonomy/src/Plugin/views/argument/IndexTidDepth.php
+++ b/core/modules/taxonomy/src/Plugin/views/argument/IndexTidDepth.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\taxonomy\Plugin\views\argument;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\Condition;
 use Drupal\Core\Entity\EntityStorageInterface;
 use Drupal\Core\Form\FormStateInterface;
@@ -105,7 +106,7 @@ public function query($group_by = FALSE) {
       $tids = $this->argument;
     }
     // Now build the subqueries.
-    $subquery = db_select('taxonomy_index', 'tn');
+    $subquery = Database::getConnection()->select('taxonomy_index', 'tn');
     $subquery->addField('tn', 'nid');
     $where = (new Condition('OR'))->condition('tn.tid', $tids, $operator);
     $last = "tn";
diff --git a/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTidDepth.php b/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTidDepth.php
index ebb5b51f2214..987f8152c088 100644
--- a/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTidDepth.php
+++ b/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTidDepth.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\taxonomy\Plugin\views\filter;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\Condition;
 use Drupal\Core\Form\FormStateInterface;
 
@@ -71,7 +72,7 @@ public function query() {
     }
 
     // Now build the subqueries.
-    $subquery = db_select('taxonomy_index', 'tn');
+    $subquery = Database::getConnection()->select('taxonomy_index', 'tn');
     $subquery->addField('tn', 'nid');
     $where = (new Condition('OR'))->condition('tn.tid', $this->value, $operator);
     $last = "tn";
diff --git a/core/modules/taxonomy/src/Plugin/views/relationship/NodeTermData.php b/core/modules/taxonomy/src/Plugin/views/relationship/NodeTermData.php
index 13fd056aba3e..b757c23f4255 100644
--- a/core/modules/taxonomy/src/Plugin/views/relationship/NodeTermData.php
+++ b/core/modules/taxonomy/src/Plugin/views/relationship/NodeTermData.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\taxonomy\Plugin\views\relationship;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\taxonomy\VocabularyStorageInterface;
 use Drupal\views\ViewExecutable;
@@ -129,7 +130,7 @@ public function query() {
       $def['type'] = empty($this->options['required']) ? 'LEFT' : 'INNER';
       $def['adjusted'] = TRUE;
 
-      $query = db_select('taxonomy_term_field_data', 'td');
+      $query = Database::getConnection()->select('taxonomy_term_field_data', 'td');
       $query->addJoin($def['type'], 'taxonomy_index', 'tn', 'tn.tid = td.tid');
       $query->condition('td.vid', array_filter($this->options['vids']), 'IN');
       $query->addTag('taxonomy_term_access');
diff --git a/core/modules/taxonomy/src/TermStorage.php b/core/modules/taxonomy/src/TermStorage.php
index 2d47722faeae..4f5b513844b2 100644
--- a/core/modules/taxonomy/src/TermStorage.php
+++ b/core/modules/taxonomy/src/TermStorage.php
@@ -325,7 +325,7 @@ public function resetWeights($vid) {
    * {@inheritdoc}
    */
   public function getNodeTerms(array $nids, array $vocabs = [], $langcode = NULL) {
-    $query = db_select($this->getDataTable(), 'td');
+    $query = $this->database->select($this->getDataTable(), 'td');
     $query->innerJoin('taxonomy_index', 'tn', 'td.tid = tn.tid');
     $query->fields('td', ['tid']);
     $query->addField('tn', 'nid', 'node_nid');
diff --git a/core/modules/taxonomy/taxonomy.tokens.inc b/core/modules/taxonomy/taxonomy.tokens.inc
index 211a1214451b..8511c7acb9a7 100644
--- a/core/modules/taxonomy/taxonomy.tokens.inc
+++ b/core/modules/taxonomy/taxonomy.tokens.inc
@@ -120,7 +120,7 @@ function taxonomy_tokens($type, $tokens, array $data, array $options, Bubbleable
           break;
 
         case 'node-count':
-          $query = db_select('taxonomy_index');
+          $query = \Drupal::database()->select('taxonomy_index');
           $query->condition('tid', $term->id());
           $query->addTag('term_node_count');
           $count = $query->countQuery()->execute()->fetchField();
diff --git a/core/modules/taxonomy/tests/src/Functional/TaxonomyQueryAlterTest.php b/core/modules/taxonomy/tests/src/Functional/TaxonomyQueryAlterTest.php
index 81bd6796b53d..0958df3e5d9e 100644
--- a/core/modules/taxonomy/tests/src/Functional/TaxonomyQueryAlterTest.php
+++ b/core/modules/taxonomy/tests/src/Functional/TaxonomyQueryAlterTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\taxonomy\Functional;
 
+use Drupal\Core\Database\Database;
 use Drupal\Tests\BrowserTestBase;
 
 /**
@@ -58,7 +59,8 @@ public function testTaxonomyQueryAlter() {
     $this->assertQueryTagTestResult(3, 1, 'TermStorage::loadChildren()');
 
     $this->setupQueryTagTestHooks();
-    $query = db_select('taxonomy_term_data', 't');
+    $connection = Database::getConnection();
+    $query = $connection->select('taxonomy_term_data', 't');
     $query->addField('t', 'tid');
     $query->addTag('taxonomy_term_access');
     $tids = $query->execute()->fetchCol();
@@ -66,7 +68,7 @@ public function testTaxonomyQueryAlter() {
     $this->assertQueryTagTestResult(1, 1, 'custom db_select() with taxonomy_term_access tag (preferred)');
 
     $this->setupQueryTagTestHooks();
-    $query = db_select('taxonomy_term_data', 't');
+    $query = $connection->select('taxonomy_term_data', 't');
     $query->addField('t', 'tid');
     $query->addTag('term_access');
     $tids = $query->execute()->fetchCol();
diff --git a/core/modules/tracker/tracker.pages.inc b/core/modules/tracker/tracker.pages.inc
index de08c63cdc11..eccd4754c71b 100644
--- a/core/modules/tracker/tracker.pages.inc
+++ b/core/modules/tracker/tracker.pages.inc
@@ -6,6 +6,7 @@
  */
 
 use Drupal\Core\Cache\Cache;
+use Drupal\Core\Database\Database;
 use Drupal\node\Entity\Node;
 
 /**
@@ -22,13 +23,13 @@
  */
 function tracker_page($account = NULL) {
   if ($account) {
-    $query = db_select('tracker_user', 't')
+    $query = Database::getConnection()->select('tracker_user', 't')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
       ->addMetaData('base_table', 'tracker_user')
       ->condition('t.uid', $account->id());
   }
   else {
-    $query = db_select('tracker_node', 't', ['target' => 'replica'])
+    $query = Database::getConnection('replica')->select('tracker_node', 't')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
       ->addMetaData('base_table', 'tracker_node');
   }
diff --git a/core/modules/user/tests/src/Functional/UserDeleteTest.php b/core/modules/user/tests/src/Functional/UserDeleteTest.php
index 5803a049aaa6..b34103cb50ca 100644
--- a/core/modules/user/tests/src/Functional/UserDeleteTest.php
+++ b/core/modules/user/tests/src/Functional/UserDeleteTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\user\Functional;
 
+use Drupal\Core\Database\Database;
 use Drupal\Tests\BrowserTestBase;
 use Drupal\user\Entity\User;
 
@@ -24,7 +25,8 @@ public function testUserDeleteMultiple() {
     $uids = [$user_a->id(), $user_b->id(), $user_c->id()];
 
     // These users should have a role
-    $query = db_select('user__roles', 'r');
+    $connection = Database::getConnection();
+    $query = $connection->select('user__roles', 'r');
     $roles_created = $query
       ->fields('r', ['entity_id'])
       ->condition('entity_id', $uids, 'IN')
@@ -38,7 +40,7 @@ public function testUserDeleteMultiple() {
     // Delete the users.
     user_delete_multiple($uids);
     // Test if the roles assignments are deleted.
-    $query = db_select('user__roles', 'r');
+    $query = $connection->select('user__roles', 'r');
     $roles_after_deletion = $query
       ->fields('r', ['entity_id'])
       ->condition('entity_id', $uids, 'IN')
diff --git a/core/modules/views/tests/src/Kernel/Plugin/JoinTest.php b/core/modules/views/tests/src/Kernel/Plugin/JoinTest.php
index 1086612ae882..e59027f4fb40 100644
--- a/core/modules/views/tests/src/Kernel/Plugin/JoinTest.php
+++ b/core/modules/views/tests/src/Kernel/Plugin/JoinTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\views\Kernel\Plugin;
 
+use Drupal\Core\Database\Database;
 use Drupal\views_test_data\Plugin\views\join\JoinTest as JoinTestPlugin;
 use Drupal\views\Plugin\views\join\JoinPluginBase;
 use Drupal\views\Views;
@@ -58,7 +59,7 @@ public function testExamplePlugin() {
     $rand_int = rand(0, 1000);
     $join->setJoinValue($rand_int);
 
-    $query = db_select('views_test_data');
+    $query = Database::getConnection()->select('views_test_data');
     $table = ['alias' => 'users_field_data'];
     $join->buildJoin($query, $table, $view->query);
 
@@ -93,7 +94,7 @@ public function testBasePlugin() {
 
     // Build the actual join values and read them back from the dbtng query
     // object.
-    $query = db_select('views_test_data');
+    $query = Database::getConnection()->select('views_test_data');
     $table = ['alias' => 'users_field_data'];
     $join->buildJoin($query, $table, $view->query);
 
diff --git a/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTagTest.php b/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTagTest.php
index 0fefc390f43c..865205eb2e56 100644
--- a/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTagTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTagTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\KernelTests\Core\Cache;
 
 use Drupal\Core\Cache\Cache;
+use Drupal\Core\Database\Database;
 use Drupal\Core\DependencyInjection\ContainerBuilder;
 use Drupal\KernelTests\KernelTestBase;
 use Symfony\Component\DependencyInjection\Reference;
@@ -43,7 +44,8 @@ public function testTagInvalidations() {
       $this->assertTrue($bin->get('test'), 'Cache item was set in bin.');
     }
 
-    $invalidations_before = intval(db_select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
+    $connection = Database::getConnection();
+    $invalidations_before = intval($connection->select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
     Cache::invalidateTags(['test_tag:2']);
 
     // Test that cache entry has been invalidated in multiple bins.
@@ -53,7 +55,7 @@ public function testTagInvalidations() {
     }
 
     // Test that only one tag invalidation has occurred.
-    $invalidations_after = intval(db_select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
+    $invalidations_after = intval($connection->select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
     $this->assertEqual($invalidations_after, $invalidations_before + 1, 'Only one addition cache tag invalidation has occurred after invalidating a tag used in multiple bins.');
   }
 
diff --git a/core/tests/Drupal/KernelTests/Core/Database/AlterTest.php b/core/tests/Drupal/KernelTests/Core/Database/AlterTest.php
index e2a6589d7b3c..6ee99afb829a 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/AlterTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/AlterTest.php
@@ -14,7 +14,7 @@ class AlterTest extends DatabaseTestBase {
    * Tests that we can do basic alters.
    */
   public function testSimpleAlter() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
     $query->addTag('database_test_alter_add_range');
@@ -28,7 +28,7 @@ public function testSimpleAlter() {
    * Tests that we can alter the joins on a query.
    */
   public function testAlterWithJoin() {
-    $query = db_select('test_task');
+    $query = $this->connection->select('test_task');
     $tid_field = $query->addField('test_task', 'tid');
     $task_field = $query->addField('test_task', 'task');
     $query->orderBy($task_field);
@@ -52,7 +52,7 @@ public function testAlterWithJoin() {
    * Tests that we can alter a query's conditionals.
    */
   public function testAlterChangeConditional() {
-    $query = db_select('test_task');
+    $query = $this->connection->select('test_task');
     $tid_field = $query->addField('test_task', 'tid');
     $pid_field = $query->addField('test_task', 'pid');
     $task_field = $query->addField('test_task', 'task');
@@ -77,7 +77,7 @@ public function testAlterChangeConditional() {
    * Tests that we can alter the fields of a query.
    */
   public function testAlterChangeFields() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $name_field = $query->addField('test', 'name');
     $age_field = $query->addField('test', 'age', 'age');
     $query->orderBy('name');
@@ -92,7 +92,7 @@ public function testAlterChangeFields() {
    * Tests that we can alter expressions in the query.
    */
   public function testAlterExpression() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $name_field = $query->addField('test', 'name');
     $age_field = $query->addExpression("age*2", 'double_age');
     $query->condition('age', 27);
@@ -112,7 +112,7 @@ public function testAlterExpression() {
    * This also tests hook_query_TAG_alter().
    */
   public function testAlterRemoveRange() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
     $query->range(0, 2);
@@ -128,7 +128,7 @@ public function testAlterRemoveRange() {
    */
   public function testSimpleAlterSubquery() {
     // Create a sub-query with an alter tag.
-    $subquery = db_select('test', 'p');
+    $subquery = $this->connection->select('test', 'p');
     $subquery->addField('p', 'name');
     $subquery->addField('p', 'id');
     // Pick out George.
@@ -138,7 +138,7 @@ public function testSimpleAlterSubquery() {
     $subquery->addTag('database_test_alter_change_expressions');
 
     // Create a main query and join to sub-query.
-    $query = db_select('test_task', 'tt');
+    $query = $this->connection->select('test_task', 'tt');
     $query->join($subquery, 'pq', 'pq.id = tt.pid');
     $age_field = $query->addField('pq', 'double_age');
     $name_field = $query->addField('pq', 'name');
diff --git a/core/tests/Drupal/KernelTests/Core/Database/BasicSyntaxTest.php b/core/tests/Drupal/KernelTests/Core/Database/BasicSyntaxTest.php
index 468e892811ba..a5635de7d5db 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/BasicSyntaxTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/BasicSyntaxTest.php
@@ -83,14 +83,14 @@ public function testLikeEscape() {
       ->execute();
 
     // Match both "Ringo" and "Ring_".
-    $num_matches = db_select('test', 't')
+    $num_matches = $this->connection->select('test', 't')
       ->condition('name', 'Ring_', 'LIKE')
       ->countQuery()
       ->execute()
       ->fetchField();
     $this->assertIdentical($num_matches, '2', 'Found 2 records.');
     // Match only "Ring_" using a LIKE expression with no wildcards.
-    $num_matches = db_select('test', 't')
+    $num_matches = $this->connection->select('test', 't')
       ->condition('name', $this->connection->escapeLike('Ring_'), 'LIKE')
       ->countQuery()
       ->execute()
@@ -114,14 +114,14 @@ public function testLikeBackslash() {
 
     // Match both rows using a LIKE expression with two wildcards and a verbatim
     // backslash.
-    $num_matches = db_select('test', 't')
+    $num_matches = $this->connection->select('test', 't')
       ->condition('name', 'abc%\\\\_', 'LIKE')
       ->countQuery()
       ->execute()
       ->fetchField();
     $this->assertIdentical($num_matches, '2', 'Found 2 records.');
     // Match only the former using a LIKE expression with no wildcards.
-    $num_matches = db_select('test', 't')
+    $num_matches = $this->connection->select('test', 't')
       ->condition('name', $this->connection->escapeLike('abc%\_'), 'LIKE')
       ->countQuery()
       ->execute()
diff --git a/core/tests/Drupal/KernelTests/Core/Database/DatabaseLegacyTest.php b/core/tests/Drupal/KernelTests/Core/Database/DatabaseLegacyTest.php
index 1724f1475d7f..3125da8cff76 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/DatabaseLegacyTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/DatabaseLegacyTest.php
@@ -6,6 +6,7 @@
 use Drupal\Core\Database\Query\Delete;
 use Drupal\Core\Database\Query\Insert;
 use Drupal\Core\Database\Query\Merge;
+use Drupal\Core\Database\Query\Select;
 use Drupal\Core\Database\Query\Truncate;
 use Drupal\Core\Database\Query\Update;
 use Drupal\Core\Database\Transaction;
@@ -478,4 +479,13 @@ public function testDbInsert() {
     $this->assertInstanceOf(Insert::class, db_insert('test'));
   }
 
+  /**
+   * Tests the db_select() function.
+   *
+   * @expectedDeprecation db_select() is deprecated in Drupal 8.0.x and will be removed before Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call call select() on it. For example, $injected_database->db_select($table, $alias, $options); See https://www.drupal.org/node/2993033
+   */
+  public function testDbSelect() {
+    $this->assertInstanceOf(Select::class, db_select('test'));
+  }
+
 }
diff --git a/core/tests/Drupal/KernelTests/Core/Database/DeleteTruncateTest.php b/core/tests/Drupal/KernelTests/Core/Database/DeleteTruncateTest.php
index 9301c0144293..69e78d8803dd 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/DeleteTruncateTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/DeleteTruncateTest.php
@@ -24,7 +24,7 @@ public function testSubselectDelete() {
     $num_records_before = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
     $pid_to_delete = db_query("SELECT * FROM {test_task} WHERE task = 'sleep'")->fetchField();
 
-    $subquery = db_select('test', 't')
+    $subquery = $this->connection->select('test', 't')
       ->fields('t', ['id'])
       ->condition('t.id', [$pid_to_delete], 'IN');
     $delete = $this->connection->delete('test_task')
diff --git a/core/tests/Drupal/KernelTests/Core/Database/FetchTest.php b/core/tests/Drupal/KernelTests/Core/Database/FetchTest.php
index d0439c5f1045..dbb9ab0e2fb9 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/FetchTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/FetchTest.php
@@ -117,7 +117,7 @@ public function testQueryFetchBoth() {
    * Confirms that we can fetch all records into an array explicitly.
    */
   public function testQueryFetchAllColumn() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->orderBy('name');
     $query_result = $query->execute()->fetchAll(\PDO::FETCH_COLUMN);
diff --git a/core/tests/Drupal/KernelTests/Core/Database/InsertTest.php b/core/tests/Drupal/KernelTests/Core/Database/InsertTest.php
index cbc5c9d9360a..cd53504c6f5c 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/InsertTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/InsertTest.php
@@ -151,7 +151,7 @@ public function testInsertLastInsertID() {
    * Tests that the INSERT INTO ... SELECT (fields) ... syntax works.
    */
   public function testInsertSelectFields() {
-    $query = db_select('test_people', 'tp');
+    $query = $this->connection->select('test_people', 'tp');
     // The query builder will always append expressions after fields.
     // Add the expression first to test that the insert fields are correctly
     // re-ordered.
@@ -177,7 +177,7 @@ public function testInsertSelectFields() {
    * Tests that the INSERT INTO ... SELECT * ... syntax works.
    */
   public function testInsertSelectAll() {
-    $query = db_select('test_people', 'tp')
+    $query = $this->connection->select('test_people', 'tp')
       ->fields('tp')
       ->condition('tp.name', 'Meredith');
 
diff --git a/core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php b/core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php
index f0885143c862..782974c5b38f 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php
@@ -59,7 +59,7 @@ public function testInsertDuplicateData() {
       }
 
       // Ensure the other values were not inserted.
-      $record = db_select('test')
+      $record = $this->connection->select('test')
         ->fields('test', ['name', 'age'])
         ->condition('age', [17, 75], 'IN')
         ->execute()->fetchObject();
@@ -104,7 +104,7 @@ public function testInsertDuplicateDataFromSelect() {
       // 3 => [name] => Meredith, [age] => 30, [job] => Speaker
       // Records 0 and 1 should pass, record 2 should lead to integrity
       // constraint violation.
-      $query = db_select('test_people', 'tp')
+      $query = $this->connection->select('test_people', 'tp')
         ->fields('tp', ['name', 'age', 'job'])
         ->orderBy('name');
 
@@ -136,7 +136,7 @@ public function testInsertDuplicateDataFromSelect() {
       }
 
       // Ensure the values for records 2 and 3 were not inserted.
-      $record = db_select('test')
+      $record = $this->connection->select('test')
         ->fields('test', ['name', 'age'])
         ->condition('age', [17, 30], 'IN')
         ->execute()->fetchObject();
diff --git a/core/tests/Drupal/KernelTests/Core/Database/QueryTest.php b/core/tests/Drupal/KernelTests/Core/Database/QueryTest.php
index bfe60b6c0f64..898dd8fb14c2 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/QueryTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/QueryTest.php
@@ -53,7 +53,7 @@ public function testArrayArgumentsSQLInjection() {
 
     // Test that the insert query that was used in the SQL injection attempt did
     // not result in a row being inserted in the database.
-    $result = db_select('test')
+    $result = $this->connection->select('test')
       ->condition('name', 'test12345678')
       ->countQuery()
       ->execute()
@@ -78,7 +78,7 @@ public function testConditionOperatorArgumentsSQLInjection() {
       }
     });
     try {
-      $result = db_select('test', 't')
+      $result = $this->connection->select('test', 't')
         ->fields('t')
         ->condition('name', 1, $injection)
         ->execute();
@@ -90,7 +90,7 @@ public function testConditionOperatorArgumentsSQLInjection() {
 
     // Test that the insert query that was used in the SQL injection attempt did
     // not result in a row being inserted in the database.
-    $result = db_select('test')
+    $result = $this->connection->select('test')
       ->condition('name', 'test12345678')
       ->countQuery()
       ->execute()
@@ -106,7 +106,7 @@ public function testConditionOperatorArgumentsSQLInjection() {
     $injection = "= 1 UNION ALL SELECT password FROM user WHERE uid =";
 
     try {
-      $result = db_select('test', 't')
+      $result = $this->connection->select('test', 't')
         ->fields('t', ['name', 'name'])
         ->condition('name', 1, $injection)
         ->execute();
@@ -123,7 +123,7 @@ public function testConditionOperatorArgumentsSQLInjection() {
     $injection = "IS NOT NULL) UNION ALL SELECT name FROM {TEST_UPPERCASE} -- ";
 
     try {
-      $result = db_select('test', 't')
+      $result = $this->connection->select('test', 't')
         ->fields('t', ['name'])
         ->condition('name', 1, $injection)
         ->execute();
diff --git a/core/tests/Drupal/KernelTests/Core/Database/SelectCloneTest.php b/core/tests/Drupal/KernelTests/Core/Database/SelectCloneTest.php
index 3b14283b3451..fb5963a3b513 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/SelectCloneTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/SelectCloneTest.php
@@ -13,11 +13,11 @@ class SelectCloneTest extends DatabaseTestBase {
    * Test that subqueries as value within conditions are cloned properly.
    */
   public function testSelectConditionSubQueryCloning() {
-    $subquery = db_select('test', 't');
+    $subquery = $this->connection->select('test', 't');
     $subquery->addField('t', 'id', 'id');
     $subquery->condition('age', 28, '<');
 
-    $query = db_select('test', 't');
+    $query = $this->connection->select('test', 't');
     $query->addField('t', 'name', 'name');
     $query->condition('id', $subquery, 'IN');
 
diff --git a/core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php b/core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php
index 23ec66494a9e..4844cef645d2 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/SelectComplexTest.php
@@ -25,7 +25,7 @@ class SelectComplexTest extends DatabaseTestBase {
    * Tests simple JOIN statements.
    */
   public function testDefaultJoin() {
-    $query = db_select('test_task', 't');
+    $query = $this->connection->select('test_task', 't');
     $people_alias = $query->join('test', 'p', 't.pid = p.id');
     $name_field = $query->addField($people_alias, 'name', 'name');
     $query->addField('t', 'task', 'task');
@@ -50,7 +50,7 @@ public function testDefaultJoin() {
    * Tests LEFT OUTER joins.
    */
   public function testLeftOuterJoin() {
-    $query = db_select('test', 'p');
+    $query = $this->connection->select('test', 'p');
     $people_alias = $query->leftJoin('test_task', 't', 't.pid = p.id');
     $name_field = $query->addField('p', 'name', 'name');
     $query->addField($people_alias, 'task', 'task');
@@ -74,7 +74,7 @@ public function testLeftOuterJoin() {
    * Tests GROUP BY clauses.
    */
   public function testGroupBy() {
-    $query = db_select('test_task', 't');
+    $query = $this->connection->select('test_task', 't');
     $count_field = $query->addExpression('COUNT(task)', 'num');
     $task_field = $query->addField('t', 'task');
     $query->orderBy($count_field);
@@ -110,7 +110,7 @@ public function testGroupBy() {
    * Tests GROUP BY and HAVING clauses together.
    */
   public function testGroupByAndHaving() {
-    $query = db_select('test_task', 't');
+    $query = $this->connection->select('test_task', 't');
     $count_field = $query->addExpression('COUNT(task)', 'num');
     $task_field = $query->addField('t', 'task');
     $query->orderBy($count_field);
@@ -146,7 +146,7 @@ public function testGroupByAndHaving() {
    * The SQL clause varies with the database.
    */
   public function testRange() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
     $query->range(0, 2);
@@ -159,7 +159,7 @@ public function testRange() {
    * Test whether the range property of a select clause can be undone.
    */
   public function testRangeUndo() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $name_field = $query->addField('test', 'name');
     $age_field = $query->addField('test', 'age', 'age');
     $query->range(0, 2);
@@ -173,7 +173,7 @@ public function testRangeUndo() {
    * Tests distinct queries.
    */
   public function testDistinct() {
-    $query = db_select('test_task');
+    $query = $this->connection->select('test_task');
     $query->addField('test_task', 'task');
     $query->distinct();
     $query_result = $query->countQuery()->execute()->fetchField();
@@ -185,7 +185,7 @@ public function testDistinct() {
    * Tests that we can generate a count query from a built query.
    */
   public function testCountQuery() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $name_field = $query->addField('test', 'name');
     $age_field = $query->addField('test', 'age', 'age');
     $query->orderBy('name');
@@ -205,7 +205,7 @@ public function testCountQuery() {
    * Tests having queries.
    */
   public function testHavingCountQuery() {
-    $query = db_select('test')
+    $query = $this->connection->select('test')
       ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
       ->groupBy('age')
       ->having('age + 1 > 0');
@@ -219,7 +219,7 @@ public function testHavingCountQuery() {
    * Tests that countQuery removes 'all_fields' statements and ordering clauses.
    */
   public function testCountQueryRemovals() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->fields('test');
     $query->orderBy('name');
     $count = $query->countQuery();
@@ -254,11 +254,11 @@ public function testCountQueryFieldRemovals() {
     // up in the query, an error will be thrown. If not, it will return the
     // number of records, which in this case happens to be 4 (there are four
     // records in the {test} table).
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->fields('test', ['fail']);
     $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed fields');
 
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addExpression('fail');
     $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed expressions');
   }
@@ -267,7 +267,7 @@ public function testCountQueryFieldRemovals() {
    * Tests that we can generate a count query from a query with distinct.
    */
   public function testCountQueryDistinct() {
-    $query = db_select('test_task');
+    $query = $this->connection->select('test_task');
     $query->addField('test_task', 'task');
     $query->distinct();
 
@@ -280,7 +280,7 @@ public function testCountQueryDistinct() {
    * Tests that we can generate a count query from a query with GROUP BY.
    */
   public function testCountQueryGroupBy() {
-    $query = db_select('test_task');
+    $query = $this->connection->select('test_task');
     $query->addField('test_task', 'pid');
     $query->groupBy('pid');
 
@@ -290,7 +290,7 @@ public function testCountQueryGroupBy() {
 
     // Use a column alias as, without one, the query can succeed for the wrong
     // reason.
-    $query = db_select('test_task');
+    $query = $this->connection->select('test_task');
     $query->addField('test_task', 'pid', 'pid_alias');
     $query->addExpression('COUNT(test_task.task)', 'count');
     $query->groupBy('pid_alias');
@@ -309,7 +309,7 @@ public function testNestedConditions() {
     // "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)"
     // That should find only one record. Yes it's a non-optimal way of writing
     // that query but that's not the point!
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'job');
     $query->condition('name', 'Paul');
     $query->condition((new Condition('OR'))->condition('age', 26)->condition('age', 27));
@@ -322,7 +322,7 @@ public function testNestedConditions() {
    * Confirms we can join on a single table twice with a dynamic alias.
    */
   public function testJoinTwice() {
-    $query = db_select('test')->fields('test');
+    $query = $this->connection->select('test')->fields('test');
     $alias = $query->join('test', 'test', 'test.job = %alias.job');
     $query->addField($alias, 'name', 'othername');
     $query->addField($alias, 'job', 'otherjob');
@@ -343,12 +343,12 @@ public function testJoinSubquery() {
       'mail' => $this->randomMachineName() . '@example.com',
     ]);
 
-    $query = db_select('test_task', 'tt', ['target' => 'replica']);
+    $query = Database::getConnection('replica')->select('test_task', 'tt');
     $query->addExpression('tt.pid + 1', 'abc');
     $query->condition('priority', 1, '>');
     $query->condition('priority', 100, '<');
 
-    $subquery = db_select('test', 'tp');
+    $subquery = $this->connection->select('test', 'tp');
     $subquery->join('test_one_blob', 'tpb', 'tp.id = tpb.id');
     $subquery->join('node', 'n', 'tp.id = n.nid');
     $subquery->addTag('node_access');
@@ -376,7 +376,7 @@ public function testJoinSubquery() {
    * Tests that rowCount() throws exception on SELECT query.
    */
   public function testSelectWithRowCount() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $result = $query->execute();
     try {
@@ -394,7 +394,7 @@ public function testSelectWithRowCount() {
    */
   public function testJoinConditionObject() {
     // Same test as testDefaultJoin, but with a Condition object.
-    $query = db_select('test_task', 't');
+    $query = $this->connection->select('test_task', 't');
     $join_cond = (new Condition('AND'))->where('t.pid = p.id');
     $people_alias = $query->join('test', 'p', $join_cond);
     $name_field = $query->addField($people_alias, 'name', 'name');
@@ -421,7 +421,7 @@ public function testJoinConditionObject() {
     $join_cond = (new Condition('AND'))
       ->condition('t1.name', $t1_name)
       ->condition('t2.name', $t2_name);
-    $query = db_select('test', 't1');
+    $query = $this->connection->select('test', 't1');
     $query->innerJoin('test', 't2', $join_cond);
     $query->addField('t1', 'name', 't1_name');
     $query->addField('t2', 'name', 't2_name');
diff --git a/core/tests/Drupal/KernelTests/Core/Database/SelectOrderedTest.php b/core/tests/Drupal/KernelTests/Core/Database/SelectOrderedTest.php
index 5e81e08989cd..a8fd385f0a4b 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/SelectOrderedTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/SelectOrderedTest.php
@@ -13,7 +13,7 @@ class SelectOrderedTest extends DatabaseTestBase {
    * Tests basic ORDER BY.
    */
   public function testSimpleSelectOrdered() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $age_field = $query->addField('test', 'age', 'age');
     $query->orderBy($age_field);
@@ -34,7 +34,7 @@ public function testSimpleSelectOrdered() {
    * Tests multiple ORDER BY.
    */
   public function testSimpleSelectMultiOrdered() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $age_field = $query->addField('test', 'age', 'age');
     $job_field = $query->addField('test', 'job');
@@ -65,7 +65,7 @@ public function testSimpleSelectMultiOrdered() {
    * Tests ORDER BY descending.
    */
   public function testSimpleSelectOrderedDesc() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $age_field = $query->addField('test', 'age', 'age');
     $query->orderBy($age_field, 'DESC');
diff --git a/core/tests/Drupal/KernelTests/Core/Database/SelectSubqueryTest.php b/core/tests/Drupal/KernelTests/Core/Database/SelectSubqueryTest.php
index c035d35ea38e..0916d8601cd3 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/SelectSubqueryTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/SelectSubqueryTest.php
@@ -14,7 +14,7 @@ class SelectSubqueryTest extends DatabaseTestBase {
    */
   public function testFromSubquerySelect() {
     // Create a subquery, which is just a normal query object.
-    $subquery = db_select('test_task', 'tt');
+    $subquery = $this->connection->select('test_task', 'tt');
     $subquery->addField('tt', 'pid', 'pid');
     $subquery->addField('tt', 'task', 'task');
     $subquery->condition('priority', 1);
@@ -22,7 +22,7 @@ public function testFromSubquerySelect() {
     for ($i = 0; $i < 2; $i++) {
       // Create another query that joins against the virtual table resulting
       // from the subquery.
-      $select = db_select($subquery, 'tt2');
+      $select = $this->connection->select($subquery, 'tt2');
       $select->join('test', 't', 't.id=tt2.pid');
       $select->addField('t', 'name');
       if ($i) {
@@ -48,7 +48,7 @@ public function testFromSubquerySelect() {
    */
   public function testFromSubquerySelectWithLimit() {
     // Create a subquery, which is just a normal query object.
-    $subquery = db_select('test_task', 'tt');
+    $subquery = $this->connection->select('test_task', 'tt');
     $subquery->addField('tt', 'pid', 'pid');
     $subquery->addField('tt', 'task', 'task');
     $subquery->orderBy('priority', 'DESC');
@@ -56,7 +56,7 @@ public function testFromSubquerySelectWithLimit() {
 
     // Create another query that joins against the virtual table resulting
     // from the subquery.
-    $select = db_select($subquery, 'tt2');
+    $select = $this->connection->select($subquery, 'tt2');
     $select->join('test', 't', 't.id=tt2.pid');
     $select->addField('t', 'name');
 
@@ -74,13 +74,13 @@ public function testFromSubquerySelectWithLimit() {
    */
   public function testConditionSubquerySelect() {
     // Create a subquery, which is just a normal query object.
-    $subquery = db_select('test_task', 'tt');
+    $subquery = $this->connection->select('test_task', 'tt');
     $subquery->addField('tt', 'pid', 'pid');
     $subquery->condition('tt.priority', 1);
 
     // Create another query that joins against the virtual table resulting
     // from the subquery.
-    $select = db_select('test_task', 'tt2');
+    $select = $this->connection->select('test_task', 'tt2');
     $select->addField('tt2', 'task');
     $select->condition('tt2.pid', $subquery, 'IN');
 
@@ -97,11 +97,11 @@ public function testConditionSubquerySelect() {
    */
   public function testConditionSubquerySelect2() {
     // Create a subquery, which is just a normal query object.
-    $subquery = db_select('test', 't2');
+    $subquery = $this->connection->select('test', 't2');
     $subquery->addExpression('AVG(t2.age)');
 
     // Create another query that adds a clause using the subquery.
-    $select = db_select('test', 't');
+    $select = $this->connection->select('test', 't');
     $select->addField('t', 'name');
     $select->condition('t.age', $subquery, '<');
 
@@ -118,16 +118,16 @@ public function testConditionSubquerySelect2() {
    */
   public function testConditionSubquerySelect3() {
     // Create subquery 1, which is just a normal query object.
-    $subquery1 = db_select('test_task', 'tt');
+    $subquery1 = $this->connection->select('test_task', 'tt');
     $subquery1->addExpression('AVG(tt.priority)');
     $subquery1->where('tt.pid = t.id');
 
     // Create subquery 2, which is just a normal query object.
-    $subquery2 = db_select('test_task', 'tt2');
+    $subquery2 = $this->connection->select('test_task', 'tt2');
     $subquery2->addExpression('AVG(tt2.priority)');
 
     // Create another query that adds a clause using the subqueries.
-    $select = db_select('test', 't');
+    $select = $this->connection->select('test', 't');
     $select->addField('t', 'name');
     $select->condition($subquery1, $subquery2, '>');
 
@@ -148,22 +148,22 @@ public function testConditionSubquerySelect3() {
    */
   public function testConditionSubquerySelect4() {
     // Create subquery 1, which is just a normal query object.
-    $subquery1 = db_select('test_task', 'tt');
+    $subquery1 = $this->connection->select('test_task', 'tt');
     $subquery1->addExpression('AVG(tt.priority)');
     $subquery1->where('tt.pid = t.id');
 
     // Create subquery 2, which is just a normal query object.
-    $subquery2 = db_select('test_task', 'tt2');
+    $subquery2 = $this->connection->select('test_task', 'tt2');
     $subquery2->addExpression('MIN(tt2.priority)');
     $subquery2->where('tt2.pid <> t.id');
 
     // Create subquery 3, which is just a normal query object.
-    $subquery3 = db_select('test_task', 'tt3');
+    $subquery3 = $this->connection->select('test_task', 'tt3');
     $subquery3->addExpression('AVG(tt3.priority)');
     $subquery3->where('tt3.pid <> t.id');
 
     // Create another query that adds a clause using the subqueries.
-    $select = db_select('test', 't');
+    $select = $this->connection->select('test', 't');
     $select->addField('t', 'name');
     $select->condition($subquery1, [$subquery2, $subquery3], 'BETWEEN');
 
@@ -182,13 +182,13 @@ public function testConditionSubquerySelect4() {
    */
   public function testJoinSubquerySelect() {
     // Create a subquery, which is just a normal query object.
-    $subquery = db_select('test_task', 'tt');
+    $subquery = $this->connection->select('test_task', 'tt');
     $subquery->addField('tt', 'pid', 'pid');
     $subquery->condition('priority', 1);
 
     // Create another query that joins against the virtual table resulting
     // from the subquery.
-    $select = db_select('test', 't');
+    $select = $this->connection->select('test', 't');
     $select->join($subquery, 'tt', 't.id=tt.pid');
     $select->addField('t', 'name');
 
@@ -217,10 +217,10 @@ public function testExistsSubquerySelect() {
       ])
       ->execute();
     // Base query to {test}.
-    $query = db_select('test', 't')
+    $query = $this->connection->select('test', 't')
       ->fields('t', ['name']);
     // Subquery to {test_people}.
-    $subquery = db_select('test_people', 'tp')
+    $subquery = $this->connection->select('test_people', 'tp')
       ->fields('tp', ['name'])
       ->where('tp.name = t.name');
     $query->exists($subquery);
@@ -248,10 +248,10 @@ public function testNotExistsSubquerySelect() {
       ->execute();
 
     // Base query to {test}.
-    $query = db_select('test', 't')
+    $query = $this->connection->select('test', 't')
       ->fields('t', ['name']);
     // Subquery to {test_people}.
-    $subquery = db_select('test_people', 'tp')
+    $subquery = $this->connection->select('test_people', 'tp')
       ->fields('tp', ['name'])
       ->where('tp.name = t.name');
     $query->notExists($subquery);
diff --git a/core/tests/Drupal/KernelTests/Core/Database/SelectTest.php b/core/tests/Drupal/KernelTests/Core/Database/SelectTest.php
index aa1bb1d57d37..df8a7082adea 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/SelectTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/SelectTest.php
@@ -16,7 +16,7 @@ class SelectTest extends DatabaseTestBase {
    * Tests rudimentary SELECT statements.
    */
   public function testSimpleSelect() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
     $num_records = $query->countQuery()->execute()->fetchField();
@@ -28,7 +28,7 @@ public function testSimpleSelect() {
    * Tests rudimentary SELECT statement with a COMMENT.
    */
   public function testSimpleComment() {
-    $query = db_select('test')->comment('Testing query comments');
+    $query = $this->connection->select('test')->comment('Testing query comments');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
     $result = $query->execute();
@@ -46,7 +46,7 @@ public function testSimpleComment() {
    * Tests query COMMENT system against vulnerabilities.
    */
   public function testVulnerableComment() {
-    $query = db_select('test')->comment('Testing query comments */ SELECT nid FROM {node}; --');
+    $query = $this->connection->select('test')->comment('Testing query comments */ SELECT nid FROM {node}; --');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
     $result = $query->execute();
@@ -101,7 +101,7 @@ public function makeCommentsProvider() {
    * Tests basic conditionals on SELECT statements.
    */
   public function testSimpleSelectConditional() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $name_field = $query->addField('test', 'name');
     $age_field = $query->addField('test', 'age', 'age');
     $query->condition('age', 27);
@@ -121,7 +121,7 @@ public function testSimpleSelectConditional() {
    * Tests SELECT statements with expressions.
    */
   public function testSimpleSelectExpression() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $name_field = $query->addField('test', 'name');
     $age_field = $query->addExpression("age*2", 'double_age');
     $query->condition('age', 27);
@@ -141,7 +141,7 @@ public function testSimpleSelectExpression() {
    * Tests SELECT statements with multiple expressions.
    */
   public function testSimpleSelectExpressionMultiple() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $name_field = $query->addField('test', 'name');
     $age_double_field = $query->addExpression("age*2");
     $age_triple_field = $query->addExpression("age*3");
@@ -163,7 +163,7 @@ public function testSimpleSelectExpressionMultiple() {
    * Tests adding multiple fields to a SELECT statement at the same time.
    */
   public function testSimpleSelectMultipleFields() {
-    $record = db_select('test')
+    $record = $this->connection->select('test')
       ->fields('test', ['id', 'name', 'age', 'job'])
       ->condition('age', 27)
       ->execute()->fetchObject();
@@ -186,7 +186,7 @@ public function testSimpleSelectMultipleFields() {
    * Tests adding all fields from a given table to a SELECT statement.
    */
   public function testSimpleSelectAllFields() {
-    $record = db_select('test')
+    $record = $this->connection->select('test')
       ->fields('test')
       ->condition('age', 27)
       ->execute()->fetchObject();
@@ -211,7 +211,7 @@ public function testSimpleSelectAllFields() {
   public function testNullCondition() {
     $this->ensureSampleDataNull();
 
-    $names = db_select('test_null', 'tn')
+    $names = $this->connection->select('test_null', 'tn')
       ->fields('tn', ['name'])
       ->condition('age', NULL)
       ->execute()->fetchCol();
@@ -225,7 +225,7 @@ public function testNullCondition() {
   public function testIsNullCondition() {
     $this->ensureSampleDataNull();
 
-    $names = db_select('test_null', 'tn')
+    $names = $this->connection->select('test_null', 'tn')
       ->fields('tn', ['name'])
       ->isNull('age')
       ->execute()->fetchCol();
@@ -240,7 +240,7 @@ public function testIsNullCondition() {
   public function testIsNotNullCondition() {
     $this->ensureSampleDataNull();
 
-    $names = db_select('test_null', 'tn')
+    $names = $this->connection->select('test_null', 'tn')
       ->fields('tn', ['name'])
       ->isNotNull('tn.age')
       ->orderBy('name')
@@ -302,11 +302,11 @@ public function testExtenderAlwaysFalseCondition() {
    * that.
    */
   public function testUnion() {
-    $query_1 = db_select('test', 't')
+    $query_1 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', [27, 28], 'IN');
 
-    $query_2 = db_select('test', 't')
+    $query_2 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', 28);
 
@@ -325,11 +325,11 @@ public function testUnion() {
    * Tests that we can UNION ALL multiple SELECT queries together.
    */
   public function testUnionAll() {
-    $query_1 = db_select('test', 't')
+    $query_1 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', [27, 28], 'IN');
 
-    $query_2 = db_select('test', 't')
+    $query_2 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', 28);
 
@@ -349,11 +349,11 @@ public function testUnionAll() {
    * Tests that we can get a count query for a UNION Select query.
    */
   public function testUnionCount() {
-    $query_1 = db_select('test', 't')
+    $query_1 = $this->connection->select('test', 't')
       ->fields('t', ['name', 'age'])
       ->condition('age', [27, 28], 'IN');
 
-    $query_2 = db_select('test', 't')
+    $query_2 = $this->connection->select('test', 't')
       ->fields('t', ['name', 'age'])
       ->condition('age', 28);
 
@@ -372,12 +372,12 @@ public function testUnionCount() {
    */
   public function testUnionOrder() {
     // This gives George and Ringo.
-    $query_1 = db_select('test', 't')
+    $query_1 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', [27, 28], 'IN');
 
     // This gives Paul.
-    $query_2 = db_select('test', 't')
+    $query_2 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', 26);
 
@@ -401,12 +401,12 @@ public function testUnionOrder() {
    */
   public function testUnionOrderLimit() {
     // This gives George and Ringo.
-    $query_1 = db_select('test', 't')
+    $query_1 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', [27, 28], 'IN');
 
     // This gives Paul.
-    $query_2 = db_select('test', 't')
+    $query_2 = $this->connection->select('test', 't')
       ->fields('t', ['name'])
       ->condition('age', 26);
 
@@ -451,7 +451,7 @@ public function testRandomOrder() {
 
     // First select the items in order and make sure we get an ordered list.
     $expected_ids = range(1, $number_of_items);
-    $ordered_ids = db_select('test', 't')
+    $ordered_ids = $this->connection->select('test', 't')
       ->fields('t', ['id'])
       ->range(0, $number_of_items)
       ->orderBy('id')
@@ -462,7 +462,7 @@ public function testRandomOrder() {
     // Now perform the same query, but instead choose a random ordering. We
     // expect this to contain a differently ordered version of the original
     // result.
-    $randomized_ids = db_select('test', 't')
+    $randomized_ids = $this->connection->select('test', 't')
       ->fields('t', ['id'])
       ->range(0, $number_of_items)
       ->orderRandom()
@@ -475,7 +475,7 @@ public function testRandomOrder() {
 
     // Now perform the exact same query again, and make sure the order is
     // different.
-    $randomized_ids_second_set = db_select('test', 't')
+    $randomized_ids_second_set = $this->connection->select('test', 't')
       ->fields('t', ['id'])
       ->range(0, $number_of_items)
       ->orderRandom()
@@ -565,7 +565,7 @@ public function testRegexCondition() {
    * Tests that aliases are renamed when they are duplicates.
    */
   public function testSelectDuplicateAlias() {
-    $query = db_select('test', 't');
+    $query = $this->connection->select('test', 't');
     $alias1 = $query->addField('t', 'name', 'the_alias');
     $alias2 = $query->addField('t', 'age', 'the_alias');
     $this->assertNotIdentical($alias1, $alias2, 'Duplicate aliases are renamed.');
@@ -580,7 +580,7 @@ public function testInvalidSelectCount() {
       // Normally it would throw an exception but we are suppressing
       // it with the throw_exception option.
       $options['throw_exception'] = FALSE;
-      db_select('some_table_that_doesnt_exist', 't', $options)
+      $this->connection->select('some_table_that_doesnt_exist', 't', $options)
         ->fields('t')
         ->countQuery()
         ->execute();
@@ -594,7 +594,7 @@ public function testInvalidSelectCount() {
 
     try {
       // This query will fail because the table does not exist.
-      db_select('some_table_that_doesnt_exist', 't')
+      $this->connection->select('some_table_that_doesnt_exist', 't')
         ->fields('t')
         ->countQuery()
         ->execute();
@@ -611,7 +611,7 @@ public function testInvalidSelectCount() {
    */
   public function testEmptyInCondition() {
     try {
-      db_select('test', 't')
+      $this->connection->select('test', 't')
         ->fields('t')
         ->condition('age', [], 'IN')
         ->execute();
@@ -623,7 +623,7 @@ public function testEmptyInCondition() {
     }
 
     try {
-      db_select('test', 't')
+      $this->connection->select('test', 't')
         ->fields('t')
         ->condition('age', [], 'NOT IN')
         ->execute();
diff --git a/core/tests/Drupal/KernelTests/Core/Database/SerializeQueryTest.php b/core/tests/Drupal/KernelTests/Core/Database/SerializeQueryTest.php
index b3299d6005ae..47eb1d7f3737 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/SerializeQueryTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/SerializeQueryTest.php
@@ -13,7 +13,7 @@ class SerializeQueryTest extends DatabaseTestBase {
    * Confirms that a query can be serialized and unserialized.
    */
   public function testSerializeQuery() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'age');
     $query->condition('name', 'Ringo');
     // If this doesn't work, it will throw an exception, so no need for an
diff --git a/core/tests/Drupal/KernelTests/Core/Database/TaggingTest.php b/core/tests/Drupal/KernelTests/Core/Database/TaggingTest.php
index cab91381fdf7..d667d22915c3 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/TaggingTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/TaggingTest.php
@@ -16,7 +16,7 @@ class TaggingTest extends DatabaseTestBase {
    * Confirms that a query has a tag added to it.
    */
   public function testHasTag() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
 
@@ -30,7 +30,7 @@ public function testHasTag() {
    * Tests query tagging "has all of these tags" functionality.
    */
   public function testHasAllTags() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
 
@@ -45,7 +45,7 @@ public function testHasAllTags() {
    * Tests query tagging "has at least one of these tags" functionality.
    */
   public function testHasAnyTag() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
 
@@ -59,7 +59,7 @@ public function testHasAnyTag() {
    * Confirms that an extended query has a tag added to it.
    */
   public function testExtenderHasTag() {
-    $query = db_select('test')
+    $query = $this->connection->select('test')
       ->extend('Drupal\Core\Database\Query\SelectExtender');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
@@ -74,7 +74,7 @@ public function testExtenderHasTag() {
    * Tests extended query tagging "has all of these tags" functionality.
    */
   public function testExtenderHasAllTags() {
-    $query = db_select('test')
+    $query = $this->connection->select('test')
       ->extend('Drupal\Core\Database\Query\SelectExtender');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
@@ -90,7 +90,7 @@ public function testExtenderHasAllTags() {
    * Tests extended query tagging "has at least one of these tags" functionality.
    */
   public function testExtenderHasAnyTag() {
-    $query = db_select('test')
+    $query = $this->connection->select('test')
       ->extend('Drupal\Core\Database\Query\SelectExtender');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
@@ -107,7 +107,7 @@ public function testExtenderHasAnyTag() {
    * This is how we pass additional context to alter hooks.
    */
   public function testMetaData() {
-    $query = db_select('test');
+    $query = $this->connection->select('test');
     $query->addField('test', 'name');
     $query->addField('test', 'age', 'age');
 
diff --git a/core/tests/Drupal/KernelTests/Core/Database/UpdateComplexTest.php b/core/tests/Drupal/KernelTests/Core/Database/UpdateComplexTest.php
index a1ace5593ff2..3ac43642fbc1 100644
--- a/core/tests/Drupal/KernelTests/Core/Database/UpdateComplexTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Database/UpdateComplexTest.php
@@ -126,7 +126,7 @@ public function testUpdateOnlyExpression() {
    * Test UPDATE with a subselect value.
    */
   public function testSubSelectUpdate() {
-    $subselect = db_select('test_task', 't');
+    $subselect = $this->connection->select('test_task', 't');
     $subselect->addExpression('MAX(priority) + :increment', 'max_priority', [':increment' => 30]);
     // Clone this to make sure we are running a different query when
     // asserting.
diff --git a/core/tests/Drupal/KernelTests/Core/Entity/FieldSqlStorageTest.php b/core/tests/Drupal/KernelTests/Core/Entity/FieldSqlStorageTest.php
index d57cd97ac83c..f22ab48e03de 100644
--- a/core/tests/Drupal/KernelTests/Core/Entity/FieldSqlStorageTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Entity/FieldSqlStorageTest.php
@@ -193,8 +193,9 @@ public function testFieldWrite() {
     $entity->{$this->fieldName} = $values;
     $entity->save();
 
+    $connection = Database::getConnection();
     // Read the tables and check the correct values have been stored.
-    $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
+    $rows = $connection->select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
     $this->assertEqual(count($rows), $this->fieldCardinality);
     foreach ($rows as $delta => $row) {
       $expected = [
@@ -217,7 +218,7 @@ public function testFieldWrite() {
     }
     $entity->{$this->fieldName} = $values;
     $entity->save();
-    $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
+    $rows = $connection->select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
     $this->assertEqual(count($rows), count($values));
     foreach ($rows as $delta => $row) {
       $expected = [
@@ -245,7 +246,7 @@ public function testFieldWrite() {
 
     // Check that data for both revisions are in the revision table.
     foreach ($revision_values as $revision_id => $values) {
-      $rows = db_select($this->revisionTable, 't')->fields('t')->condition('revision_id', $revision_id)->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
+      $rows = $connection->select($this->revisionTable, 't')->fields('t')->condition('revision_id', $revision_id)->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
       $this->assertEqual(count($rows), min(count($values), $this->fieldCardinality));
       foreach ($rows as $delta => $row) {
         $expected = [
@@ -264,7 +265,7 @@ public function testFieldWrite() {
     // Test emptying the field.
     $entity->{$this->fieldName} = NULL;
     $entity->save();
-    $rows = db_select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
+    $rows = $connection->select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
     $this->assertEqual(count($rows), 0);
   }
 
-- 
GitLab