Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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

  • Loading branch information...
commit e53280c6500e82a28b5ffec1ec3c24d2df9aad87 1 parent 8ec3641
g4b0 authored chillu committed
View
22 model/SQLQuery.php
@@ -1060,18 +1060,22 @@ public function count( $column = null) {
/**
* 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
14 tests/model/SQLQueryTest.php
@@ -367,6 +367,19 @@ public function testSelectLast() {
$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
2  tests/model/SQLQueryTest.yml
@@ -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'
Please sign in to comment.
Something went wrong with that request. Please try again.