/** * Prepara uma SQL para efetuar uma consutla (SELECT) * * <code> * $total = $obj->count(); * $total_distinct = $obj->count('distinct nome'); * </code> * @param boolean $forCount Define sera uma consulta para contagem ou nao * @param string $what String contendo logica para contagem * @author Hugo Ferreira da Silva * @link http://www.hufersil.com.br/lumine * @return int Numero de registros encontrados */ protected function _prepareSQL($forCount = false, $what = '*') { $sql = "SELECT "; if ($forCount == false) { if (empty($this->_data)) { reset($this->_join_list); foreach ($this->_join_list as $ent) { $this->selectAs($ent); } } $sql .= Lumine_Parser::parseSQLValues($this, implode(', ', $this->_data)); } if ($forCount == true && !empty($what)) { $sql .= ' count(' . Lumine_Parser::parseSQLValues($this, $what) . ') as "lumine_count" '; } $sql .= PHP_EOL . " FROM "; $list = array(); reset($this->_from); foreach ($this->_from as $obj) { $list[] = Lumine_Parser::parseFromValue($obj); } $sql .= implode(', ', $list); if (count($this->_join_list) > 1) { $sql .= Lumine_Parser::parseJoinValues($this, $this->_join_list); } $where = $this->_makeWhereFromFields(); if (!empty($this->_where)) { reset($this->_where); // para cada condicao em where foreach ($this->_where as $i => $item) { // tiramos espacos em branco $item = trim($item); // se iniciar com OR ou AND if (preg_match('@^\\b(or|and)\\b@i', $item)) { // somente adicionamos na clausula $where .= ' ' . $item; // do contrario } else { // o padrao eh AND $where .= empty($where) ? $item : ' AND ' . $item; } $where .= PHP_EOL . "\t"; } } if (!empty($where)) { $sql .= PHP_EOL . " WHERE " . Lumine_Parser::parseSQLValues($this, $where); } if (!empty($this->_group)) { $sql .= PHP_EOL . " GROUP BY " . Lumine_Parser::parseSQLValues($this, implode(', ', $this->_group)); } if (!empty($this->_having)) { $sql .= PHP_EOL . " HAVING " . Lumine_Parser::parseSQLValues($this, implode(' AND ', $this->_having)); } if (!empty($this->_order)) { $sql .= PHP_EOL . " ORDER BY " . Lumine_Parser::parseSQLValues($this, implode(', ', $this->_order)); } $sql .= PHP_EOL . $this->_getConnection()->setLimit($this->_offset, $this->_limit); return $sql; }