diff --git a/core/modules/system/tests/modules/database_test/database_test.install b/core/modules/system/tests/modules/database_test/database_test.install index effd261994db612edc7dcb2e96b7d8fb9e064036..47ed774a590a1ecabe07297dbbfec31c75d009e5 100644 --- a/core/modules/system/tests/modules/database_test/database_test.install +++ b/core/modules/system/tests/modules/database_test/database_test.install @@ -320,7 +320,9 @@ function database_test_schema() { 'fields' => [ 'id' => [ 'description' => 'Simple unique ID.', - 'type' => 'int', + // Using a serial as an ID properly tests + // \Drupal\Core\Database\Driver\pgsql\Upsert. + 'type' => 'serial', 'not null' => TRUE, ], 'update' => [ diff --git a/core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php b/core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php index 30474c541d98f2bae0e377d1a80cf69cc366a139..f46fd41e66b23a79c73bcfe5b63d10d5402cbee4 100644 --- a/core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php +++ b/core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php @@ -68,7 +68,8 @@ public function testUpsertWithKeywords() { // Add a new row. $upsert->values([ - 'id' => 2, + // Test a non sequence ID for better testing of the default return value. + 'id' => 3, 'update' => 'Update value 2', ]); @@ -80,6 +81,10 @@ public function testUpsertWithKeywords() { $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(); @@ -88,8 +93,18 @@ public function testUpsertWithKeywords() { $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' => 2])->fetch(); + $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); } /**