BUG SQLQuery::aggregate() with limit, groupBy and orderBy (fixes #8148)

This commit is contained in:
g4b0 2012-12-20 14:04:22 +01:00 committed by Ingo Schommer
parent 8ec3641e60
commit e53280c650
3 changed files with 29 additions and 9 deletions

View File

@ -1060,18 +1060,22 @@ class SQLQuery {
/**
* Return a new SQLQuery that calls the given aggregate functions on this data.
*
* @param $column An aggregate expression, such as 'MAX("Balance")', or a set of them (as an escaped SQL statement)
* @param $alias An optional alias for the aggregate column.
*/
public function aggregate($column) {
if($this->groupby || $this->limit) {
throw new Exception("SQLQuery::aggregate() doesn't work with groupby or limit, yet");
}
public function aggregate($column, $alias = null) {
$clone = clone $this;
$clone->setLimit(array());
$clone->setOrderBy(array());
$clone->setGroupBy(array());
$clone->setSelect($column);
$clone->setLimit($this->limit);
$clone->setOrderBy($this->orderby);
$clone->setGroupBy($this->groupby);
if($alias) {
$clone->selectField($column, $alias);
} else {
$clone->setSelect($column);
}
return $clone;
}

View File

@ -367,6 +367,19 @@ class SQLQueryTest extends SapphireTest {
$this->assertEquals('Object 1', $row['Name']);
}
}
/**
* Tests aggregate() function
*/
public function testAggregate() {
$query = new SQLQuery();
$query->setFrom('"SQLQueryTest_DO"');
$query->setGroupBy("Common");
$queryClone = $query->aggregate('COUNT(*)', 'cnt');
$result = $queryClone->execute();
$this->assertEquals(array(2), $result->column('cnt'));
}
/**
* Test that "_SortColumn0" is added for an aggregate in the ORDER BY
@ -399,6 +412,7 @@ class SQLQueryTest_DO extends DataObject implements TestOnly {
static $db = array(
"Name" => "Varchar",
"Meta" => "Varchar",
"Common" => "Varchar",
"Date" => "SS_Datetime"
);
}

View File

@ -2,8 +2,10 @@ SQLQueryTest_DO:
test1:
Name: 'Object 1'
Meta: 'Details 1'
Common: 'Common Value'
Date: 2012-01-01 10:00:00
test2:
Name: 'Object 2'
Meta: 'Details 2'
Date: 2012-05-01 09:00:00
Common: 'Common Value'