diff --git a/model/SQLQuery.php b/model/SQLQuery.php index d7729d7a9..4503b5624 100644 --- a/model/SQLQuery.php +++ b/model/SQLQuery.php @@ -566,6 +566,7 @@ class SQLQuery { if($this->orderby) { $i = 0; foreach($this->orderby as $clause => $dir) { + // public function calls and multi-word columns like "CASE WHEN ..." if(strpos($clause, '(') !== false || strpos($clause, " ") !== false ) { // remove the old orderby diff --git a/tests/model/SQLQueryTest.php b/tests/model/SQLQueryTest.php index f59c2d519..d3e64b827 100755 --- a/tests/model/SQLQueryTest.php +++ b/tests/model/SQLQueryTest.php @@ -368,12 +368,38 @@ class SQLQueryTest extends SapphireTest { } } + /** + * Test that "_SortColumn0" is added for an aggregate in the ORDER BY + * clause, in combination with a LIMIT and GROUP BY clause. + * For some databases, like MSSQL, this is a complicated scenario + * because a subselect needs to be done to query paginated data. + */ + public function testOrderByContainingAggregateAndLimitOffset() { + $query = new SQLQuery(); + $query->setSelect(array('"Name"', '"Meta"')); + $query->setFrom('"SQLQueryTest_DO"'); + $query->setOrderBy(array('MAX(Date)')); + $query->setGroupBy(array('"Name"', '"Meta"')); + $query->setLimit('1', '1'); + + $records = array(); + foreach($query->execute() as $record) { + $records[] = $record; + } + + $this->assertCount(1, $records); + + $this->assertEquals('Object 2', $records[0]['Name']); + $this->assertEquals('2012-05-01 09:00:00', $records['0']['_SortColumn0']); + } + } class SQLQueryTest_DO extends DataObject implements TestOnly { static $db = array( "Name" => "Varchar", "Meta" => "Varchar", + "Date" => "SS_Datetime" ); } diff --git a/tests/model/SQLQueryTest.yml b/tests/model/SQLQueryTest.yml index 725b7dee4..9d88cd25b 100644 --- a/tests/model/SQLQueryTest.yml +++ b/tests/model/SQLQueryTest.yml @@ -2,6 +2,8 @@ SQLQueryTest_DO: test1: Name: 'Object 1' Meta: 'Details 1' + Date: 2012-01-01 10:00:00 test2: Name: 'Object 2' - Meta: 'Details 2' \ No newline at end of file + Meta: 'Details 2' + Date: 2012-05-01 09:00:00