You are here

public function InsertTest::testMultiInsert in Drupal 9

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

Tests that we can insert multiple records in one query object.

File

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

Class

InsertTest
Tests the insert builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testMultiInsert() {
  $num_records_before = (int) $this->connection
    ->query('SELECT COUNT(*) FROM {test}')
    ->fetchField();
  $query = $this->connection
    ->insert('test');
  $query
    ->fields([
    'name' => 'Larry',
    'age' => '30',
  ]);

  // 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
    ->assertSame(2, $query
    ->count(), 'Two records are queued for insertion.');

  // We should be able to say "use the field order".
  // This is not the recommended mechanism for most cases, but it should work.
  $query
    ->values([
    'Moe',
    '32',
  ]);

  // Check how many records are queued for insertion.
  $this
    ->assertSame(3, $query
    ->count(), 'Three records are queued for insertion.');
  $query
    ->execute();
  $num_records_after = (int) $this->connection
    ->query('SELECT COUNT(*) FROM {test}')
    ->fetchField();
  $this
    ->assertSame($num_records_before + 3, $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.');
}