public function getSelect()
{
// Close off any open query elements.
$this->_endQuery();
$Sql = !$this->_Distinct ? 'select ' : 'select distinct ';
// Don't escape the field if it is numeric or an asterisk (all columns)
$Selects = array();
foreach ($this->_Selects as $Key => $Expr) {
$Field = $Expr['Field'];
$Function = $Expr['Function'];
$Alias = $Expr['Alias'];
$CaseOptions = val('CaseOptions', $Expr);
if ($Field != '*' && !is_numeric($Field)) {
$Field = $this->escapeIdentifier($Field);
}
if ($Alias == '' && $Function != '') {
$Alias = $Field;
}
// if (in_array(strtolower($Function), array('max', 'min', 'avg', 'sum', 'count')))
if ($Function != '') {
if (strpos($Function, '%s') !== false) {
$Field = sprintf($Function, $Field);
} else {
$Field = $Function . '(' . $Field . ')';
}
}
if ($CaseOptions !== false) {
$Field = 'case ' . $Field . $CaseOptions . ' end';
}
if ($Alias != '') {
$Field .= ' as ' . $this->quoteIdentifier($Alias);
}
if ($Field != '') {
$Selects[] = $Field;
}
}
$Sql .= count($Selects) == 0 ? '*' : implode(', ', $Selects);
if (count($this->_Froms) > 0) {
$Sql .= "\nfrom " . $this->_fromTables($this->_Froms);
}
if (count($this->_Joins) > 0) {
$Sql .= "\n";
$Sql .= implode("\n", $this->_Joins);
}
if (count($this->_Wheres) > 0) {
$Sql .= "\nwhere ";
}
$Sql .= implode("\n", $this->_Wheres);
// Close any where groups that were left open.
for ($i = 0; $i < $this->_OpenWhereGroupCount; ++$i) {
$Sql .= ')';
}
$this->_OpenWhereGroupCount = 0;
if (count($this->_GroupBys) > 0) {
$Sql .= "\ngroup by ";
// special consideration for table aliases
if (count($this->_AliasMap) > 0 && $this->Database->DatabasePrefix) {
$Sql .= implode(', ', $this->_filterTableAliases($this->_GroupBys));
} else {
$Sql .= implode(', ', $this->_GroupBys);
}
}
if (count($this->_Havings) > 0) {
$Sql .= "\nhaving " . implode("\n", $this->_Havings);
}
if (count($this->_OrderBys) > 0) {
$Sql .= "\norder by " . implode(', ', $this->_OrderBys);
}
if (is_numeric($this->_Limit)) {
$Sql .= "\n";
$Sql = $this->getLimit($Sql, $this->_Limit, $this->_Offset);
}
return $Sql;
}