SelectOrderedTest.php 2.56 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Definition of Drupal\system\Tests\Database\SelectOrderedTest.
 */

namespace Drupal\system\Tests\Database;

/**
11
 * Tests SELECT with ORDER BY clauses.
12 13 14 15 16 17 18 19 20 21 22 23
 */
class SelectOrderedTest extends DatabaseTestBase {

  public static function getInfo() {
    return array(
      'name' => 'Select tests, ordered',
      'description' => 'Test the Select query builder.',
      'group' => 'Database',
    );
  }

  /**
24
   * Tests basic ORDER BY.
25 26 27 28 29 30 31 32 33 34 35 36
   */
  function testSimpleSelectOrdered() {
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->orderBy($age_field);
    $result = $query->execute();

    $num_records = 0;
    $last_age = 0;
    foreach ($result as $record) {
      $num_records++;
37
      $this->assertTrue($record->age >= $last_age, 'Results returned in correct order.');
38 39 40
      $last_age = $record->age;
    }

41
    $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
42 43 44
  }

  /**
45
   * Tests multiple ORDER BY.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
   */
  function testSimpleSelectMultiOrdered() {
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $job_field = $query->addField('test', 'job');
    $query->orderBy($job_field);
    $query->orderBy($age_field);
    $result = $query->execute();

    $num_records = 0;
    $expected = array(
      array('Ringo', 28, 'Drummer'),
      array('John', 25, 'Singer'),
      array('George', 27, 'Singer'),
      array('Paul', 26, 'Songwriter'),
    );
63
    $results = $result->fetchAll(\PDO::FETCH_NUM);
64 65 66 67
    foreach ($expected as $k => $record) {
      $num_records++;
      foreach ($record as $kk => $col) {
        if ($expected[$k][$kk] != $results[$k][$kk]) {
68
          $this->assertTrue(FALSE, 'Results returned in correct order.');
69 70 71
        }
      }
    }
72
    $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
73 74 75
  }

  /**
76
   * Tests ORDER BY descending.
77 78 79 80 81 82 83 84 85 86 87 88
   */
  function testSimpleSelectOrderedDesc() {
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->orderBy($age_field, 'DESC');
    $result = $query->execute();

    $num_records = 0;
    $last_age = 100000000;
    foreach ($result as $record) {
      $num_records++;
89
      $this->assertTrue($record->age <= $last_age, 'Results returned in correct order.');
90 91 92
      $last_age = $record->age;
    }

93
    $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
94 95
  }
}