You are here

public function DatabaseExceptionWrapperTest::testPrepare in Drupal 9

Tests deprecation of Connection::prepare.

@group legacy

File

core/tests/Drupal/KernelTests/Core/Database/DatabaseExceptionWrapperTest.php, line 21

Class

DatabaseExceptionWrapperTest
Tests exceptions thrown by queries.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testPrepare() {
  $this
    ->expectDeprecation('Connection::prepare() is deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Database drivers should instantiate \\PDOStatement objects by calling \\PDO::prepare in their Connection::prepareStatement method instead. \\PDO::prepare should not be called outside of driver code. See https://www.drupal.org/node/3137786');
  $connection = Database::getConnection();
  try {

    // SQLite validates the syntax upon preparing a statement already.
    // @throws \PDOException
    $query = $connection
      ->prepare('bananas');

    // MySQL only validates the syntax upon trying to execute a query.
    // @throws \Drupal\Core\Database\DatabaseExceptionWrapper
    $connection
      ->query($query);
    $this
      ->fail('Expected PDOException or DatabaseExceptionWrapper, none was thrown.');
  } catch (\Exception $e) {
    $this
      ->assertTrue($e instanceof \PDOException || $e instanceof DatabaseExceptionWrapper, 'Exception should be an instance of \\PDOException or DatabaseExceptionWrapper, thrown ' . get_class($e));
  }
}