function StatementTest::testRepeatedInsertStatementReuse

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Database/StatementTest.php \Drupal\KernelTests\Core\Database\StatementTest::testRepeatedInsertStatementReuse()
  2. 11.x core/tests/Drupal/KernelTests/Core/Database/StatementTest.php \Drupal\KernelTests\Core\Database\StatementTest::testRepeatedInsertStatementReuse()

Tests that a prepared statement object can be reused for multiple inserts.

File

core/tests/Drupal/KernelTests/Core/Database/StatementTest.php, line 19

Class

StatementTest
Tests the Statement classes.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testRepeatedInsertStatementReuse() : void {
  $num_records_before = $this->connection
    ->select('test')
    ->countQuery()
    ->execute()
    ->fetchField();
  $sql = "INSERT INTO {test} ([name], [age]) VALUES (:name, :age)";
  $args = [
    ':name' => 'Larry',
    ':age' => '30',
  ];
  $options = [
    'allow_square_brackets' => FALSE,
  ];
  $stmt = $this->connection
    ->prepareStatement($sql, $options);
  $this->assertInstanceOf(StatementInterface::class, $stmt);
  $this->assertTrue($stmt->execute($args, $options));
  // We should be able to specify values in any order if named.
  $args = [
    ':age' => '31',
    ':name' => 'Curly',
  ];
  $this->assertTrue($stmt->execute($args, $options));
  $num_records_after = $this->connection
    ->select('test')
    ->countQuery()
    ->execute()
    ->fetchField();
  $this->assertEquals($num_records_before + 2, $num_records_after);
  $this->assertSame('30', $this->connection
    ->query('SELECT [age] FROM {test} WHERE [name] = :name', [
    ':name' => 'Larry',
  ])
    ->fetchField());
  $this->assertSame('31', $this->connection
    ->query('SELECT [age] FROM {test} WHERE [name] = :name', [
    ':name' => 'Curly',
  ])
    ->fetchField());
}

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