You are here

public function DeleteTruncateTest::testSubselectDelete in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Database/DeleteTruncateTest.php \Drupal\KernelTests\Core\Database\DeleteTruncateTest::testSubselectDelete()

Confirms that we can use a subselect in a delete successfully.

File

core/tests/Drupal/KernelTests/Core/Database/DeleteTruncateTest.php, line 23

Class

DeleteTruncateTest
Tests delete and truncate queries.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testSubselectDelete() {
  $num_records_before = $this->connection
    ->query('SELECT COUNT(*) FROM {test_task}')
    ->fetchField();
  $pid_to_delete = $this->connection
    ->query("SELECT * FROM {test_task} WHERE task = 'sleep' ORDER BY tid")
    ->fetchField();
  $subquery = $this->connection
    ->select('test', 't')
    ->fields('t', [
    'id',
  ])
    ->condition('t.id', [
    $pid_to_delete,
  ], 'IN');
  $delete = $this->connection
    ->delete('test_task')
    ->condition('task', 'sleep')
    ->condition('pid', $subquery, 'IN');
  $num_deleted = $delete
    ->execute();
  $this
    ->assertEqual($num_deleted, 1, 'Deleted 1 record.');
  $num_records_after = $this->connection
    ->query('SELECT COUNT(*) FROM {test_task}')
    ->fetchField();
  $this
    ->assertEqual($num_records_before, $num_records_after + $num_deleted, 'Deletion adds up.');
}