You are here

public function UpsertTest::testUpsert in Drupal 10

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php \Drupal\KernelTests\Core\Database\UpsertTest::testUpsert()
  2. 9 core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php \Drupal\KernelTests\Core\Database\UpsertTest::testUpsert()

Confirms that we can upsert (update-or-insert) records successfully.

File

core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php, line 18

Class

UpsertTest
Tests the Upsert query builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testUpsert() {
  $connection = Database::getConnection();
  $num_records_before = $connection
    ->query('SELECT COUNT(*) FROM {test_people}')
    ->fetchField();
  $upsert = $connection
    ->upsert('test_people')
    ->key('job')
    ->fields([
    'job',
    'age',
    'name',
  ]);

  // Add a new row.
  $upsert
    ->values([
    'job' => 'Presenter',
    'age' => 31,
    'name' => 'Tiffany',
  ]);

  // Update an existing row.
  $upsert
    ->values([
    'job' => 'Speaker',
    // The initial age was 30.
    'age' => 32,
    'name' => 'Meredith',
  ]);
  $result = $upsert
    ->execute();
  $this
    ->assertIsInt($result);
  $this
    ->assertGreaterThanOrEqual(2, $result, 'The result of the upsert operation should report that at least two rows were affected.');
  $num_records_after = $connection
    ->query('SELECT COUNT(*) FROM {test_people}')
    ->fetchField();
  $this
    ->assertEquals($num_records_before + 1, $num_records_after, 'Rows were inserted and updated properly.');
  $person = $connection
    ->query('SELECT * FROM {test_people} WHERE [job] = :job', [
    ':job' => 'Presenter',
  ])
    ->fetch();
  $this
    ->assertEquals('Presenter', $person->job, 'Job set correctly.');
  $this
    ->assertEquals(31, $person->age, 'Age set correctly.');
  $this
    ->assertEquals('Tiffany', $person->name, 'Name set correctly.');
  $person = $connection
    ->query('SELECT * FROM {test_people} WHERE [job] = :job', [
    ':job' => 'Speaker',
  ])
    ->fetch();
  $this
    ->assertEquals('Speaker', $person->job, 'Job was not changed.');
  $this
    ->assertEquals(32, $person->age, 'Age updated correctly.');
  $this
    ->assertEquals('Meredith', $person->name, 'Name was not changed.');
}