From 6f9aa32ccc4c80670de551623563f63c297b66f1 Mon Sep 17 00:00:00 2001 From: Sam Minnee Date: Wed, 28 Apr 2010 01:19:04 +0000 Subject: [PATCH] BUGFIX: Fixed unlimitedRowCount() for grouped queries git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/2.4@103613 467b73ca-7a2a-4603-9d3b-597d59a354a9 --- core/model/SQLQuery.php | 27 ++++++++++++++------------- tests/DataObjectTest.php | 10 ++++++++++ 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/core/model/SQLQuery.php b/core/model/SQLQuery.php index 42983839d..79d3399aa 100755 --- a/core/model/SQLQuery.php +++ b/core/model/SQLQuery.php @@ -419,12 +419,6 @@ class SQLQuery { /// VARIOUS TRANSFORMATIONS BELOW - /** - * Return the number of rows in this query if the limit were removed. Useful in paged data sets. - * @return int - * - * TODO Respect HAVING and GROUPBY, which can affect the result-count - */ function unlimitedRowCount( $column = null) { // we can't clear the select if we're relying on its output by a HAVING clause if(count($this->having)) { @@ -432,19 +426,26 @@ class SQLQuery { return $records->numRecords(); } + $clone = clone $this; + $clone->limit = null; + $clone->orderby = null; + // Choose a default column if($column == null) { if($this->groupby) { - $column = 'DISTINCT ' . implode(", ", $this->groupby); + $countQuery = new SQLQuery(); + $countQuery->select = array("count(*)"); + $countQuery->from = array('(' . $clone->sql() . ') as all_distinct'); + + return $countQuery->execute()->value(); + } else { - $column = '*'; + $clone->select = array("count(*)"); } + } else { + $clone->select = array("count($column)"); } - - $clone = clone $this; - $clone->select = array("count($column)"); - $clone->limit = null; - $clone->orderby = null; + $clone->groupby = null; return $clone->execute()->value(); } diff --git a/tests/DataObjectTest.php b/tests/DataObjectTest.php index 163fe1d60..e82c30031 100755 --- a/tests/DataObjectTest.php +++ b/tests/DataObjectTest.php @@ -741,6 +741,16 @@ class DataObjectTest extends SapphireTest { $this->assertEquals("Prop", $player->Position); } + /** + * Check that the queries generated for many-many relation queries can have unlimitedRowCount + * called on them. + */ + function testManyManyUnlimitedRowCount() { + $player = $this->objFromFixture('DataObjectTest_Player', 'player2'); + $query = $player->getManyManyComponentsQuery('Teams'); + $this->assertEquals(2, $query->unlimitedRowCount()); + } + /** * Tests that singular_name() generates sensible defaults. */