3 namespace Drupal\KernelTests\Core\Database;
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\IntegrityConstraintViolationException;
9 * Tests handling of some invalid data.
13 class InvalidDataTest extends DatabaseTestBase {
15 * Tests aborting of traditional SQL database systems with invalid data.
17 public function testInsertDuplicateData() {
18 // Try to insert multiple records where at least one has bad data.
21 ->fields(['name', 'age', 'job'])
27 'name' => 'John', // <-- Duplicate value on unique field.
29 'job' => 'Consultant',
37 $this->fail('Insert succeeded when it should not have.');
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();
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");
52 $this->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
56 $this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
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();
65 $this->assertFalse($record, 'The rest of the insert aborted as expected.');