You are here

function MergeTest::testMergeUpdateExpression in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Database/MergeTest.php \Drupal\system\Tests\Database\MergeTest::testMergeUpdateExpression()

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

File

core/modules/system/src/Tests/Database/MergeTest.php, line 123
Contains \Drupal\system\Tests\Database\MergeTest.

Class

MergeTest
Tests the MERGE query builder.

Namespace

Drupal\system\Tests\Database

Code

function testMergeUpdateExpression() {
  $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')
    ->fetchField();
  $age_before = db_query('SELECT age FROM {test_people} WHERE job = :job', array(
    ':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.
  db_merge('test_people')
    ->key('job', 'Speaker')
    ->fields(array(
    'name' => 'Tiffany',
  ))
    ->insertFields(array(
    'age' => 31,
  ))
    ->expression('age', 'age + :age', array(
    ':age' => 4,
  ))
    ->execute();
  $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')
    ->fetchField();
  $this
    ->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
  $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(
    ':job' => 'Speaker',
  ))
    ->fetch();
  $this
    ->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
  $this
    ->assertEqual($person->age, $age_before + 4, 'Age updated correctly.');
  $this
    ->assertEqual($person->job, 'Speaker', 'Job set correctly.');
}