diff --git a/email_registration.module b/email_registration.module
index 2941c23..9fae725 100644
--- a/email_registration.module
+++ b/email_registration.module
@@ -11,11 +11,13 @@ use Drupal\Core\Render\Element\Email;
 use Drupal\Core\Form\FormStateInterface;
 
 /**
- * Implements hook_ENTITY_TYPE_insert() for user entities.
+ * Implements hook_ENTITY_TYPE_insert().
+ *
+ * Alter the user name (after entity being stored).
  */
 function email_registration_user_insert(UserInterface $account) {
   // Don't create a new username if one is already set.
-  $name = $account->getUsername();
+  $name = $account->getAccountName();
   if (!empty($name) && strpos($name, 'email_registration_') !== 0) {
     return;
   }
@@ -42,17 +44,12 @@ function email_registration_user_insert(UserInterface $account) {
   // Ensure whatever name we have is unique.
   $new_name = email_registration_unique_username($new_name, $account->id());
 
-  // @todo Make sure we still need this update.
-  // Replace with generated username.
-  db_update('users_field_data')
-    ->fields(array('name' => $new_name))
-    ->condition('uid', $account->id())
-    ->execute();
-
-  $account->setUsername($new_name);
+  $account->setUsername($new_name)->save();
 }
 
 /**
+ * Make the username unique.
+ *
  * Given a starting point for a Drupal username (e.g. the name portion of an
  * email address) return a legal, unique Drupal username. This function is
  * designed to work on the results of the /user/register or /admin/people/create
@@ -61,22 +58,24 @@ function email_registration_user_insert(UserInterface $account) {
  * ensure that the email/name is already validated using something like that.
  *
  * @param string $name
- *   A name from which to base the final user name.  May contain illegal characters; these will be stripped.
+ *   A name from which to base the final user name.
+ *   May contain illegal characters; these will be stripped.
  * @param int $uid
- *   (optional) Uid to ignore when searching for unique user (e.g. if we update the username after the
- *   {users} row is inserted)
+ *   (optional) Uid to ignore when searching for unique user
+ *   (e.g. if we update the username after the {users} row is inserted).
  *
  * @return string
  *   A unique user name based on $name.
  *
- * @see user_validate_name().
+ * @see user_validate_name()
  */
 function email_registration_unique_username($name, $uid = 0) {
   // Iterate until we find a unique name.
   $i = 0;
+  $database = \Drupal::database();
   do {
     $new_name = empty($i) ? $name : $name . '_' . $i;
-    $found = db_query_range("SELECT uid from {users_field_data} WHERE uid <> :uid AND name = :name", 0, 1, array(':uid' => $uid, ':name' => $new_name))->fetchAssoc();
+    $found = $database->queryRange("SELECT uid from {users_field_data} WHERE uid <> :uid AND name = :name", 0, 1, array(':uid' => $uid, ':name' => $new_name))->fetchAssoc();
     $i++;
   } while (!empty($found));
 
@@ -86,7 +85,7 @@ function email_registration_unique_username($name, $uid = 0) {
 /**
  * Function to clean up username.
  *
- * e.g.
+ * Run username sanitation, e.g.:
  *     Replace two or more spaces with a single underscore
  *     Strip illegal characters.
  *
@@ -145,6 +144,7 @@ function email_registration_form_user_login_form_alter(&$form, FormStateInterfac
 
 /**
  * Form element validation handler for the user login form.
+ *
  * Allows users to authenticate by email, which is our preferred method.
  */
 function email_registration_user_login_validate($form, FormStateInterface $form_state) {
diff --git a/src/Tests/EmailRegistrationTestCase.php b/src/Tests/EmailRegistrationTestCase.php
index 4b92edb..a4f240b 100644
--- a/src/Tests/EmailRegistrationTestCase.php
+++ b/src/Tests/EmailRegistrationTestCase.php
@@ -66,6 +66,28 @@ class EmailRegistrationTestCase extends WebTestBase {
     );
     $this->drupalPostForm('/user/register', $register, t('Create new account'));
     $this->assertRaw('Registration successful. You are now logged in.', t('User properly created, immediately logged in.'));
+
+    // Test email_registration_unique_username().
+    $this->drupalLogout();
+    $user_config
+      ->set('verify_mail', FALSE)
+      ->set('register', USER_REGISTER_VISITORS)
+      ->save();
+    $name = $this->randomMachineName(32);
+    $pass = $this->randomString(10);
+
+    $this->createUser(array(), $name);
+    $next_unique_name = email_registration_unique_username($name);
+
+    $register = array(
+      'mail' => $name . '@example2.com',
+      'pass[pass1]' => $pass,
+      'pass[pass2]' => $pass,
+    );
+    $this->drupalPostForm('/user/register', $register, t('Create new account'));
+    $account = user_load_by_mail($register['mail']);
+    $this->assertTrue($next_unique_name === $account->getAccountName());
+
   }
 
 }
