Execute the provided queries
@param $queryProvider
@param $buildDepth
@param $orderby
@param Info $pagingInfo
@return Array of PersistentObject instances
972415
public static function execute(UnionQueryProvider $queryProvider, $buildDepth=BuildDepth::SINGLE, $orderby=null, PagingInfo $pagingInfo=null) {
    $cache = ObjectFactory::getInstance('dynamicCache');
    $cacheSection = str_replace('\\', '.', __CLASS__);

    $queryIds = $queryProvider->getIds();
    $numQueries = sizeof($queryIds);

    // get cache key for stored offsets of previous page
    $pagingInfo = $pagingInfo ?: new PagingInfo(PagingInfo::SIZE_INFINITE);
    $page = $pagingInfo->getPage();
    $prevPage = $page > 1 ? $page-1 : 1;
    $prevPagingInfo = new PagingInfo($pagingInfo->getPageSize(), true);
    $prevPagingInfo->setPage($prevPage);
    $prevCacheKey = self::getCacheKey($queryIds, $buildDepth, $orderby, $prevPagingInfo);

    // get offsets
    if ($page == 1) {
      $offsets = array_fill(0, $numQueries, 0);
    }
    else {
      if ($cache->exists($cacheSection, $prevCacheKey)) {
        $offsets = $cache->get($cacheSection, $prevCacheKey);
      }
      else {
        // previous offsets must be generated by loading the pages for pages other than first
        for ($i=1; $i<$page; $i++) {
          $tmpPagingInfo = new PagingInfo($pagingInfo->getPageSize(), true);
          $tmpPagingInfo->setPage($i);
          $tmpCacheKey = self::getCacheKey($queryIds, $buildDepth, $orderby, $tmpPagingInfo);
          if (!$cache->exists($cacheSection, $tmpCacheKey)) {
            self::execute($queryProvider, $buildDepth, $orderby, $tmpPagingInfo);
          }
          $offsets = $cache->get($cacheSection, $tmpCacheKey);
        }
      }
    }

    $tmpResult = [];
    $total = 0;
    for ($i=0, $countI=$numQueries; $i<$countI; $i++) {
      // collect n objects from each query
      $queryId = $queryIds[$i];

      // set paging info
      $tmpPagingInfo = new PagingInfo($pagingInfo->getPageSize(), false);
      $tmpPagingInfo->setOffset($offsets[$i]);

      $objects = $queryProvider->execute($queryId, $buildDepth, $orderby, $tmpPagingInfo);
      foreach ($objects as $object) {
        $object->setProperty('queryId', $queryId);
      }
      $tmpResult = array_merge($tmpResult, $objects);
      $total += $tmpPagingInfo->getTotalCount();
    }
    $pagingInfo->setTotalCount($total);

    // sort
    if ($orderby != null) {
      $comparator = new ObjectComparator($orderby);
      usort($tmpResult, [$comparator, 'compare']);
    }

    // truncate
    $result = array_slice($tmpResult, 0, $pagingInfo->getPageSize());

    // update offsets
    $counts = array_fill_keys($queryIds, 0);
    for ($i=0, $count=sizeof($result); $i<$count; $i++) {
      $counts[$result[$i]->getProperty('queryId')]++;
    }
    for ($i=0, $count=$numQueries; $i<$count; $i++) {
      $offsets[$i] += $counts[$queryIds[$i]];
    }
    $cacheKey = self::getCacheKey($queryIds, $buildDepth, $orderby, $pagingInfo);
    $cache->put($cacheSection, $cacheKey, $offsets);
    return $result;
  }
236821
protected function addOrderBy(QueryBuilder $queryBuilder, $alias, array $sortBy = [])
    {
        foreach ($sortBy as $field => $order) {
            // if no relation is defined add alias by default
            if (false === strpos($field, '.')) {
                $field = $alias . '.' . $field;
            }

            $queryBuilder->addOrderBy($field, $order);
        }
    }
462797
public function buildQueryBuilder()
    {
        $builder = new QueryBuilder();

        foreach ($this->parsers as $parser) {
            if ($parser->wasApplied()) {
                $parser->apply($builder);
            }
        }

        foreach ($this->sorts as $sort) {
            $builder->orderBy($sort[0], $sort[1]);
        }

        if (!empty($this->perPage)) {
            $builder->setPageSize($this->perPage);
        }

        if (!empty($this->page)) {
            $builder->setPage($this->page);
        }

        if (!empty($this->searchQuery)) {
            $builder->setSearchQuery($this->searchQuery);
        }

        return $builder;
    }
1006919
private function getSearchQueryOrderBy($query, $orderBy)
	{
		foreach ($orderBy as $key => $value) {
			$query->orderBy($key, $value);
		}

		return $query;
	}
274680
private void orderResults(ResultSet cqlRows) throws InvalidRequestException
    {
        if (cqlRows.size() == 0 || !needsPostQueryOrdering())
            return;

        assert orderingIndexes != null;

        List<Integer> idToSort = new ArrayList<Integer>();
        List<Comparator<ByteBuffer>> sorters = new ArrayList<Comparator<ByteBuffer>>();

        for (ColumnIdentifier.Raw identifier : parameters.orderings.keySet())
        {
            ColumnDefinition orderingColumn = cfm.getColumnDefinition(identifier.prepare(cfm));
            idToSort.add(orderingIndexes.get(orderingColumn.name));
            sorters.add(orderingColumn.type);
        }

        Comparator<List<ByteBuffer>> comparator = idToSort.size() == 1
                                                ? new SingleColumnComparator(idToSort.get(0), sorters.get(0))
                                                : new CompositeComparator(sorters, idToSort);
        Collections.sort(cqlRows.rows, comparator);
    }
476111
private Result buildResult(Filter<S> filter, OrderingList<S> ordering, QueryHints hints)
        throws SupportException, RepositoryException
    {
        List<IndexedQueryAnalyzer<S>.Result> subResults;
        if (filter == null) {
            subResults = Collections
                .singletonList(mIndexAnalyzer.analyze(filter, ordering, hints));
        } else {
            subResults = splitIntoSubResults(filter, ordering, hints);
        }

        if (subResults.size() <= 1) {
            // Total ordering not required.
            return new Result(subResults);
        }

        // If any orderings have an unspecified direction, switch to ASCENDING
        // or DESCENDING, depending on which is more popular. Then build new
        // sub-results.
        for (int pos = 0; pos < ordering.size(); pos++) {
            OrderedProperty<S> op = ordering.get(pos);
            if (op.getDirection() != Direction.UNSPECIFIED) {
                continue;
            }

            // Find out which direction is most popular for this property.
            Tally tally = new Tally(op.getChainedProperty());
            for (IndexedQueryAnalyzer<S>.Result result : subResults) {
                tally.increment(findHandledDirection(result, op));
            }

            ordering = ordering.replace(pos, op.direction(tally.getBestDirection()));

            // Re-calc with specified direction. Only do one property at a time
            // since one simple change might alter the query plan.
            subResults = splitIntoSubResults(filter, ordering, hints);

            if (subResults.size() <= 1) {
                // Total ordering no longer required.
                return new Result(subResults);
            }
        }

        // Gather all the keys available. As ordering properties touch key
        // properties, they are removed from all key sets. When a key set size
        // reaches zero, total ordering has been achieved.
        List<Set<ChainedProperty<S>>> keys = getKeys();

        // Check if current ordering is total.
        for (OrderedProperty<S> op : ordering) {
            ChainedProperty<S> property = op.getChainedProperty();
            if (pruneKeys(keys, property)) {
                // Found a key which is fully covered, indicating total ordering.
                return new Result(subResults, ordering);
            }
        }

        // Create a super key which contains all the properties required for
        // total ordering. The goal here is to append these properties to the
        // ordering in a fashion that takes advantage of each index's natural
        // ordering. This in turn should cause any sort operation to operate
        // over smaller groups. Smaller groups means smaller sort buffers.
        // Smaller sort buffers makes a merge sort happy.

        // Super key could be stored simply in a set, but a map makes it
        // convenient for tracking tallies.
        Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>();
        for (Set<ChainedProperty<S>> key : keys) {
            for (ChainedProperty<S> property : key) {
                if (!superKey.containsKey(property)) {
                    superKey.put(property, new Tally(property));
                }
            }
        }

        // Keep looping until total ordering achieved.
        while (true) {
            // For each ordering score, iterate over the entire unused ordering
            // properties and select the next free property. If property is in
            // the super key increment a tally associated with property
            // direction. Choose the property with the best tally and augment
            // the orderings with it and create new sub-results. Remove the
            // property from the super key and the key set. If any key is now
            // fully covered, a total ordering has been achieved.

            for (IndexedQueryAnalyzer<S>.Result result : subResults) {
                OrderingScore<S> score = result.getCompositeScore().getOrderingScore();

                OrderingList<S> unused = score.getUnusedOrdering();
                if (unused.size() > 0) {
                    for (OrderedProperty<S> prop : unused) {
                        ChainedProperty<S> chainedProp = prop.getChainedProperty();
                        Tally tally = superKey.get(chainedProp);
                        if (tally != null) {
                            tally.increment(prop.getDirection());
                        }
                    }
                }

                OrderingList<S> free = score.getFreeOrdering();
                if (free.size() > 0) {
                    OrderedProperty<S> prop = free.get(0);
                    ChainedProperty<S> chainedProp = prop.getChainedProperty();
                    Tally tally = superKey.get(chainedProp);
                    if (tally != null) {
                        tally.increment(prop.getDirection());
                    }
                }
            }

            Tally best = bestTally(superKey.values());
            ChainedProperty<S> bestProperty = best.getProperty();

            // Now augment the orderings and create new sub-results.
            ordering = ordering.concat(OrderedProperty.get(bestProperty, best.getBestDirection()));
            subResults = splitIntoSubResults(filter, ordering, hints);

            if (subResults.size() <= 1) {
                // Total ordering no longer required.
                break;
            }

            // Remove property from super key and key set...
            superKey.remove(bestProperty);
            if (superKey.size() == 0) {
                break;
            }
            if (pruneKeys(keys, bestProperty)) {
                break;
            }

            // Clear the tallies for the next run.
            for (Tally tally : superKey.values()) {
                tally.clear();
            }
        }

        return new Result(subResults, ordering);
    }
301271
public static void applyOrderBy(MultivaluedMap<String, String> queryParams, Query query) {
        List<String> orders = queryParams.get(SORT_PARAM_NAME);
        if (orders != null && orders.size() > 0) {
            OrderBy orderBy = query.orderBy();
            for (String order : orders) {
                EbeanUtils.appendOrder(orderBy, order);
            }
        }
    }
650877
private function getQueryBuilderForCachingHash($queryBuilder)
    {
        return [
            $queryBuilder->getQuery()->getSQL(),
            array_map([$this, 'parameterToArray'], $queryBuilder->getParameters()->toArray()),
        ];
    }
1234977
public function fetchResources(QueryBuilder $builder, string $modelClass): PaginatedDataInterface
    {
        $data = $this->fetchPaginatedResourcesWithoutRelationships($builder, $modelClass);

        if ($this->hasIncludes() === true) {
            $this->loadRelationships($data);
            $this->clearFetchParameters();
        }

        return $data;
    }
418250
protected <T> CompletableFuture<ResultSet> executeQuery(final EntityInfo<T> info, final AsyncConnection conn, final String sql) {
        final byte[] bytes = conn.getAttribute(CONN_ATTR_BYTESBAME);
        final ByteBufferWriter writer = ByteBufferWriter.create(bufferPool);
        {
            writer.put((byte) 'Q');
            int start = writer.position();
            writer.putInt(0);
            writeUTF8String(writer, sql);
            writer.putInt(start, writer.position() - start);
        }
        final ByteBuffer[] buffers = writer.toBuffers();
        final CompletableFuture<ResultSet> future = new CompletableFuture();
        conn.write(buffers, buffers, new CompletionHandler<Integer, ByteBuffer[]>() {
            @Override
            public void completed(Integer result, ByteBuffer[] attachment1) {
                if (result < 0) {
                    failed(new SQLException("Write Buffer Error"), attachment1);
                    return;
                }
                int index = -1;
                for (int i = 0; i < attachment1.length; i++) {
                    if (attachment1[i].hasRemaining()) {
                        index = i;
                        break;
                    }
                    bufferPool.accept(attachment1[i]);
                }
                if (index == 0) {
                    conn.write(attachment1, attachment1, this);
                    return;
                } else if (index > 0) {
                    ByteBuffer[] newattachs = new ByteBuffer[attachment1.length - index];
                    System.arraycopy(attachment1, index, newattachs, 0, newattachs.length);
                    conn.write(newattachs, newattachs, this);
                    return;
                }
                final PgResultSet resultSet = new PgResultSet();
                final List<ByteBuffer> readBuffs = new ArrayList<>();
                conn.read(new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment2) {
                        if (result < 0) {
                            failed(new SQLException("Read Buffer Error"), attachment2);
                            return;
                        }
                        if (result == 8192 || !attachment2.hasRemaining()) { //postgresql数据包上限为8192 还有数据
                            attachment2.flip();
                            readBuffs.add(attachment2);
                            conn.read(this);
                            return;
                        }
                        attachment2.flip();
                        readBuffs.add(attachment2);
                        final ByteBufferReader buffer = ByteBufferReader.create(readBuffs);
                        boolean endok = false;
                        boolean futureover = false;
                        while (buffer.hasRemaining()) {
                            final char cmd = (char) buffer.get();
                            int length = buffer.getInt();
                            switch (cmd) {
                                case 'E':
                                    byte[] field = new byte[255];
                                    String level = null,
                                     code = null,
                                     message = null;
                                    for (byte type = buffer.get(); type != 0; type = buffer.get()) {
                                        String value = readUTF8String(buffer, field);
                                        if (type == (byte) 'S') {
                                            level = value;
                                        } else if (type == 'C') {
                                            code = value;
                                        } else if (type == 'M') {
                                            message = value;
                                        }
                                    }
                                    future.completeExceptionally(new SQLException(message, code, 0));
                                    futureover = true;
                                    break;
                                case 'T':
                                    RowDesc rowDesc = new RespRowDescDecoder().read(buffer, length, bytes);
                                    resultSet.setRowDesc(rowDesc);
                                    break;
                                case 'D':
                                    RowData rowData = new RespRowDataDecoder().read(buffer, length, bytes);
                                    resultSet.addRowData(rowData);
                                    futureover = true;
                                    break;
                                case 'Z':
                                    //buffer.position(buffer.position() + length - 4);
                                    buffer.skip(length - 4);
                                    endok = true;
                                    break;
                                default:
                                    //buffer.position(buffer.position() + length - 4);
                                    buffer.skip(length - 4);
                                    break;
                            }
                        }
                        for (ByteBuffer buf : readBuffs) {
                            bufferPool.accept(buf);
                        }
                        if (!futureover) future.completeExceptionally(new SQLException("SQL(" + sql + ") executeQuery error"));
                        if (endok) {
                            readPool.offerConnection(conn);
                            future.complete(resultSet);
                        } else {
                            conn.dispose();
                        }
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment2) {
                        //不用bufferPool.accept
                        future.completeExceptionally(exc);
                        conn.dispose();
                    }
                });
            }

            @Override
            public void failed(Throwable exc, ByteBuffer[] attachment1) {
                for (ByteBuffer attach : attachment1) {
                    bufferPool.accept(attach);
                }
                future.completeExceptionally(exc);
            }
        });
        return future;
    }
826357
protected function getPaginator4QueryBuilder(QueryBuilder $queryBuilder, int $count, int $page = 1): ?Paginator
    {
        if (!$queryBuilder) {
            return null;
        }

        $paginator = new Paginator(
            new DoctrineAdapter\SimpleQueryDoctrine($count, $queryBuilder->getQuery())
        );
        $paginator->setDefaultItemCountPerPage(25);
        $paginator->setCurrentPageNumber($page);

        return $paginator;
    }
1145472
public function buildWithSubQuery(VictoireQueryInterface $containerEntity, QueryBuilder $itemsQueryBuilder, EntityManager $em)
    {
        //get the query of the container entity
        $query = $containerEntity->getQuery();
        if (method_exists($containerEntity, 'additionnalQueryPart')) {
            $query = $containerEntity->additionnalQueryPart();
        }

        if ($query !== '' && $query !== null) {
            $subQuery = $em->createQueryBuilder()
                                ->select('item.id')
                                ->from($itemsQueryBuilder->getRootEntities()[0], 'item');

            $itemsQueryBuilder->andWhere(
                sprintf('main_item.id IN (%s %s)', $subQuery->getQuery()->getDql(), $query)
            );
        }

        //Add ORDER BY if set
        if ($orderBy = json_decode($containerEntity->getOrderBy(), true)) {
            foreach ($orderBy as $addOrderBy) {
                $reflectionClass = new \ReflectionClass($itemsQueryBuilder->getRootEntities()[0]);
                $reflectionProperty = $reflectionClass->getProperty($addOrderBy['by']);

                //If ordering field is an association, treat it as a boolean
                if ($this->isAssociationField($reflectionProperty)) {
                    $itemsQueryBuilder->addSelect('CASE WHEN main_item.'.$addOrderBy['by'].' IS NULL THEN 0 ELSE 1 END AS HIDDEN caseOrder');
                    $itemsQueryBuilder->addOrderBy('caseOrder', $addOrderBy['order']);
                } else {
                    $itemsQueryBuilder->addOrderBy('main_item.'.$addOrderBy['by'], $addOrderBy['order']);
                }
            }
        }

        $currentView = $this->currentView;

        // If the current page is a BEP, we parse all its properties and inject them as query parameters
        if ($currentView() && $currentView() instanceof BusinessPage && null !== $currentEntity = $currentView()->getBusinessEntity()) {

            // NEW
            $metadatas = $em->getClassMetadata(get_class($currentEntity));
            foreach ($metadatas->fieldMappings as $fieldName => $field) {
                if (strpos($query, ':'.$fieldName) !== false) {
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName));
                }
            }
            foreach ($metadatas->associationMappings as $fieldName => $field) {
                if (strpos($query, ':'.$fieldName) !== false) {
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName)->getId());
                }
            }

            if (strpos($query, ':currentEntity') !== false) {
                $itemsQueryBuilder->setParameter('currentEntity', $currentEntity->getId());
            }
        } elseif ($currentView() instanceof BusinessTemplate && strpos($query, ':currentEntity') !== false) {
            $itemsQueryBuilder->setParameter('currentEntity', $containerEntity->getEntity()->getId());
        }

        if (strpos($query, ':currentUser') !== false && is_object($this->getCurrentUser())) {
            $itemsQueryBuilder->setParameter('currentUser', $this->getCurrentUser()->getId());
        }

        return $itemsQueryBuilder;
    }
1135269
public void setQueryParamsBuilds(QueryParamsBuilder queryParamsBuilder) {
		PreconditionUtil.assertNotNull("A query params builder must be provided, but is null", queryParamsBuilder);
		this.queryParamsBuilder = queryParamsBuilder;
		this.querySpecDeserializer = null;
	}
615418
protected function createQueryWithFilter(
        PaginateFinderConfiguration $configuration,
        array $siteIds,
        $order = array()
    ) {
        $qa = $this->createAggregationQueryBuilderWithSiteIds($siteIds);
        $filters = $this->getFilterSearch($configuration);
        if (!empty($filters)) {
            $qa->match($filters);
        }

        if (!empty($order)) {
            $qa->sort($order);
        }

        return $qa;
    }
807488
protected function buildQueryBuilder(array $criteria, array $orderBy, $collection = false)
    {
        $queryBuilder = $collection ? $this->createQueryBuilderForCollection() : $this->createQueryBuilder();

        $this->applyCriteria($queryBuilder, $criteria);
        $this->applySorting($queryBuilder, $orderBy);

        return $queryBuilder;
    }
980809
public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,
			int resultFlags, ObjectCache objectCache) throws SQLException {
		prepareQueryForAll();
		return buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags);
	}
467259
public function createQuery($managerName, Request $request, array $criteria = [], array $orderBy = [], $strictMode = true)
	{
		$this->lastManagerName = $managerName;
		$config = $this->getManagerConfig($managerName);
		$options = [
				'twig_extension_enabled' 	=> $this->container->getParameter('oka_pagination.twig.enable_extension'),
				'strict_mode' 				=> $strictMode
		];
		
		$sortConfig = $config['request']['sort'];
		$queryMapConfig = $config['request']['query_map'];
		
		// Extract pagination data in request
		$page = RequestParser::extractPageInRequest($request, $queryMapConfig['page'], 1);
		$config['item_per_page'] = RequestParser::extractItemPerPageInRequest($request, $queryMapConfig['item_per_page'], $config['item_per_page']);
		$filters = RequestParser::extractFiltersInRequest($request, $queryMapConfig['filters']);
		
		// Parse pagination request query for sort
		$sortAttributes = RequestParser::parseQueryToArray($request, $queryMapConfig['sort'], $sortConfig['delimiter']);
		$descAttributes = RequestParser::parseQueryToArray($request, $queryMapConfig['desc'], $sortConfig['delimiter']);
		
		foreach ($sortAttributes as $key => $attribute) {
			if (!in_array($attribute, $sortConfig['attributes_availables'])) {
				if (true === $strictMode) {
					throw new SortAttributeNotAvailableException($attribute, sprintf('Invalid request sort attribute "%s" not avalaible.', $attribute));
				}
				continue;
			}
			
			$sortAttributes[$attribute] = in_array($attribute, $descAttributes) ? 'DESC' : 'ASC';
			unset($sortAttributes[$key]);
		}
		
		$criteria = empty($filters) ? $criteria : array_merge($criteria, $filters);
		$orderBy = empty($sortAttributes) ? $orderBy : array_merge($orderBy, $sortAttributes);
		
		if (isset($config['model_manager_name']) && isset($config['db_driver'])) {
			/** @var \Doctrine\Bundle\DoctrineBundle\Registry $registry */
			$registry = $this->container->get(BundleExtension::$doctrineDrivers[$config['db_driver']]['registry']);
			$objectManager = $registry->getManager($config['model_manager_name']);
		} else {
			$objectManager = $this->container->get('oka_pagination.default.object_manager');
		}
		
		$query = new PaginationQuery($objectManager, $this->qbHandler, null, $managerName, $options, $config, $page, $criteria, $orderBy);
		$query->addQueryPart('select', RequestParser::parseQueryToArray($request, 'fields', ',', []));
		$query->addQueryPart('distinct', (boolean) RequestParser::getRequestParameterValue($request, 'distinct', true));
		
		if (true === $options['twig_extension_enabled']) {
			$query->setTwig($this->container->get('twig'));
		}
		
		return $query;
	}