Compile the SELECT statement for fetching the number of objects.

@throws UnexpectedValueException If the source does not have a table defined.
@return string
777647
public function sqlLoadCount()
    {
        if (!$this->hasTable()) {
            throw new UnexpectedValueException(
                'Can not get SQL count. No table defined.'
            );
        }

        $tables  = $this->sqlFrom();
        $filters = $this->sqlFilters();

        $query = 'SELECT COUNT(*) FROM '.$tables.$filters;
        return $query;
    }
775981
public function compileSelect()
    {

        // Compile "Select From"
        if (sizeof($this->query->getQuerySelect()) == 0) {
            $this->queryString = 'SELECT * ';

            return;
        }

        foreach ($this->query->getQuerySelect() as $key => $value) {
            if ($value instanceof Raw) {
                $value = $value->getString();
            }

            if ($key == 0) {
                $selectString = "$value";
            } else {
                $selectString .= ",$value";
            }
        }

        $this->queryString = "SELECT $selectString";
    }
625323
protected function buildSelect()
    {
        if (empty($this->sqlParts['select'])) {
            $this->sqlParts['select'] = ['*'];
        }

        $builder = $this->getLookupBuilder();
        $columns = [];
        foreach ($this->sqlParts['select'] as $alias => $column) {
            if ($column instanceof Aggregation) {
                $columns[$alias] = $this->buildSelectFromAggregation($column);
            } elseif (is_string($column)) {
                if (false !== strpos($column, 'SELECT')) {
                    $columns[$alias] = $column;
                } else {
                    $columns[$alias] = $this->addColumnAlias($builder->fetchColumnName($column));
                }
            } else {
                $columns[$alias] = $column;
            }
        }

        $selectSql = $this->sqlParts['distinct'] ? 'SELECT DISTINCT ' : 'SELECT ';
        if (empty($columns)) {
            return $selectSql.'*';
        }

        if (false === is_array($columns)) {
            $columns = [$columns];
        }

        $select = [];
        foreach ($columns as $column => $subQuery) {
            if ($subQuery instanceof ToSqlInterface) {
                $subQuery = $subQuery->toSQL();
            } else {
                $subQuery = $this->getAdapter()->quoteSql($subQuery);
            }

            if (is_numeric($column)) {
                $column = $subQuery;
                $subQuery = '';
            }

            if (!empty($subQuery)) {
                if (false !== strpos($subQuery, 'SELECT')) {
                    $value = $this->columnAs(
                        '('.$subQuery.')',
                        $this->getQuotedName($column)
                    );
                } else {
                    $value = $this->columnAs(
                        $this->getQuotedName($subQuery),
                        $this->getQuotedName($column)
                    );
                }
            } else {
                $value = $this->normalizeColumns($column);
            }
            $select[] = $value;
        }

        return $selectSql.implode(', ', $select);
    }
939193
public function count() {
        $sql    = $this->getSQL();
        $values = $this->values;
        if ($sql) {
            try {
                $statement = $this->dialect->prepare($sql);
                foreach ($values as $value) {
                    list ($name, $val, $type) = $value;
                    if (!$statement->bindValue($name, $val, $type)) {
                        $this->errorSQL    = $sql;
                        $this->errorValues = $values->__toString();
                        $this->error       = 'can not bind the value ' . $val . '[' . $type . '] to the argument:' . $name;

                        return false;
                    }
                }
                $rst = $statement->execute();
                $cnt = false;
                if ($rst) {
                    $cnt = $statement->rowCount();
                } else {
                    $this->dumpSQL($statement);
                }
                if ($statement) {
                    $statement->closeCursor();
                    $statement = null;
                }
                QueryBuilder::addSqlCount();

                return $cnt;
            } catch (\PDOException $e) {
                $this->exception   = $e;
                $this->error       = $e->getMessage();
                $this->errorSQL    = $sql;
                $this->errorValues = $values->__toString();

                return false;
            }
        } else {
            $this->error       = 'Can not generate the delete SQL';
            $this->errorSQL    = '';
            $this->errorValues = $values->__toString();
        }

        return false;
    }
467368
private function getPreparedSelect()
    {
        if (is_null($this->preparedSelect)) {
            $this->preparedSelect = $this->getServer()
                ->select()
                ->select($this->valueColumnName)
                ->from($this->tableName)
                ->where('AND')
                ->expr($this->keyColumnName, '=', ':id')
                ->begin('OR')
                ->expr($this->expireColumnName, '=', ':zero')
                ->expr($this->expireColumnName, '>', ':expire')
                ->end();
        }

        return $this->preparedSelect;
    }
51912
protected function buildSelect()
    {
        $selects = [];
        foreach ($this->select as $select) {
            $shouldBeQuoted = true;

            // Check our list of nonQuoteStrings to see if we should quote or not.
            foreach ($this->nonQuoteStrings as $nonQuoteString) {
                if (strpos(strtolower($select), $nonQuoteString) !== false) {
                    $shouldBeQuoted = false;
                    break;
                }
            }

            if ($shouldBeQuoted) {
                $selects[] = $this->getQuotedTableName() . '.' . $this->quoteIdentifier($select);
            } else {
                $selects[] = $select;
            }
        }
        return 'SELECT ' . implode(', ', $selects);
    }
203650
protected function byPredicate()
    {
        $fields = $this->fieldIdentifiers();
        if (empty($fields)) {
            throw new UnexpectedValueException(
                'Property is required.'
            );
        }

        $conditions = [];
        $value      = $this->value();
        $operator   = $this->operator();
        $function   = $this->func();
        foreach ($fields as $fieldName) {
            if ($function !== null) {
                $target = sprintf('%1$s(%2$s)', $function, $fieldName);
            } else {
                $target = $fieldName;
            }

            switch ($operator) {
                case 'FIND_IN_SET':
                    if ($value === null) {
                        throw new UnexpectedValueException(sprintf(
                            'Value is required on field "%s" for "%s"',
                            $target,
                            $operator
                        ));
                    }

                    if (is_array($value)) {
                        $value = implode(',', $value);
                    }

                    $conditions[] = sprintf('%2$s(\'%3$s\', %1$s)', $target, $operator, $value);
                    break;

                case '!':
                case 'NOT':
                    $conditions[] = sprintf('%2$s %1$s', $target, $operator);
                    break;

                case 'IS NULL':
                case 'IS TRUE':
                case 'IS FALSE':
                case 'IS UNKNOWN':
                case 'IS NOT NULL':
                case 'IS NOT TRUE':
                case 'IS NOT FALSE':
                case 'IS NOT UNKNOWN':
                    $conditions[] = sprintf('%1$s %2$s', $target, $operator);
                    break;

                case 'IN':
                case 'NOT IN':
                    if ($value === null) {
                        throw new UnexpectedValueException(sprintf(
                            'Value is required on field "%s" for "%s"',
                            $target,
                            $operator
                        ));
                    }

                    if (is_array($value)) {
                        $value = implode('\',\'', $value);
                    }

                    $conditions[] = sprintf('%1$s %2$s (\'%3$s\')', $target, $operator, $value);
                    break;

                default:
                    if ($value === null) {
                        throw new UnexpectedValueException(sprintf(
                            'Value is required on field "%s" for "%s"',
                            $target,
                            $operator
                        ));
                    }

                    $conditions[] = sprintf('%1$s %2$s \'%3$s\'', $target, $operator, $value);
                    break;
            }
        }

        return $this->compileConditions($conditions, 'OR');
    }
752590
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 = ArrayValue('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;
   }
376212
public function compile()
    {
        // check for the bare minimum
        if ($this->table === false || $this->type === false) {
            throw (new \Exception('Query compilation failure: missing table or type'));
        }
        switch ($this->type) {
            case 'UPDATE':
                return $this->generateUPDATEStatement();
            case 'INSERT':
                return $this->generateINSERTStatement();
            case 'DELETE':
                return $this->generateDELETEStatement();
            default:
                return $this->generateSELECTStatement();
        }
    }
944109
@Override
  public String buildQuery() {
    validateQuery();

    StringBuilder stringBuilder = new StringBuilder();
    if (!Strings.isNullOrEmpty(select)) {
      stringBuilder = stringBuilder.append(SELECT).append(" ").append(select).append(" ");
    }
    if (!Strings.isNullOrEmpty(from)) {
      stringBuilder = stringBuilder.append(FROM).append(" ").append(from).append(" ");
    }
    if (!Strings.isNullOrEmpty(where)) {
      stringBuilder = stringBuilder.append(WHERE).append(" ").append(where).append(" ");
    }
    if (!Strings.isNullOrEmpty(orderBy)) {
      stringBuilder = stringBuilder.append(ORDER_BY).append(" ").append(orderBy).append(" ");
    }
    if (limit != null) {
      stringBuilder = stringBuilder.append(LIMIT).append(" ").append(limit).append(" ");
    }
    if (offset != null) {
      stringBuilder = stringBuilder.append(OFFSET).append(" ").append(offset).append(" ");
    }
    return stringBuilder.toString().trim();
  }
584166
public function getSelectSql($for_max_object_count = false): string
    {
        // Select
        if ($this->getSelectFields()) {
            $select_sql = [];
            foreach ($this->getSelectFields() as $field_data) {
                // Simple select
                if ($field_data['type'] === 'simple') {
                    $select_sql[] = '`' . $field_data['table'] . '`.`' . $field_data['field'] . '`' . ($field_data['as'] ? ' AS `' . $field_data['as'] . '`' : '');
                } elseif ($field_data['type'] === 'string') {
                    $select_sql[] = $field_data['field'];
                } elseif ($field_data['type'] === TableStructure::FIELD_TYPE_TRANSLATION) {
                    $select_sql[] = '`' . $field_data['table'] . '`.`' . $field_data['field'] . '` AS `' . $field_data['as'] . '`';
                }
            }
            $select_sql = implode(', ', $select_sql);
        } else {
            $select_sql = '`' . $this->getDbTableName() . '`.*';
        }

        // Where
        $where_sql = $this->getWhereSql();
        $where_sql = $where_sql ? 'WHERE ' . $where_sql : '';

        // Having
        $having_sql = $this->getHavingSql();
        $having_sql = $having_sql ? 'HAVING ' . $having_sql : '';

        // Order by
        $order_by_sql = $this->getOrderBySQL();

        // Limit
        $limit_sql = $this->sql_limit ? 'LIMIT ' . $this->sql_offset . ', ' . $this->sql_limit : '';

        // Group by
        $group_sql = $this->getGroupBySql();

        // Joins
        $join_sql = $this->getJoinTablesSql();

        // Counting total
        if ($for_max_object_count) {
            $select_sql = 'COUNT(*)';
            $where_sql = '';
            $having_sql = '';
            $order_by_sql = '';
            $limit_sql = '';
        }

        $sql_calc_found_rows = $this->require_to_count_total_rows ? ' SQL_CALC_FOUND_ROWS ' : '';

        $sql = '
SELECT ' . $sql_calc_found_rows . $select_sql . '
FROM `' . $this->getDbTableName() . '`
' . $join_sql . '
' . $where_sql . '
' . $group_sql . '
' . $having_sql . '
' . $order_by_sql . '
' . $limit_sql . '
    ';

        return $sql;
    }
747657
public function selectOne()
    {
        $this->setLimit(1);

        $query = 'SELECT ' . $this->getQueryFields() . ' FROM ' . $this->getTable() . ' ' . $this->getQueryWhere() . ' ' . $this->getQueryOrderBy() . ' ' . $this->getQueryLimit();

        $statement = $this->db->prepare($query);
        $statement->execute($this->binds);

        $this->clear();

        if ($statement->rowCount() === 0) {
            throw new ExceptionNoData('No data for current query! (query: ' . $query . ', bind: ' . json_encode($this->binds) . ')', 10001);
        }

        //~ Create new object, set data & save it in cache
        return $this->newDataInstance($statement->fetchObject(), true);
    }
459631
public function form_select($params) {
        if (!isset($params['field'])) {
            throw new \UnexpectedValueException("The field parameter is required.");
        }
        $values = isset($params['values']) ? $params['values'] : null;
        $attributes = isset($params['attrs']) ? $params['attrs'] : array();
        $options = isset($params['options']) ? $params['options'] : array();
        return Form::select($params['field'], $values, $options, $attributes);
    }
528288
private function getPreparedMultiSelect()
    {
        if (is_null($this->preparedMultiSelect)) {
            $this->preparedMultiSelect = $this->getServer()
                ->select()
                ->select([$this->keyColumnName, $this->valueColumnName])
                ->from($this->tableName)
                ->where('AND')
                ->expr($this->keyColumnName, 'in', ':ids')
                ->begin('OR')
                ->expr($this->expireColumnName, '=', ':zero')
                ->expr($this->expireColumnName, '>', ':expire')
                ->end();
        }

        return $this->preparedMultiSelect;
    }
806140
public function getQuery(): Query
    {
    	// TODO: Bindings could be defined only locally in this method because it has to be regenerated on every call

        if (count($this->from) == 0) {
            throw new Exception('Can not build SELECT query, there is no FROM table defined');
        }

        $query = "SELECT\n";

        if (sizeof($this->fields) == 0) {
            $query .= "\t*";
        } else {
            foreach ($this->fields as $fld) {
                $field = $fld['name'];
                $as = $fld['as'];

                $query .= "\t{$field}";
                if ($as !== null) {
                    $query .= " as {$as}";
                }

                $query .= ",\n";
            }

            $query = substr($query, 0, -2);
        }

        $query .= "\nFROM";
        foreach ($this->from as $from) {
            if ($from['table'] instanceof static) {
                /* @var $subSelect \Koldy\Db\Query\Select */
                $subSelect = $from['table'];
                $subSql = $subSelect->__toString();
                $subSql = str_replace("\n", "\n\t", $subSql);
                $query .= " (\n\t{$subSql}\n) {$from['alias']}\n";

                $subSelectBindings = $subSelect->getBindings();
                if (!$subSelectBindings->isEmpty()) {
                    $this->getBindings()->addBindingsFromInstance($subSelectBindings);
                }
            } else {
                $query .= "\n\t{$from['table']}";
                if ($from['alias'] !== null) {
                    $query .= " as {$from['alias']},";
                } else {
                    $query .= ',';
                }
            }
        }
        $query = substr($query, 0, -1);

        foreach ($this->joins as $join) {
            $query .= "\n\t{$join['type']} {$join['table']} ON ";

            if (is_array($join['first'])) {
                foreach ($join['first'] as $joinArg) {
                    if ($joinArg instanceof Expr) {
                        $query .= "{$joinArg} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 2) {
                        $query .= "{$joinArg[0]} = {$joinArg[1]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 3) {
                        $query .= "{$joinArg[0]} {$joinArg[1]} {$joinArg[2]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 4) {
                        if (substr($query, -5) == ' AND ') {
                            $query = substr($query, 0, -5);
                        }

                        $query .= " {$joinArg[0]} {$joinArg[1]} {$joinArg[2]} {$joinArg[3]} AND ";

                    } else {
                        throw new Exception('Unknown JOIN argument');

                    }
                }

                $query = substr($query, 0, -5);
            } else {
                if ($join['operator'] === null) {
                    throw new Exception('Operator can\'t be null');
                }

                if ($join['second'] === null) {
                    throw new Exception('Second parameter can\'t be null');
                }

                $query .= "{$join['first']} {$join['operator']} {$join['second']}";
            }
        }

        if ($this->hasWhere()) {
            $query .= "\nWHERE\n\t" . trim($this->getWhereSql());
        }

        if (sizeof($this->groupBy) > 0) {
            $query .= "\nGROUP BY";
            foreach ($this->groupBy as $r) {
                $query .= " {$r['field']},";
            }
            $query = substr($query, 0, -1);
        }

        $sizeofHaving = count($this->having);
        if ($sizeofHaving > 0) {
            $query .= "\nHAVING";
            if ($sizeofHaving == 1) {
                $nl = ' ';
            } else {
                $nl = "\n\t";
            }

            foreach ($this->having as $index => $having) {
                $link = ($index > 0) ? "{$having['link']} " : '';
                if ($having['value'] instanceof Expr) {
                    $query .= "{$nl}{$link}{$having['field']} {$having['operator']} {$having['value']}";
                } else {
	                //$bindName = $this->bind($having['field'], $having['value'], 'h');
	                $bindName = $this->getBindings()->makeAndSet('h' . $having['field'], $having['value']);
	                $query .= "{$nl}{$link}{$having['field']} {$having['operator']} :{$bindName}";
                }
            }
        }

        if (sizeof($this->orderBy) > 0) {
            $query .= "\nORDER BY";
            foreach ($this->orderBy as $r) {
                $query .= "\n\t{$r['field']} {$r['direction']},";
            }
            $query = substr($query, 0, -1);
        }

        if ($this->limit !== null) {
            $query .= "\nLIMIT {$this->limit->howMuch} OFFSET {$this->limit->start}";
        }

        return new Query($query, $this->getBindings(), $this->getAdapterConnection());
    }
505661
public function getStatement()
    {
        return $this->_fixBlanks(
            trim(
                str_replace(
                    array(
                        '<fields>', '<joinFields>', '<tableName>',
                        '<joins>', '<where>', '<groupBy>',
                        '<orderBy>', '<limit>'
                    ),
                    array(
                        $this->getFields(),
                        $this->getJoinFields(),
                        $this->_sql->getTableName(),
                        $this->getJoins(), 
                        $this->getWhere(),
                        $this->getGroupBy(),
                        $this->getOrderBy(),
                        $this->getLimit()
                    ),
                    $this->_select
                )
            )
        );
    }
648371
public function fetch()
    {
        
        if ((null !== $this->statement) && $this->statement->fetch()) {
            $row = [];
            foreach ($this->stmt_results as $dbColumnName => $dbColumnValue) {
                $row[$this->stmt_cols[$dbColumnName]] = $dbColumnValue;
            }
            return $row;
        } elseif ($this->result instanceof \mysqli_result) {
            return mysqli_fetch_array($this->result, MYSQLI_ASSOC);
        } else {
            return null;
            
            if (!isset($this->result)) {
                throw new Exception('The database result resource is not currently set.');
            }
        }
    }