function UpsertTest::testDegeneratedCompositeKeyUpsert

Same name and namespace in other branches
  1. main core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php \Drupal\KernelTests\Core\Database\UpsertTest::testDegeneratedCompositeKeyUpsert()

Tests an upsert with a composite key and no columns to update.

File

core/tests/Drupal/KernelTests/Core/Database/UpsertTest.php, line 270

Class

UpsertTest
Tests the Upsert query builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testDegeneratedCompositeKeyUpsert() : void {
  $this->installSchema('database_test', [
    'test_composite_primary',
  ]);
  // Insert two new rows.
  $this->connection
    ->insert('test_composite_primary')
    ->fields([
    'name' => 'Kate',
    'age' => 25,
    'job' => 'Volunteer',
  ])
    ->values([
    'name' => 'Bertie',
    'age' => 6,
    'job' => 'Puppet',
  ])
    ->execute();
  $this->assertSame('2', $this->connection
    ->query('SELECT COUNT(*) FROM {test_composite_primary}')
    ->fetchField());
  // Performing an upsert with the same composite key should be a no-op.
  $this->connection
    ->upsert('test_composite_primary')
    ->key([
    'name',
    'age',
  ])
    ->fields([
    'name' => 'Kate',
    'age' => 25,
  ])
    ->values([
    'name' => 'Bertie',
    'age' => 6,
  ])
    ->execute();
  $this->assertSame('2', $this->connection
    ->query('SELECT COUNT(*) FROM {test_composite_primary}')
    ->fetchField());
  // Different composite keys should insert other rows.
  $this->connection
    ->upsert('test_composite_primary')
    ->key([
    'name',
    'age',
  ])
    ->fields([
    'name',
    'age',
  ])
    ->values([
    'name' => 'Kate',
    'age' => 25,
  ])
    ->values([
    'name' => 'Arthur',
    'age' => 30,
  ])
    ->values([
    'name' => 'Bertie',
    'age' => 6,
  ])
    ->values([
    'name' => 'Zaphod',
    'age' => 200,
  ])
    ->execute();
  $this->assertSame('4', $this->connection
    ->query('SELECT COUNT(*) FROM {test_composite_primary}')
    ->fetchField());
}

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