function MergeTest::testMergeUpdateExpression

Same name in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Database/MergeTest.php \Drupal\KernelTests\Core\Database\MergeTest::testMergeUpdateExpression()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Database/MergeTest.php \Drupal\KernelTests\Core\Database\MergeTest::testMergeUpdateExpression()
  3. 10 core/tests/Drupal/KernelTests/Core/Database/MergeTest.php \Drupal\KernelTests\Core\Database\MergeTest::testMergeUpdateExpression()

Confirms that we can merge-update a record successfully, with expressions.

File

core/tests/Drupal/KernelTests/Core/Database/MergeTest.php, line 120

Class

MergeTest
Tests the MERGE query builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testMergeUpdateExpression() : void {
    $num_records_before = $this->connection
        ->query('SELECT COUNT(*) FROM {test_people}')
        ->fetchField();
    $age_before = $this->connection
        ->query('SELECT [age] FROM {test_people} WHERE [job] = :job', [
        ':job' => 'Speaker',
    ])
        ->fetchField();
    // This is a very contrived example, as I have no idea why you'd want to
    // change age this way, but that's beside the point.
    // Note that we are also double-setting age here, once as a literal and
    // once as an expression. This test will only pass if the expression wins,
    // which is what is supposed to happen.
    $this->connection
        ->merge('test_people')
        ->key('job', 'Speaker')
        ->fields([
        'name' => 'Tiffany',
    ])
        ->insertFields([
        'age' => 31,
    ])
        ->expression('age', '[age] + :age', [
        ':age' => 4,
    ])
        ->execute();
    $num_records_after = $this->connection
        ->query('SELECT COUNT(*) FROM {test_people}')
        ->fetchField();
    $this->assertEquals($num_records_before, $num_records_after, 'Merge updated properly.');
    $person = $this->connection
        ->query('SELECT * FROM {test_people} WHERE [job] = :job', [
        ':job' => 'Speaker',
    ])
        ->fetch();
    $this->assertEquals('Tiffany', $person->name, 'Name set correctly.');
    $this->assertEquals($age_before + 4, $person->age, 'Age updated correctly.');
    $this->assertEquals('Speaker', $person->job, 'Job set correctly.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.