Upgraded drupal core with security updates
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Database / InvalidDataTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Database;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\IntegrityConstraintViolationException;
7
8 /**
9  * Tests handling of some invalid data.
10  *
11  * @group Database
12  */
13 class InvalidDataTest extends DatabaseTestBase {
14   /**
15    * Tests aborting of traditional SQL database systems with invalid data.
16    */
17   public function testInsertDuplicateData() {
18     // Try to insert multiple records where at least one has bad data.
19     try {
20       db_insert('test')
21         ->fields(['name', 'age', 'job'])
22         ->values([
23           'name' => 'Elvis',
24           'age' => 63,
25           'job' => 'Singer',
26         ])->values([
27           'name' => 'John', // <-- Duplicate value on unique field.
28           'age' => 17,
29           'job' => 'Consultant',
30         ])
31         ->values([
32           'name' => 'Frank',
33           'age' => 75,
34           'job' => 'Singer',
35         ])
36         ->execute();
37       $this->fail('Insert succeeded when it should not have.');
38     }
39     catch (IntegrityConstraintViolationException $e) {
40       // Check if the first record was inserted.
41       $name = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 63])->fetchField();
42
43       if ($name == 'Elvis') {
44         if (!Database::getConnection()->supportsTransactions()) {
45           // This is an expected fail.
46           // Database engines that don't support transactions can leave partial
47           // inserts in place when an error occurs. This is the case for MySQL
48           // when running on a MyISAM table.
49           $this->pass("The whole transaction has not been rolled-back when a duplicate key insert occurs, this is expected because the database doesn't support transactions");
50         }
51         else {
52           $this->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
53         }
54       }
55       else {
56         $this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
57       }
58
59       // Ensure the other values were not inserted.
60       $record = db_select('test')
61         ->fields('test', ['name', 'age'])
62         ->condition('age', [17, 75], 'IN')
63         ->execute()->fetchObject();
64
65       $this->assertFalse($record, 'The rest of the insert aborted as expected.');
66     }
67   }
68
69 }