You are here

function DatabaseSelectComplexTestCase::testGroupByAndHaving in SimpleTest 7

Test GROUP BY and HAVING clauses together.

File

tests/database_test.test, line 1749

Class

DatabaseSelectComplexTestCase
Test more complex select statements.

Code

function testGroupByAndHaving() {
  $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);
  $query
    ->havingCondition('COUNT(task)', 2, '>=');
  $result = $query
    ->execute();
  $num_records = 0;
  $last_count = 0;
  $records = array();
  foreach ($result as $record) {
    $num_records++;
    $this
      ->assertTrue($record->{$count_field} >= 2, t('Record has the minimum count.'));
    $this
      ->assertTrue($record->{$count_field} >= $last_count, t('Results returned in correct order.'));
    $last_count = $record->{$count_field};
    $records[$record->{$task_field}] = $record->{$count_field};
  }
  $correct_results = array(
    'sleep' => 2,
  );
  foreach ($correct_results as $task => $count) {
    $this
      ->assertEqual($records[$task], $count, t("Correct number of '@task' records found.", array(
      '@task' => $task,
    )));
  }
  $this
    ->assertEqual($num_records, 1, t('Returned the correct number of total rows.'));
}