function NonPublicSchemaTest::testUpsert

Same name in other branches
  1. 11.x core/modules/pgsql/tests/src/Kernel/pgsql/NonPublicSchemaTest.php \Drupal\Tests\pgsql\Kernel\pgsql\NonPublicSchemaTest::testUpsert()

@covers \Drupal\Core\Database\Connection::upsert

File

core/modules/pgsql/tests/src/Kernel/pgsql/NonPublicSchemaTest.php, line 185

Class

NonPublicSchemaTest
Tests schema API for non-public schema for the PostgreSQL driver.

Namespace

Drupal\Tests\pgsql\Kernel\pgsql

Code

public function testUpsert() : void {
    $num_records_before = $this->testingFakeConnection
        ->query('SELECT COUNT(*) FROM {faking_table}')
        ->fetchField();
    $upsert = $this->testingFakeConnection
        ->upsert('faking_table')
        ->key('id')
        ->fields([
        'id',
        'test_field',
    ]);
    // Upserting a new row.
    $upsert->values([
        'id' => '456',
        'test_field' => '444',
    ]);
    // Upserting an existing row.
    $upsert->values([
        'id' => '1',
        'test_field' => '898',
    ]);
    $result = $upsert->execute();
    $this->assertSame(2, $result, 'The result of the upsert operation should report that at exactly two rows were affected.');
    $num_records_after = $this->testingFakeConnection
        ->query('SELECT COUNT(*) FROM {faking_table}')
        ->fetchField();
    $this->assertEquals($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
    // Check if new row has been added with upsert.
    $result = $this->testingFakeConnection
        ->query('SELECT * FROM {faking_table} WHERE [id] = :id', [
        ':id' => '456',
    ])
        ->fetch();
    $this->assertEquals('456', $result->id, 'ID set correctly.');
    $this->assertEquals('444', $result->test_field, 'test_field set correctly.');
    // Check if new row has been edited with upsert.
    $result = $this->testingFakeConnection
        ->query('SELECT * FROM {faking_table} WHERE [id] = :id', [
        ':id' => '1',
    ])
        ->fetch();
    $this->assertEquals('1', $result->id, 'ID set correctly.');
    $this->assertEquals('898', $result->test_field, 'test_field set correctly.');
}

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