You are here

function SelectComplexTest::testGroupBy in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Database/SelectComplexTest.php \Drupal\system\Tests\Database\SelectComplexTest::testGroupBy()

Tests GROUP BY clauses.

File

core/modules/system/src/Tests/Database/SelectComplexTest.php, line 79
Contains \Drupal\system\Tests\Database\SelectComplexTest.

Class

SelectComplexTest
Tests the Select query builder with more complex queries.

Namespace

Drupal\system\Tests\Database

Code

function testGroupBy() {
  $query = db_select('test_task', 't');
  $count_field = $query
    ->addExpression('COUNT(task)', 'num');
  $task_field = $query
    ->addField('t', 'task');
  $query
    ->orderBy($count_field);
  $query
    ->groupBy($task_field);
  $result = $query
    ->execute();
  $num_records = 0;
  $last_count = 0;
  $records = array();
  foreach ($result as $record) {
    $num_records++;
    $this
      ->assertTrue($record->{$count_field} >= $last_count, 'Results returned in correct order.');
    $last_count = $record->{$count_field};
    $records[$record->{$task_field}] = $record->{$count_field};
  }
  $correct_results = array(
    'eat' => 1,
    'sleep' => 2,
    'code' => 1,
    'found new band' => 1,
    'perform at superbowl' => 1,
  );
  foreach ($correct_results as $task => $count) {
    $this
      ->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", array(
      '@task' => $task,
    )));
  }
  $this
    ->assertEqual($num_records, 6, 'Returned the correct number of total rows.');
}