function InsertTest::testRepeatedInsert

Same name in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Database/InsertTest.php \Drupal\KernelTests\Core\Database\InsertTest::testRepeatedInsert()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Database/InsertTest.php \Drupal\KernelTests\Core\Database\InsertTest::testRepeatedInsert()
  3. 11.x core/tests/Drupal/KernelTests/Core/Database/InsertTest.php \Drupal\KernelTests\Core\Database\InsertTest::testRepeatedInsert()

Tests that an insert object can be reused with new data after it executes.

File

core/tests/Drupal/KernelTests/Core/Database/InsertTest.php, line 80

Class

InsertTest
Tests the insert builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testRepeatedInsert() : void {
    $num_records_before = $this->connection
        ->query('SELECT COUNT(*) FROM {test}')
        ->fetchField();
    $query = $this->connection
        ->insert('test');
    $query->fields([
        'name' => 'Larry',
        'age' => '30',
    ]);
    // Check how many records are queued for insertion.
    $this->assertCount(1, $query, 'One record is queued for insertion.');
    // This should run the insert, but leave the fields intact.
    $query->execute();
    // We should be able to specify values in any order if named.
    $query->values([
        'age' => '31',
        'name' => 'Curly',
    ]);
    // Check how many records are queued for insertion.
    $this->assertCount(1, $query, 'One record is queued for insertion.');
    $query->execute();
    // We should be able to say "use the field order".
    $query->values([
        'Moe',
        '32',
    ]);
    // Check how many records are queued for insertion.
    $this->assertCount(1, $query, 'One record is queued for insertion.');
    $query->execute();
    $num_records_after = $this->connection
        ->query('SELECT COUNT(*) FROM {test}')
        ->fetchField();
    $this->assertSame((int) $num_records_before + 3, (int) $num_records_after, 'Record inserts correctly.');
    $saved_age = $this->connection
        ->query('SELECT [age] FROM {test} WHERE [name] = :name', [
        ':name' => 'Larry',
    ])
        ->fetchField();
    $this->assertSame('30', $saved_age, 'Can retrieve after inserting.');
    $saved_age = $this->connection
        ->query('SELECT [age] FROM {test} WHERE [name] = :name', [
        ':name' => 'Curly',
    ])
        ->fetchField();
    $this->assertSame('31', $saved_age, 'Can retrieve after inserting.');
    $saved_age = $this->connection
        ->query('SELECT [age] FROM {test} WHERE [name] = :name', [
        ':name' => 'Moe',
    ])
        ->fetchField();
    $this->assertSame('32', $saved_age, 'Can retrieve after inserting.');
}

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