diff --git a/library/Icinga/Data/Db/Query.php b/library/Icinga/Data/Db/Query.php index efec71b35..1d0facd0a 100644 --- a/library/Icinga/Data/Db/Query.php +++ b/library/Icinga/Data/Db/Query.php @@ -32,6 +32,12 @@ class Query extends AbstractQuery */ protected $countColumns; + protected $uglySlowConservativeCount = false; + + protected $countCache; + + protected $maxCount; + protected function init() { $this->db = $this->ds->getConnection()->getDb(); @@ -60,7 +66,6 @@ class Query extends AbstractQuery protected function createQueryObjects() { - $this->beforeCreatingCountQuery(); $this->beforeCreatingSelectQuery(); $this->selectQuery = clone($this->baseQuery); $this->selectQuery->columns($this->columns); @@ -74,11 +79,28 @@ class Query extends AbstractQuery } } - $this->countQuery = clone($this->baseQuery); - if ($this->countColumns === null) { - $this->countColumns = array('cnt' => 'COUNT(*)'); + $this->beforeCreatingCountQuery(); + if ($this->uglySlowConservativeCount) { + $query = clone($this->selectQuery); + if ($this->maxCount === null) { + $this->countQuery = $this->db->select()->from( + $query, + 'COUNT(*)' + ); + } else { + $this->countQuery = $this->db->select()->from( + $query->reset('order')->limit($this->maxCount), + 'COUNT(*)' + ); + } + } else { + $this->countQuery = clone($this->baseQuery); + if ($this->countColumns === null) { + $this->countColumns = array('cnt' => 'COUNT(*)'); + } + $this->countQuery->columns($this->countColumns); } - $this->countQuery->columns($this->countColumns); + } protected function beforeCreatingCountQuery() @@ -91,7 +113,10 @@ class Query extends AbstractQuery public function count() { - return $this->db->fetchOne($this->getCountQuery()); + if ($this->countCache === null) { + $this->countCache = $this->db->fetchOne($this->getCountQuery()); + } + return $this->countCache; } public function fetchAll()