Recursive method to get a QueryBuilder.

@param _queryPart the _query part
@return the query bldr
@throws EFapsException on error
175843
private static QueryBuilder getQueryBldr(final IQueryPart _queryPart)
        throws EFapsException
    {
        final Iterator<String> typeIter = ((AbstractQueryPart) _queryPart).getTypes().iterator();
        String typeStr = typeIter.next();
        final QueryBuilder ret = new QueryBuilder(UUIDUtil.isUUID(typeStr) ? Type.get(UUID.fromString(typeStr))
                        : Type.get(typeStr));
        while (typeIter.hasNext()) {
            typeStr = typeIter.next();
            ret.addType(UUIDUtil.isUUID(typeStr) ? Type.get(UUID.fromString(typeStr)) : Type.get(typeStr));
        }
        for (final AbstractWhere where : ((AbstractQueryPart) _queryPart).getWheres()) {
            if (where instanceof AttributeWhere) {
                final AttributeWhere attrWhere = (AttributeWhere) where;
                switch (where.getComparison()) {
                    case IN:
                    case EQUAL:
                        ret.addWhereAttrEqValue(attrWhere.getAttribute(), attrWhere.getValues().toArray());
                        break;
                    case GREATER:
                        ret.addWhereAttrGreaterValue(attrWhere.getAttribute(), attrWhere.getValues().get(0));
                        break;
                    case LESS:
                        ret.addWhereAttrLessValue(attrWhere.getAttribute(), attrWhere.getValues().get(0));
                        break;
                    case LIKE:
                        ret.addWhereAttrMatchValue(attrWhere.getAttribute(), attrWhere.getValues().get(0));
                        break;
                    case UNEQUAL:
                    case NOTIN:
                        ret.addWhereAttrNotEqValue(attrWhere.getAttribute(), attrWhere.getValues().toArray());
                        break;
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            } else if (where instanceof SelectWhere) {
                final SelectWhere selWhere = (SelectWhere) where;
                switch (where.getComparison()) {
                    case EQUAL:
                        ret.addWhereSelectEqValue(selWhere.getSelect(), selWhere.getValues().toArray());
                        break;
                    case GREATER:
                        ret.addWhereSelectGreaterValue(selWhere.getSelect(), selWhere.getValues().get(0));
                        break;
                    case LESS:
                        ret.addWhereSelectLessValue(selWhere.getSelect(), selWhere.getValues().get(0));
                        break;
                    case LIKE:
                        ret.addWhereSelectMatchValue(selWhere.getSelect(), selWhere.getValues().get(0));
                        break;
                    case UNEQUAL:
                    case IN:
                    case NOTIN:
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            } else if (where instanceof AttrQueryWhere) {
                final AttrQueryWhere attrQueryWhere = (AttrQueryWhere) where;
                switch (where.getComparison()) {
                    case IN:
                        ret.addWhereAttrInQuery(attrQueryWhere.getAttribute(),
                                        getQueryBldr(attrQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) attrQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case NOTIN:
                        ret.addWhereAttrNotInQuery(attrQueryWhere.getAttribute(),
                                        getQueryBldr(attrQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) attrQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case EQUAL:
                    case GREATER:
                    case LESS:
                    case LIKE:
                    case UNEQUAL:
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            } else if (where instanceof SelectQueryWhere) {
                final SelectQueryWhere selQueryWhere = (SelectQueryWhere) where;
                switch (where.getComparison()) {
                    case IN:
                        ret.addWhereAttrInQuery(selQueryWhere.getSelect(),
                                        getQueryBldr(selQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) selQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case NOTIN:
                        ret.addWhereAttrNotInQuery(selQueryWhere.getSelect(),
                                        getQueryBldr(selQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) selQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case EQUAL:
                    case GREATER:
                    case LESS:
                    case LIKE:
                    case UNEQUAL:
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            }
        }
        if (_queryPart instanceof AbstractQueryStmtPart) {
            ret.setLimit(((AbstractQueryStmtPart) _queryPart).getLimit());
        }
        return ret;
    }
999594
private function processQueryPart($part)
    {
        $queryPart = (string) $part;

        if (is_object($part) && $part instanceof self && $part->count() > 1) {
            return $this->preSeparator . $queryPart . $this->postSeparator;
        }

        // Fixes DDC-1237: User may have added a where item containing nested expression (with "OR" or "AND")
        if (stripos($queryPart, ' OR ') !== false || stripos($queryPart, ' AND ') !== false) {
            return $this->preSeparator . $queryPart . $this->postSeparator;
        }

        return $queryPart;
    }
19234
private function executeQuery(QueryPartition $partition)
    {
        return $this->execute($partition->sql(), [
            'partitionToken' => $partition->token()
        ] + $partition->options());
    }
271954
private function buildQuery(
        QueryBuilder $queryBuilder,
        FullyQualifiedClassName $section,
        array $fetchFields
    ): QueryBuilder {

        // 1: Get the entities that belong to the fields we want to query
        $this->buildReflections($section, $fetchFields);
        reset($this->reflections);
        $start = $this->reflections[key($this->reflections)];

        // 2: Make select properties
        $this->makeSelectProperties($start);

        // 3: Make joins
        $this->makeJoins($start);

        // 4: And bring it all together in the query builder
        $queryBuilder->addSelect($this->selectProperties);
        $queryBuilder->from($start['reflection']->getName(), $start['propertyName']);
        array_multisort($this->joins);
        foreach ($this->joins as $join=>$order) {
            $joinOn = explode(' ', $join);
            $queryBuilder->leftJoin($joinOn[0], $joinOn[1]);
        }

        return $queryBuilder;
    }
279591
public function requestRepresentableQueryItem(): QueryItem {
		$selectBuilder  = $this->queryState->getPdo()->getMetaData()->createSelectStatementBuilder();
		$this->queryModel->apply($selectBuilder);
		
		return $selectBuilder->toQueryResult();
	}
773187
public function getQuery()
    {
        $idField = $this->documentKey;

        if ($idField == null) {
            throw new QueryException('id should not be null');
        }

        $this->setQuery(sprintf('id:%s', $idField));

        return parent::getQuery();
    }
30740
private function getLoadTypeQueryBuilder(): QueryBuilder
    {
        $q = $this->connection->createQueryBuilder();
        $expr = $q->expr();
        $q
            ->select([
                'c.id AS ezcontentclass_id',
                'c.version AS ezcontentclass_version',
                'c.serialized_name_list AS ezcontentclass_serialized_name_list',
                'c.serialized_description_list AS ezcontentclass_serialized_description_list',
                'c.identifier AS ezcontentclass_identifier',
                'c.created AS ezcontentclass_created',
                'c.modified AS ezcontentclass_modified',
                'c.modifier_id AS ezcontentclass_modifier_id',
                'c.creator_id AS ezcontentclass_creator_id',
                'c.remote_id AS ezcontentclass_remote_id',
                'c.url_alias_name AS ezcontentclass_url_alias_name',
                'c.contentobject_name AS ezcontentclass_contentobject_name',
                'c.is_container AS ezcontentclass_is_container',
                'c.initial_language_id AS ezcontentclass_initial_language_id',
                'c.always_available AS ezcontentclass_always_available',
                'c.sort_field AS ezcontentclass_sort_field',
                'c.sort_order AS ezcontentclass_sort_order',
                'c.language_mask AS ezcontentclass_language_mask',

                'a.id AS ezcontentclass_attribute_id',
                'a.serialized_name_list AS ezcontentclass_attribute_serialized_name_list',
                'a.serialized_description_list AS ezcontentclass_attribute_serialized_description_list',
                'a.identifier AS ezcontentclass_attribute_identifier',
                'a.category AS ezcontentclass_attribute_category',
                'a.data_type_string AS ezcontentclass_attribute_data_type_string',
                'a.can_translate AS ezcontentclass_attribute_can_translate',
                'a.is_required AS ezcontentclass_attribute_is_required',
                'a.is_information_collector AS ezcontentclass_attribute_is_information_collector',
                'a.is_searchable AS ezcontentclass_attribute_is_searchable',
                'a.placement AS ezcontentclass_attribute_placement',
                'a.data_float1 AS ezcontentclass_attribute_data_float1',
                'a.data_float2 AS ezcontentclass_attribute_data_float2',
                'a.data_float3 AS ezcontentclass_attribute_data_float3',
                'a.data_float4 AS ezcontentclass_attribute_data_float4',
                'a.data_int1 AS ezcontentclass_attribute_data_int1',
                'a.data_int2 AS ezcontentclass_attribute_data_int2',
                'a.data_int3 AS ezcontentclass_attribute_data_int3',
                'a.data_int4 AS ezcontentclass_attribute_data_int4',
                'a.data_text1 AS ezcontentclass_attribute_data_text1',
                'a.data_text2 AS ezcontentclass_attribute_data_text2',
                'a.data_text3 AS ezcontentclass_attribute_data_text3',
                'a.data_text4 AS ezcontentclass_attribute_data_text4',
                'a.data_text5 AS ezcontentclass_attribute_data_text5',
                'a.serialized_data_text AS ezcontentclass_attribute_serialized_data_text',

                'g.group_id AS ezcontentclass_classgroup_group_id',

                'ml.name AS ezcontentclass_attribute_multilingual_name',
                'ml.description AS ezcontentclass_attribute_multilingual_description',
                'ml.language_id AS ezcontentclass_attribute_multilingual_language_id',
                'ml.data_text AS ezcontentclass_attribute_multilingual_data_text',
                'ml.data_json AS ezcontentclass_attribute_multilingual_data_json',
            ])
            ->from('ezcontentclass', 'c')
            ->leftJoin(
                'c',
                'ezcontentclass_attribute',
                'a',
                $expr->andX(
                    $expr->eq('c.id', 'a.contentclass_id'),
                    $expr->eq('c.version', 'a.version')
                )
            )
            ->leftJoin(
                'c',
                'ezcontentclass_classgroup',
                'g',
                $expr->andX(
                    $expr->eq('c.id', 'g.contentclass_id'),
                    $expr->eq('c.version', 'g.contentclass_version')
                )
            )
            ->leftJoin(
                'a',
                'ezcontentclass_attribute_ml',
                'ml',
                $expr->andX(
                    $expr->eq('a.id', 'ml.contentclass_attribute_id'),
                    $expr->eq('a.version', 'ml.version')
                )
            )
            ->orderBy('a.placement');

        return $q;
    }
1039488
private function _getReducedDQLQueryPart($queryPartName, $options = array())
    {
        $queryPart = $this->getDQLPart($queryPartName);

        if (empty($queryPart)) {
            return (isset($options['empty']) ? $options['empty'] : '');
        }

        return (isset($options['pre']) ? $options['pre'] : '')
             . (is_array($queryPart) ? implode($options['separator'], $queryPart) : $queryPart)
             . (isset($options['post']) ? $options['post'] : '');
    }
1186050
public static List<IndexDefinition> get()
        throws EFapsException
    {
        final List<IndexDefinition> ret = new ArrayList<>();

        final QueryBuilder queryBldr = new QueryBuilder(CIAdminIndex.IndexDefinition);
        final MultiPrintQuery multi = queryBldr.getPrint();
        final SelectBuilder selUUID = SelectBuilder.get().linkto(CIAdminIndex.IndexDefinition.TypeLink)
                        .attribute(CIAdminDataModel.Type.UUID);
        multi.addSelect(selUUID);
        multi.execute();
        while (multi.next()) {
            final UUID uuidTmp = UUID.fromString(multi.getSelect(selUUID));
            final Set<Type> types = getChildTypes(Type.get(uuidTmp));
            for (final Type type : types) {
                final IndexDefinition indexDef = IndexDefinition.get(type.getUUID());
                if (!type.isAbstract()) {
                    ret.add(indexDef);
                }
            }
        }
        return ret;
    }
578597
protected function getOneOrNullResultFromQueryBuilder(QueryBuilder $queryBuilder)
    {
        $query = $queryBuilder->getQuery();

        $result = $query->getOneOrNullResult();

        return $result;
    }
855380
private function getQueryBuilderWithNewAliases(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $originAlias = 'o', string $replacement = 'o_2'): QueryBuilder
    {
        $queryBuilderClone = clone $queryBuilder;

        $joinParts = $queryBuilder->getDQLPart('join');
        $wherePart = $queryBuilder->getDQLPart('where');

        //reset parts
        $queryBuilderClone->resetDQLPart('join');
        $queryBuilderClone->resetDQLPart('where');
        $queryBuilderClone->resetDQLPart('orderBy');
        $queryBuilderClone->resetDQLPart('groupBy');
        $queryBuilderClone->resetDQLPart('having');

        //Change from alias
        $from = $queryBuilderClone->getDQLPart('from')[0];
        $queryBuilderClone->resetDQLPart('from');
        $queryBuilderClone->from($from->getFrom(), $replacement);

        $aliases = ["$originAlias."];
        $replacements = ["$replacement."];

        //Change join aliases
        foreach ($joinParts[$originAlias] as $joinPart) {
            /** @var Join $joinPart */
            $joinString = str_replace($aliases, $replacements, $joinPart->getJoin());
            $pos = strpos($joinString, '.');
            if (false === $pos) {
                if (null !== $joinPart->getCondition() && null !== $this->resourceClassResolver && $this->resourceClassResolver->isResourceClass($joinString)) {
                    $newAlias = $queryNameGenerator->generateJoinAlias($joinPart->getAlias());
                    $aliases[] = "{$joinPart->getAlias()}.";
                    $replacements[] = "$newAlias.";
                    $condition = str_replace($aliases, $replacements, $joinPart->getCondition());
                    $join = new Join($joinPart->getJoinType(), $joinPart->getJoin(), $newAlias, $joinPart->getConditionType(), $condition);
                    $queryBuilderClone->add('join', [$replacement => $join], true);
                }

                continue;
            }
            $alias = substr($joinString, 0, $pos);
            $association = substr($joinString, $pos + 1);
            $condition = str_replace($aliases, $replacements, $joinPart->getCondition());
            $newAlias = QueryBuilderHelper::addJoinOnce($queryBuilderClone, $queryNameGenerator, $alias, $association, $joinPart->getJoinType(), $joinPart->getConditionType(), $condition, $originAlias);
            $aliases[] = "{$joinPart->getAlias()}.";
            $replacements[] = "$newAlias.";
        }

        $queryBuilderClone->add('where', str_replace($aliases, $replacements, (string) $wherePart));

        return $queryBuilderClone;
    }
475553
public function getQuery()
    {
        if (count($this->parts['select']) === 0) {
            throw new QueryException('Missing "select" parts to generate query.');
        }

        $sql = 'SELECT ';

        if ($this->distinct) {
            $sql .= 'DISTINCT ';
        }

        $sql .= implode(', ', $this->parts['select']) . ' FROM';

        if (count($this->parts['from']) === 0) {
            throw new QueryException('Missing "from" parts to generate query.');
        }

        $renderedFromBefore = false;

        foreach ($this->parts['from'] as $fromPart) {
            if ($fromPart['type'] === 'FROM') {
                if ($renderedFromBefore === true) {
                    $sql .= ',';
                }

                $sql .= ' ' . $fromPart['table'];
                $renderedFromBefore = true;
            } else {
                $sql .= ' ' . $fromPart['type'] . ' JOIN ' . $fromPart['table'];

                if ($fromPart['condition']) {
                    $sql .= ' ON ' . $fromPart['condition'];
                }
            }
        }

        if (count($this->parts['where']) > 0) {
            $sql .= ' WHERE ' . implode(' AND ', $this->parts['where']);
        }

        if (count($this->parts['groupBy']) > 0) {
            $sql .= ' GROUP BY ' . implode(', ', $this->parts['groupBy']);
        }

        if (count($this->parts['having']) > 0) {
            $sql .= ' HAVING ' . implode(' AND ', $this->parts['having']);
        }

        if (count($this->parts['orderBy']) > 0) {
            $sql .= ' ORDER BY ' . implode(', ', $this->parts['orderBy']);
        }

        if ($this->limit || $this->offset) {
            $sql = $this->connection->getDatabasePlatform()->modifyLimitQuery(
                $sql,
                $this->limit,
                $this->offset
            );
        }

        return $sql;
    }
1056889
private MultiPrintQuery getMultiPrint()
        throws EFapsException
    {
        final MultiPrintQuery ret;
        if (getInstances().isEmpty()) {
            ret = new MultiPrintQuery(QueryBldrUtil.getInstances(this));
        } else {
            final List<Instance> instances = new ArrayList<>();
            for (final String oid : getInstances()) {
                instances.add(Instance.get(oid));
            }
            ret = new MultiPrintQuery(instances);
        }
        return ret;
    }
701288
public function getQuery(
        QueryBuilder $queryBuilder,
        FullyQualifiedClassName $section,
        array $fetchFields
    ): QueryBuilder {
        return $this->buildQuery($queryBuilder, $section, $fetchFields);
    }
1339723
public function useFiltersFromTypoScript(): QueryBuilder
    {
        $filters = Filters::fromTypoScriptConfiguration($this->typoScriptConfiguration);
        $this->queryToBuild->setFilterQueries($filters->getValues());

        $this->useFilterArray($this->getAdditionalFilters());

        $searchQueryFilters = $this->typoScriptConfiguration->getSearchQueryFilterConfiguration();

        if (!is_array($searchQueryFilters) || count($searchQueryFilters) <= 0) {
            return $this;
        }

        // special filter to limit search to specific page tree branches
        if (array_key_exists('__pageSections', $searchQueryFilters)) {
            $pageIds = GeneralUtility::trimExplode(',', $searchQueryFilters['__pageSections']);
            $this->usePageSectionsFromPageIds($pageIds);
            $this->typoScriptConfiguration->removeSearchQueryFilterForPageSections();
        }

        return $this;
    }
120215
public function findQueryBuilderForClass($class, array $method = [], $queryResult = null) {
        $em = $this->getDoctrine()->getManager();
        $alias = "c";
        $qb = $em->createQueryBuilder()
                ->select($alias)
                ->from($class, $alias);
        foreach ($method as $key => $value) {
            $qb
                    ->andWhere(sprintf("%s.%s = :%s", $alias, $key, $key))
                    ->setParameter($key, $value)
            ;
        }
        if ($queryResult == "OneOrNull") {
            return $qb->getQuery()->getOneOrNullResult();
        } else {
            return $qb->getQuery()->getResult();
        }
    }
1314723
protected void prepareQuery()
        throws EFapsException
    {
        this.sqlTable2Index.put(getBaseType().getMainTable(), 0);
        if (getBaseType().getMainTable() == null) {
            throw new EFapsException(AbstractObjectQuery.class, "BaseType", getBaseType());
        }
        if (getBaseType().getMainTable().getSqlColType() != null) {
            final QEqual eqPart = new QEqual(new QAttribute(getBaseType().getTypeAttribute()),
                                           new QNumberValue(getBaseType().getId()));
            if (this.includeChildTypes && !getBaseType().getChildTypes().isEmpty()) {
                for (final Type type : getBaseType().getChildTypes()) {
                    eqPart.addValue(new QNumberValue(type.getId()));
                }
            }
            if (this.where == null) {
                this.where = new QWhereSection(eqPart);
            } else {
                this.where.setPart(new QAnd(this.where.getPart(), eqPart));
            }
        }
        if (getBaseType().isCompanyDependent()) {
            final QEqual eqPart = new QEqual(new QAttribute(getBaseType().getCompanyAttribute()));
            if (this.isCompanyDependent()) {
                if (Context.getThreadContext().getCompany() == null) {
                    throw new EFapsException(InstanceQuery.class, "noCompany");
                }
                if (getBaseType().getCompanyAttribute().getAttributeType().getClassRepr().equals(
                                ConsortiumLinkType.class)) {
                    for (final Long consortium : Context.getThreadContext().getCompany().getConsortiums()) {
                        eqPart.addValue(new QNumberValue(consortium));
                    }
                } else {
                    eqPart.addValue(new QNumberValue(Context.getThreadContext().getCompany().getId()));
                }
            } else {
                for (final Long compId : Context.getThreadContext().getPerson().getCompanies()) {
                    if (getBaseType().getCompanyAttribute().getAttributeType().getClassRepr().equals(
                                    ConsortiumLinkType.class)) {
                        for (final Long consortium : Company.get(compId).getConsortiums()) {
                            eqPart.addValue(new QNumberValue(consortium));
                        }
                    } else {
                        eqPart.addValue(new QNumberValue(compId));
                    }
                }
            }
            // only add if an actual filter was set. A background process might not use Companies at all.
            if (CollectionUtils.isNotEmpty(eqPart.getValues())) {
                if (this.where == null) {
                    this.where = new QWhereSection(eqPart);
                } else {
                    this.where.setPart(new QAnd(this.where.getPart(), eqPart));
                }
            }
        }
        if (this.where != null) {
            this.where.prepare(this);
        }
        if (this.orderBy != null) {
            this.orderBy.prepare(this);
        }

        if (this.limit != null) {
            this.limit.prepare(this);
        }
    }