Build FACET {expr_list} [BY {expr_list}] [ORDER BY {expr | FACET()} {ASC | DESC}] [LIMIT [offset,] count].

@return string
768725
protected function buildFacetPart()
    {
        if (!$this->sqlParts['facet']) {
            return '';
        }

        $facetParts = array();
        foreach ($this->sqlParts['facet'] as $facet) {
            $facetExpressions = array();
            foreach ($facet['facet'] as $key => $facetExpr) {
                if (is_int($key)) {
                    $facetExpressions[] = $facetExpr;
                } else {
                    $facetExpressions[] = $key.' AS '.$facetExpr;
                }
            }
            $facetPart = 'FACET '.implode(', ', $facetExpressions);
            if ($facet['by']) {
                $facetPart .= ' BY '.$facet['by'];
            }
            if ($facet['order']) {
                $facetPart .= ' ORDER BY '.$facet['order'].$this->getDirection($facet['order'], $facet['direction']);
            }
            if ($facet['limit']) {
                $facetPart .= ' LIMIT '.(int) $facet['skip'].', '.(int) $facet['limit'];
            }

            $facetParts[] = $facetPart;
        }

        return ' '.implode(' ', $facetParts);
    }
283635
public function getIterator()
    {
        $header = $this->getHeader();

        while ($data = $this->getNextDataSet()) {
            $headerColumns = count($header);
            $dataColumns   = count($data);

            if ($headerColumns > $dataColumns && $this->appendRowsColumns) {
                $data = array_pad($data, $headerColumns, '');
                $this->malformedStatistic['appended']++;
            } elseif ($headerColumns < $dataColumns && $this->truncateRowsColumns) {
                $data = array_slice($data, 0, $headerColumns);
                $this->malformedStatistic['truncated']++;
            } elseif ($headerColumns != $dataColumns) {
                if ($this->ignoreMalformed) {
                    $this->malformedStatistic['malformed']++;
                    continue;
                }
                throw new Exception("Count mismatch in line {$this->getLineNumber()}, expected: {$headerColumns}, got: {$dataColumns}");
            }

            $set = array_combine($header, $data);
            yield $set;
        }
    }
790017
public function build($count = false)
    {
        $modelNameSpace = $this->model->getModelNameSpace();
        $mm = $this->getDI()->get('modelsManager');
        $query = $mm->createBuilder()->from($modelNameSpace);

        // $columns = $this->model->getAllowedColumns(true);
        $columns = array(
            "$modelNameSpace.*"
        );

        // process hasOne Joins
        $this->queryJoinHelper($query);
        $this->querySearchHelper($query);
        $this->querySortHelper($query);

        if ($count) {
            $query->columns('count(*) as count');
        } else {
            // preserve any columns added through joins
            $existingColumns = $query->getColumns();
            $allColumns = array_merge($columns, $existingColumns);
            $query->columns($allColumns);
        }
        // skip limit if returning a count
        if (!$count) {
            $this->queryLimitHelper($query);
        }

        // todo build fields feature into PHQL instead of doing in PHP
        return $query;
    }
455426
private function exprOperand() {
    switch ($this->currentType) {
      case T_STRING_VARNAME:
      case T_CLASS_C:
      case T_LNUMBER:
      case T_DNUMBER:
      case T_LINE:
      case T_FILE:
      case T_DIR:
      case T_TRAIT_C:
      case T_METHOD_C:
      case T_FUNC_C:
      case T_NS_C:
      case T_YIELD:
        return $this->mustMatchToken($this->currentType);
      case T_CONSTANT_ENCAPSED_STRING:
        return $this->arrayDeference($this->mustMatchToken(T_CONSTANT_ENCAPSED_STRING));
      case T_ARRAY:
        $node = new ArrayNode();
        $this->mustMatch(T_ARRAY, $node);
        $this->mustMatch('(', $node, 'openParen');
        $this->arrayPairList($node, ')');
        $this->mustMatch(')', $node, 'closeParen', TRUE);
        return $this->arrayDeference($node);
      case '[':
        $node = new ArrayNode();
        $this->mustMatch('[', $node);
        $this->arrayPairList($node, ']');
        $this->mustMatch(']', $node, NULL, TRUE);
        return $this->arrayDeference($node);
      case '(':
        $node = new ParenthesisNode();
        $this->mustMatch('(', $node, 'openParen');
        if ($this->currentType === T_NEW) {
          $node->addChild($this->newExpr(), 'expression');
          $this->mustMatch(')', $node, 'closeParen', TRUE);
          $node = $this->objectDereference($this->arrayDeference($node));
        }
        elseif ($this->currentType === T_YIELD) {
          $node->addChild($this->_yield());
          $this->mustMatch(')', $node, 'closeParen', TRUE);
        }
        else {
          $node->addChild($this->expr());
          $this->mustMatch(')', $node, 'closeParen', TRUE);
        }
        return $node;
      case T_START_HEREDOC:
        $node = new HeredocNode();
        $this->mustMatch(T_START_HEREDOC, $node);
        if ($this->tryMatch(T_END_HEREDOC, $node, NULL, TRUE)) {
          return $node;
        }
        else {
          $this->encapsList($node, T_END_HEREDOC, TRUE);
          $this->mustMatch(T_END_HEREDOC, $node, NULL, TRUE);
          return $node;
        }
      case '"':
        $node = new InterpolatedStringNode();
        $this->mustMatch('"', $node);
        $this->encapsList($node, '"');
        $this->mustMatch('"', $node);
        return $node;
      case T_STRING:
      case T_NS_SEPARATOR:
      case T_NAMESPACE:
        $namespace_path = $this->name();
        if ($this->currentType === T_DOUBLE_COLON) {
          return $this->exprClass($namespace_path);
        }
        elseif ($this->currentType === '(') {
          return $this->functionCall($namespace_path);
        }
        else {
          $constant_name = strtolower($namespace_path->getText());
          if ($constant_name === 'true') {
            $node = new TrueNode();
          }
          elseif ($constant_name === 'false') {
            $node = new FalseNode();
          }
          elseif ($constant_name === 'null') {
            $node = new NullNode();
          }
          else {
            $node = new ConstantNode();
          }
          $node->addChild($namespace_path, 'constantName');
          return $node;
        }
      case T_STATIC:
        $static = $this->mustMatchToken(T_STATIC);
        if ($this->currentType === T_FUNCTION) {
          return $this->anonymousFunction($static);
        } else {
          return $this->exprClass($static);
        }
      case '$':
      case T_VARIABLE:
        $operand = $this->indirectReference();
        if (!($operand instanceof VariableVariableNode) && $this->currentType === T_DOUBLE_COLON) {
          return $this->exprClass($operand);
        }
        elseif ($this->currentType === '(') {
          return $this->functionCall($operand, TRUE);
        }
        else {
          return $this->objectDereference($operand);
        }
      case T_ISSET:
        $node = new IssetNode();
        $this->mustMatch(T_ISSET, $node, 'name');
        $arguments = new CommaListNode();
        $this->mustMatch('(', $node, 'openParen');
        $node->addChild($arguments, 'arguments');
        do {
          $arguments->addChild($this->variable());
        } while ($this->tryMatch(',', $arguments));
        $this->mustMatch(')', $node, 'closeParen', TRUE);
        return $node;
      case T_EMPTY:
      case T_EVAL:
        if ($this->currentType === T_EMPTY) {
          $node = new EmptyNode();
        }
        else {
          $node = new EvalNode();
        }
        $this->mustMatch($this->currentType, $node, 'name');
        $arguments = new CommaListNode();
        $this->mustMatch('(', $node, 'openParen');
        $node->addChild($arguments, 'arguments');
        $arguments->addChild($this->expr());
        $this->mustMatch(')', $node, 'closeParen', TRUE);
        return $node;
      case T_INCLUDE:
      case T_REQUIRE:
      case T_INCLUDE_ONCE:
      case T_REQUIRE_ONCE:
        if ($this->currentType === T_INCLUDE) {
          $node = new IncludeNode();
        }
        elseif ($this->currentType === T_INCLUDE_ONCE) {
          $node = new IncludeOnceNode();
        }
        elseif ($this->currentType === T_REQUIRE) {
          $node = new RequireNode();
        }
        else {
          $node = new RequireOnceNode();
        }
        $this->mustMatch($this->currentType, $node);
        $node->addChild($this->expr(), 'expression');
        return $node;
      case T_NEW:
        return $this->newExpr();
      case T_LIST:
        return $this->_list();
      case T_EXIT:
        $node = new ExitNode();
        $this->mustMatch(T_EXIT, $node, NULL, TRUE);
        if ($this->currentType !== '(') {
          return $node;
        }
        $this->mustMatch('(', $node, 'openParen');
        if ($this->tryMatch(')', $node, 'closeParen', TRUE)) {
          return $node;
        }
        if ($this->currentType === T_YIELD) {
          $node->addChild($this->_yield(), 'expression');
        }
        else {
          $node->addChild($this->expr(), 'expression');
        }
        $this->mustMatch(')', $node, 'closeParen', TRUE);
        return $node;
      case T_FUNCTION:
        return $this->anonymousFunction();
      case '`':
        return $this->backtick();
    }
    throw new ParserException(
      $this->filename,
      $this->iterator->getLineNumber(),
      $this->iterator->getColumnNumber(),
      "excepted expression operand but got " . $this->current->getTypeName());
  }
40078
public function build()
    {
        /**
         * Query to be returned.
         *
         * @var string
         */
        $query = '';

        /**
         * Clauses which were built already.
         *
         * It is required to keep track of built clauses because some fields,
         * for example `join` is used by multiple clauses (`JOIN`, `LEFT JOIN`,
         * `LEFT OUTER JOIN`, etc.). The same happens for `VALUE` and `VALUES`.
         *
         * A clause is considered built just after fields' value
         * (`$this->field`) was used in building.
         *
         * @var array
         */
        $built = [];

        /**
         * Statement's clauses.
         *
         * @var array
         */
        $clauses = $this->getClauses();

        foreach ($clauses as $clause) {
            /**
             * The name of the clause.
             *
             * @var string
             */
            $name = $clause[0];

            /**
             * The type of the clause.
             *
             * @see self::$CLAUSES
             *
             * @var int
             */
            $type = $clause[1];

            /**
             * The builder (parser) of this clause.
             *
             * @var Component
             */
            $class = Parser::$KEYWORD_PARSERS[$name]['class'];

            /**
             * The name of the field that is used as source for the builder.
             * Same field is used to store the result of parsing.
             *
             * @var string
             */
            $field = Parser::$KEYWORD_PARSERS[$name]['field'];

            // The field is empty, there is nothing to be built.
            if (empty($this->$field)) {
                continue;
            }

            // Checking if this field was already built.
            if ($type & 1) {
                if (! empty($built[$field])) {
                    continue;
                }
                $built[$field] = true;
            }

            // Checking if the name of the clause should be added.
            if ($type & 2) {
                $query = trim($query) . ' ' . $name;
            }

            // Checking if the result of the builder should be added.
            if ($type & 1) {
                $query = trim($query) . ' ' . $class::build($this->$field);
            }
        }

        return $query;
    }
426768
public function expr() : Expr
    {
        $expr = new Expr($this->dm);
        $expr->setClassMetadata($this->class);

        return $expr;
    }
1123903
public function build(): string
    {
        $join = '';
        $filter = '';
        $order = '';
        $limit = '';
        
        // Biuld joins
        if ($this->join) {
            $tmp = [];
            
            foreach ($this->join as $def) {
                $tmp[] = ' ' . $def['by'] . ' JOIN ' . '{db_prefix}' . (isset($def['as']) ? $def['table'] . ' AS ' . $def['as'] : $def['join']) . ' ON (' . $def['cond'] . ')';
            }
        }
        
        $join = isset($tmp) ? implode(' ', $tmp) : '';
        
        // Add counter
        if ($this->counter) {
            
            $tmp = '(@' . $this->counter['name'] . ':=' . '@' . $this->counter['name'] . '+' . $this->counter['step'] . ') AS ' . $this->counter['as'];
            
            array_unshift($this->fields, $tmp);
        }
        
        $fieldlist = $this->buildFieldlist();
        
        // Create filterstatement
        $filter = $this->filter ? 'WHERE ' . $this->filter : '';
        
        // Create group by statement
        $group_by = '';
        
        if ($this->group_by) {
            
            if (is_array($this->group_by)) {
                $this->group_by = implode(', ', $this->group_by);
            }
            
            $group_by = 'GROUP BY ' . $this->group_by;
        }
        
        // Create having statement
        $having = $this->having ? 'HAVING ' . $this->having : '';
        
        // Create order statement
        $order = $this->order ? 'ORDER BY ' . $this->order : '';
        
        // Create limit statement
        if ($this->limit) {
            
            $limit = ' LIMIT ';
            
            if (isset($this->limit['lower'])) {
                $limit .= $this->limit['lower'];
            }
            
            if (isset($this->limit['lower']) && isset($this->limit['upper'])) {
                $limit .= ',' . $this->limit['upper'];
            }
        }
        
        // Get complete tablename with alias while respecting called mathod
        $table = $this->buildTableName();
        
        switch ($this->method) {
            
            case 'UPDATE':
                
                // we have to build our own fieldlist
                $fields = [];
                
                foreach ($this->fields as $field) {
                    $fields[] = $field . '=:' . $field;
                }
                
                $pieces = [
                    $this->method,
                    $table,
                    'SET',
                    implode(',', $fields),
                    $filter
                ];
                
                break;
            
            case 'INSERT':
            case 'REPLACE':
                
                // Build values
                $values = [];
                
                foreach ($this->fields as $field) {
                    $values[] = ':' . $field;
                }
                
                if (empty($values)) {
                    Throw new QueryBuilderException('No values for INSERT or REPLACE found.');
                }
                
                $pieces = [
                    $this->method . ' INTO',
                    $table,
                    empty($fieldlist) || $fieldlist == '*' ? '' : '(' . $fieldlist . ')',
                    'VALUES (' . implode(', ', $values) . ')'
                ];
                
                break;
            
            case 'DELETE':
                
                $pieces = [
                    $this->method,
                    'FROM ' . $table,
                    $filter,
                    $order,
                    $limit
                ];
                
                break;
            
            default:
                
                $pieces = [
                    $this->method,
                    $fieldlist,
                    'FROM ' . $table,
                    $join,
                    $filter,
                    $group_by,
                    $having,
                    $order,
                    $limit
                ];
                
                break;
        }
        
        array_walk_recursive($pieces, function (&$data, $index) {
            $data = trim($data);
        });
        
        // Build sql string from pieces
        $this->sql = trim(implode(' ', $pieces));
        
        // Finally cleanup parameters by removing parameter not needed in query and parse array parameter into sql
        // string.
        foreach ($this->params as $key => $val) {
            
            // Do cleanup
            if (strpos($this->sql, $key) === false) {
                unset($this->params[$key]);
                continue;
            }
            
            // Replace array parameter against sql valid part
            if (is_array($val)) {
                $prepared = $this->prepareArrayQuery($key, $val);
                
                array_push($this->params, $prepared['params']);
                
                $this->sql = str_replace('prep:' . $key, $prepared['sql'], $this->sql);
            }
        }
        
        return $this->sql;
    }
892566
protected function buildSetClause() {
		if (isset($this->expression))
			return $this->expression;
		
		$set = [];
		
		foreach (array_keys($this->value) as $k )
			$set[] = $k . '=#{' . $k . '}';
		
		return implode(',', $set);
	}
277743
public function AggregateExpression()
    {
        $lookaheadType = $this->lexer->lookahead['type'];
        $isDistinct    = false;

        if (! in_array($lookaheadType, [Lexer::T_COUNT, Lexer::T_AVG, Lexer::T_MAX, Lexer::T_MIN, Lexer::T_SUM], true)) {
            $this->syntaxError('One of: MAX, MIN, AVG, SUM, COUNT');
        }

        $this->match($lookaheadType);
        $functionName = $this->lexer->token['value'];
        $this->match(Lexer::T_OPEN_PARENTHESIS);

        if ($this->lexer->isNextToken(Lexer::T_DISTINCT)) {
            $this->match(Lexer::T_DISTINCT);
            $isDistinct = true;
        }

        $pathExp = $this->SimpleArithmeticExpression();

        $this->match(Lexer::T_CLOSE_PARENTHESIS);

        return new AST\AggregateExpression($functionName, $pathExp, $isDistinct);
    }
153770
public function toArray() : array
    {
        $facets = array();
        $count = $this->getFacetNormalCount();

        for ($i = 0; $i < $count; $i++) {
            $facets[] = $this->getFacetNormal($i)->toArray();
        }

        return array(
            "name" => $this->getSolidName(),
            "facets" => $facets
        );
    }
45206
public function getFacets()
    {
        if (isset($this->facets)) {
            return $this->facets;
        }

        return $this->facets = $this->getSearchResultWithLimitZero()->facets;
    }
1230311
function getIterator()
    {
        try {
            $c = $this->collection->find(
                [
                    'realm' => $this->getRealm(),
                ]
                , [
                    'projection' => ['key' => 1, 'value' => 1],
                    'typeMap'    => self::$typeMap
                 ]
            );

            foreach ($c as $d)
                yield $d['key'] => $this->getDataInterchange()->retrieveBackward( $d['value'] );

        } catch (\Exception $e) {
            throw new exReadError($e->getMessage(), $e->getCode(), $e);
        }
    }
362852
protected function buildOrderBy()
    {
        if (!$this->order_by) {
            return '';
        }

        if ($this->order_asc) {
            return ' ORDER BY' . $this->indentCsv($this->order_by) . ' ASC';
        } else {
            return ' ORDER BY' . $this->indentCsv($this->order_by) . ' DESC';
        }
    }
1256079
protected function buildSelect()
	{
		//define a container fields array
		$fields = array();

		//
		$where = $order = $limit = $join ="";

		//
		$template = "SELECT %s %s FROM %s %s %s %s %s";

		//loop through the fields
		foreach ($this->fields as $table => $tableFields) 
		{
			//loop through the fields checking for aliases
			foreach ($tableFields as $field => $alias) 
			{
				//if field is string, return field name
				if ( is_string($field) && $field != 'COUNT(1)')
				{
					//add to fields array
					$fields[] = "{$table}.{$field} AS {$alias}";

				}
				elseif (is_string($field) && $field == 'COUNT(1)') 
				{
					//add to fields array
					$fields[] = "{$field} AS {$alias}";

				}
				//not an array, return alias
				else
				{
					//get alias as field name
					$fields[] = "{$table}.{$alias}";

				}

			}

		}

		//turn the fields into a string
		$fields = join(", ", $fields);

		//get the query joins
		$queryJoin = $this->joins;

		//check if the join parameter is empty
		if ( ! empty($queryJoin) ) 
		{
			$joinTables = "(" . join(", ", $queryJoin['tables']) . ")";
			$joinConditions = "(" . join(" AND ", $queryJoin['conditions']) . ")";
			//add the joins
			$join = " LEFT JOIN $joinTables ON $joinConditions";

		}

		//get the where clause
		$queryWhere = $this->wheres;

		//check if the wheres clause is empty
		if ( ! empty($queryWhere) ) 
		{
			//append where clause
			$joined = join(" AND ", $queryWhere);

			//assign string to $where var
			$where = "WHERE {$joined}";

		}

		//get the order clause
		$queryOrder = $this->orders;

		//check if the orders clause is empty
		if ( ! empty($queryOrder) ) 
		{
			//get the direction if order
			$orderDirection = $this->directions;

			//assign string to order variable
			$order = "ORDER BY {$queryOrder} {$orderDirection}";

		}

		//get the limits clause
		$queryLimit = $this->limits;

		//check if the limits clause is empty
		if ( ! empty($queryLimit) ) 
		{
			//get the offset
			$limitOffset = $this->offset;

			//if offset has been defined
			if ( $limitOffset ) 
			{
				//get the limit string with offset
				$limit = "LIMIT {$limitOffset}, {$queryLimit}";

			}
			//limit offset undefined
			else
			{
				//get the limit string
				$limit = "LIMIT {$queryLimit}";

			}

		}

		//return the formated query string in the format of $template
		return sprintf($template, $this->distinct, $fields, $this->froms, $join, $where, $order, $limit);

	}
286140
private function bracesExpr() {
    $node = new NameExpressionNode();
    $this->mustMatch('{', $node);
    $node->addChild($this->expr());
    $this->mustMatch('}', $node, NULL, TRUE);
    return $node;
  }
1093240
public function getFacets() {
		if ($this->returnedFacets) {
			return $this->returnedFacets;
		}
		
		$result = $this->getResult();
		if (!isset($result->facet_counts)) {
			return;
		}

		if (isset($result->facet_counts->exception)) {
			// $this->logger->error($result->facet_counts->exception)
			return array();
		}
		
		$elems = $result->facet_counts->facet_fields;
		
		$facets = array();
		foreach ($elems as $field => $values) {
			$elemVals = array();
			foreach ($values as $vname => $vcount) {
				if ($vname == '_empty_') {
					continue;
				}
				$r = new stdClass;
				$r->Name = $vname;
				$r->Query = $vname;
				$r->Count = $vcount;
				$elemVals[] = $r;
			}
			$facets[$field] = $elemVals;
		}
		
		// see if there's any query facets for things too
		$query_elems = $result->facet_counts->facet_queries;
		if ($query_elems) {
			foreach ($query_elems as $vname => $count) {
				if ($vname == '_empty_') {
					continue;
				}
				
				list($field, $query) = explode(':', $vname);

				$r = new stdClass;
				$r->Type = 'query';
				$r->Name = $vname;
				$r->Query = $query;
				$r->Count = $count;
				
				$existing = isset($facets[$field]) ? $facets[$field] : array();
				$existing[] = $r;
				$facets[$field] = $existing;
			}
		}
		
		$this->returnedFacets = $facets;
		return $this->returnedFacets;
	}
1180283
protected function build()
    {
        $sql = $this->start . "\n"
            . ($this->from    ? $this->from . "\n"    : null)
            . ($this->join    ? $this->join           : null)
            . ($this->set     ? $this->set . "\n"     : null)
            . ($this->where   ? $this->where . "\n"   : null)
            . ($this->groupby ? $this->groupby . "\n" : null)
            . ($this->orderby ? $this->orderby . "\n" : null)
            . ($this->limit   ? $this->limit . "\n"   : null)
            . ($this->offset  ? $this->offset . "\n"  : null)
            . ";";

        return $sql;
    }