function UpsertTest::testUpsertWithKeywords
Same name in other branches
- 10 core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php \Drupal\KernelTests\Core\Database\UpsertTest::testUpsertWithKeywords()
- 11.x core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php \Drupal\KernelTests\Core\Database\UpsertTest::testUpsertWithKeywords()
Confirms that we can upsert records with keywords successfully.
File
-
core/
tests/ Drupal/ KernelTests/ Core/ Database/ UpsertTest.php, line 62
Class
- UpsertTest
- Tests the Upsert query builder.
Namespace
Drupal\KernelTests\Core\DatabaseCode
public function testUpsertWithKeywords() {
$num_records_before = $this->connection
->query('SELECT COUNT(*) FROM {select}')
->fetchField();
$upsert = $this->connection
->upsert('select')
->key('id')
->fields([
'id',
'update',
]);
// Add a new row.
$upsert->values([
// Test a non sequence ID for better testing of the default return value.
'id' => 3,
'update' => 'Update value 2',
]);
// Update an existing row.
$upsert->values([
'id' => 1,
'update' => 'Update value 1 updated',
]);
$result = $upsert->execute();
$this->assertIsInt($result);
// The upsert returns the number of rows affected. For MySQL the return
// value is 3 because the affected-rows value per row is 1 if the row is
// inserted as a new row, 2 if an existing row is updated. See
// https://dev.mysql.com/doc/c-api/8.0/en/mysql-affected-rows.html.
$this->assertGreaterThanOrEqual(2, $result, 'The result of the upsert operation should report that at least two rows were affected.');
$num_records_after = $this->connection
->query('SELECT COUNT(*) FROM {select}')
->fetchField();
$this->assertEquals($num_records_before + 1, $num_records_after, 'Rows were inserted and updated properly.');
$record = $this->connection
->query('SELECT * FROM {select} WHERE [id] = :id', [
':id' => 1,
])
->fetch();
$this->assertEquals('Update value 1 updated', $record->update);
$record = $this->connection
->query('SELECT * FROM {select} WHERE [id] = :id', [
':id' => 3,
])
->fetch();
$this->assertEquals('Update value 2', $record->update);
// An upsert should be re-usable.
$upsert->values([
'id' => 4,
'update' => 'Another value',
]);
$return_value = $upsert->execute();
$this->assertSame(1, $return_value);
$record = $this->connection
->query('SELECT * FROM {select} WHERE [id] = :id', [
':id' => 4,
])
->fetch();
$this->assertEquals('Another value', $record->update);
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.