function InvalidDataTest::testInsertDuplicateData

Same name and namespace in other branches
  1. 8.9.x core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php \Drupal\KernelTests\Core\Database\InvalidDataTest::testInsertDuplicateData()
  2. 10 core/tests/Drupal/KernelTests/Core/Database/InvalidDataTest.php \Drupal\KernelTests\Core\Database\InvalidDataTest::testInsertDuplicateData()
  3. 11.x 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;
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.