Ticket Details

Take advantage of datasource specific features with consistent Model and Record api

RFC Ticket (closed)

MongoDB and CouchDB returns result more complex than just the asked for result set,  specifically it returns the total number of records in the database. Taking advantage of this, and other such features should be possible. 

An example that work, but are inconsistent with generic `Model` and `Record` behaviour, add a total method to `Document` that access the _handle adapters of `CouchDB` and `MongoDB` to retrieve the count:

{{{
diff --git a/libraries/lithium/data/model/Document.php b/libraries/lithium/data/model/Document.php
index fa799dc..cc6e985 100644
--- a/libraries/lithium/data/model/Document.php
+++ b/libraries/lithium/data/model/Document.php
@@ -296,6 +296,16 @@ class Document extends \lithium\util\Collection {
        public function data($field = null) {
                return $this->to('array');
        }
+
+       /**
+        * Asks the handle to return total number of records
+        *
+        * @return int
+        */
+       public function total() {
+               if (!$this->_handle || !$this->_result) return null;
+               return $this->_handle->total($this->_result, $this);
+       }

        protected function _isComplexType($data) {
                if (is_scalar($data) || !$data) {
diff --git a/libraries/lithium/data/source/http/adapter/CouchDb.php b/libraries/lithium/data/source/http/adapter/CouchDb
index 1ff3cba..bb873f7 100644
--- a/libraries/lithium/data/source/http/adapter/CouchDb.php
+++ b/libraries/lithium/data/source/http/adapter/CouchDb.php
@@ -307,6 +307,13 @@ class CouchDb extends \lithium\data\source\Http {
                return $result;
        }

+       public function total($resource, $context) {
+               if (!is_object($resource)) {
+                       return null;
+               }
+               return $resource->total_rows;
+       }
+
        /**
         * handle conditions
         *
}}}

Another alternative, is that the count is returned by the 'describe()' function of Couch but the current adapter returns an empty fake data array.

on 12.04.09 reported by: alkemann owned by: jperras

Updates

(fixed) on 05.06.10 by jperras
Implemented in [83057cb7bc767c87bc0533c26ddf1f2eb4250e63] for CouchDb adapter.

Generally speaking, the `Document::stats()` or `RecordSet::stats()` method are the preferred methods for obtaining metadata about the returned result sets.