You are here

public function InvalidDataTest::testInsertDuplicateData in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php \Drupal\KernelTests\Core\Database\InvalidDataTest::testInsertDuplicateData()

Tests aborting of traditional SQL database systems with invalid data.

File

core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php, line 17

Class

InvalidDataTest
Tests handling of some invalid data.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testInsertDuplicateData() {

  // Try to insert multiple records where at least one has bad data.
  $this
    ->expectException(IntegrityConstraintViolationException::class);
  try {
    $this->connection
      ->insert('test')
      ->fields([
      'name',
      'age',
      'job',
    ])
      ->values([
      'name' => 'Elvis',
      'age' => 63,
      'job' => 'Singer',
    ])
      ->values([
      // Duplicate value 'John' on unique field 'name'.
      'name' => 'John',
      'age' => 17,
      'job' => 'Consultant',
    ])
      ->values([
      'name' => 'Frank',
      'age' => 75,
      'job' => 'Singer',
    ])
      ->execute();
    $this
      ->fail('Insert succeeded when it should not have.');
  } catch (IntegrityConstraintViolationException $e) {

    // Ensure the whole transaction is rolled back when a duplicate key
    // insert occurs.
    $this
      ->assertFalse($this->connection
      ->select('test')
      ->fields('test', [
      'name',
      'age',
    ])
      ->condition('age', [
      63,
      17,
      75,
    ], 'IN')
      ->execute()
      ->fetchObject());
    throw $e;
  }
}