private function _getNumberRecords($db, $sql)
    {
        $has_subquery = false;
        if (preg_match("/\(\s*?SELECT\s*?.+\)/si", $sql)) {
            $has_subquery = true;
        }
        if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is', $sql)) {
            // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
            $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $sql);
            $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _TABLE_ALIAS_";
        } elseif ($has_subquery == false) {
            // now replace SELECT ... FROM with SELECT COUNT(*) FROM
            $rewritesql = preg_replace('/\s*?SELECT\s.*?\s+FROM\s/is', 'SELECT COUNT(*) FROM ', $sql);
            // Because count(*) and 'order by' fails with mssql, access and postgresql.
            // Also a good speedup optimization - skips sorting!
            $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $rewritesql);
        } else {
            $rewritesql = $sql;
        }

        try {
            if ($this->cacheLifeTime > 0) {
                $cache_id = md5($this->objectName . $rewritesql . serialize($bindValues));
                //try to process cache service.
                $cacheSvc = Openbizx::getService(CACHE_SERVICE);
                $cacheSvc->init($this->objectName, $this->cacheLifeTime);
                if ($cacheSvc->test($cache_id)) {
                    //Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", ". Query Sql = ".$rewritesql);
                    $resultArray = $cacheSvc->load($cache_id);
                } else {
                    Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Query Sql = " . $rewritesql);
                    $result = $db->query($rewritesql);
                    $resultArray = $result->fetch();
                    $cacheSvc->save($resultArray, $cache_id);
                }
            } else {
                Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Query Sql = " . $rewritesql);
                $resultSet = $db->query($rewritesql);
                $resultArray = $resultSet->fetch();
            }
        } catch (Exception $e) {
            Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: " . $e->getMessage());
            $this->errorMessage = $this->getMessage("DATA_ERROR_QUERY") . ": Rewrite:" . $rewritesql . ". Raw:" . $sql . ". " . $e->getMessage();
            throw new \Openbizx\Data\Exception($this->errorMessage);
            return 0;
        }

        if ($has_subquery) {
            $record_count = (int) $resultSet->rowCount();
        } else {
            $record_count = (int) $resultArray[0];
        }
        return (string) $record_count;
    }