function InsertTest::testInsertFromWithSerialKey

Tests inserting from a select into a table that has a serial primary key.

File

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

Class

InsertTest
Tests the insert builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testInsertFromWithSerialKey() : void {
  // Create a copy of the test table.
  $schema = database_test_schema();
  $this->connection
    ->schema()
    ->createTable('test_backup', $schema['test']);
  $this->connection
    ->insert('test_backup')
    ->from($this->connection
    ->select('test')
    ->fields('test'))
    ->execute();
  $this->assertSame(4, (int) $this->connection
    ->select('test_backup')
    ->countQuery()
    ->execute()
    ->fetchField());
  $this->connection
    ->insert('test_backup')
    ->fields([
    'name' => 'Larry',
    'age' => '30',
  ])
    ->execute();
  $this->assertSame(5, (int) $this->connection
    ->select('test_backup')
    ->countQuery()
    ->execute()
    ->fetchField());
  // Recreate table to reset the serial counters.
  $this->connection
    ->schema()
    ->dropTable('test_backup');
  $this->connection
    ->schema()
    ->createTable('test_backup', $schema['test']);
  // Add fields to the select query, so that the primary key is included.
  $this->connection
    ->insert('test_backup')
    ->from($this->connection
    ->select('test')
    ->fields('test', [
    'id',
    'name',
  ]))
    ->execute();
  $this->assertSame(4, (int) $this->connection
    ->select('test_backup')
    ->countQuery()
    ->execute()
    ->fetchField());
  $this->connection
    ->insert('test_backup')
    ->fields([
    'name' => 'Larry',
    'age' => '30',
  ])
    ->execute();
  $this->assertSame(5, (int) $this->connection
    ->select('test_backup')
    ->countQuery()
    ->execute()
    ->fetchField());
  // Recreate table to reset the serial counters.
  $this->connection
    ->schema()
    ->dropTable('test_backup');
  $this->connection
    ->schema()
    ->createTable('test_backup', $schema['test']);
  // Add fields to the select query, so that the primary key is included.
  $this->connection
    ->insert('test_backup')
    ->from($this->connection
    ->select('test')
    ->fields('test', [
    'name',
  ]))
    ->execute();
  $this->assertSame(4, (int) $this->connection
    ->select('test_backup')
    ->countQuery()
    ->execute()
    ->fetchField());
  $this->connection
    ->insert('test_backup')
    ->fields([
    'name' => 'Larry',
    'age' => '30',
  ])
    ->execute();
  $this->assertSame(5, (int) $this->connection
    ->select('test_backup')
    ->countQuery()
    ->execute()
    ->fetchField());
}

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