To debug, build the final SQL (can be approximate)

@param  QueryBuilder $queryBuilder

@return string
765938
public function getRawSQL(QueryBuilder $queryBuilder)
    {
        $sql = $queryBuilder->getSQL();
        foreach ($queryBuilder->getParameters() as $parameter => $value) {
            $sql = str_replace($parameter, "'$value'", $sql);
        }

        return $sql;
    }
1116927
protected function toSql($fields=null) : QueryBuilder
	{
		$queryBuilder = $this->queryBuilder()
		->select($fields)
		->from($this->table);

		$orderBy = [];

		if (isset(Model::$findOptions['asc'])) {
			$orderBy[] = Model::$findOptions['asc'] . ' ASC';
		}

		if (isset(Model::$findOptions['desc'])) {
			$orderBy[] = Model::$findOptions['desc'] . ' DESC';
		}

		if (!empty($orderBy)) {
			$queryBuilder->orderBy($orderBy);
		}

		if (isset(Model::$findOptions['limit'])) {
			$limit = Model::$findOptions['limit'];

			if (is_array($limit) && count($limit) > 1) {
				$queryBuilder->limit($limit[0], $limit[1]);
			}else{
				$queryBuilder->limit($limit);
			}
		}

		return $queryBuilder;
	}
1356495
private function getRuleSelectQuery(): QueryBuilder
    {
        $query = $this->connection->createQueryBuilder();
        $query->select('DISTINCT r.*', 'rd.*')
            ->from('ngbm_rule', 'r')
            ->innerJoin(
                'r',
                'ngbm_rule_data',
                'rd',
                $query->expr()->eq('rd.rule_id', 'r.id')
            );

        return $query;
    }
1339769
private function addGroupFilterToQueryBuilder(QueryBuilder $queryBuilder, $groupSearch)
    {
        if (null !== $groupSearch && '' !== $groupSearch) {
            $upperUserSearch = strtoupper($groupSearch);
            $upperUserSearch = trim($groupSearch);
            $upperUserSearch = preg_replace('/\s+/', ' ', $upperUserSearch);

            $queryBuilder->leftJoin('log.doer', 'doer');
            $queryBuilder->leftJoin('doer.groups', 'groupDoer');
            $queryBuilder->andWhere('groupDoer.name LIKE :groupSearch');

            $queryBuilder->setParameter('groupSearch', '%'.$upperUserSearch.'%');
        }

        return $queryBuilder;
    }
1066563
public function getNewQueryBuilder($complete = false)
    {
        $queryBuilder = $this->or->createQueryBuilder();

        if (isset($this->config['where'])) {
            $this->applyFilterArr($queryBuilder, $this->config['where'], $queryBuilder);
        }

        if (isset($this->config['joinWhere'])) {
            foreach ($this->config['joinWhere'] as $where) {
                list($name, $values, $subSelectField) = $where;
                if ($subSelectField === 'id') {
                    $queryBuilder->field($name)->in($values);
                } else {
                    $founds = array();
                    $className = explode('\\', $this->or->getClassName());
                    unset($className[count($className) - 1]);
                    $tmp = $this->service->getRepository(implode('\\', $className).'\\'.ucfirst($name))
                            ->createQueryBuilder()
                                ->field($subSelectField)->in($values)
                                ->getQuery()
                                ->execute();
                    foreach ($tmp as $t) {
                        $founds[] = $t->getId();
                    }
                    if (count($founds)) {
                        $queryBuilder->field($name)->in($founds);
                    } else {
                        $queryBuilder->field($name)->equals(0);
                    }
                }
            }
        }

        if (isset($this->config['orderBy'])) {
            foreach ($this->config['orderBy'] as $orderBy) {
                list($sort, $dir) = $orderBy;
                $queryBuilder->sort($sort, $dir);
            }
        }

        if (!$complete) {
            if (isset($this->config['firstResult'])) {
                $queryBuilder->skip($this->config['firstResult']);
            }
            if (isset($this->config['maxResults'])) {
                $queryBuilder->limit($this->config['maxResults']);
            }
        }

        return $queryBuilder;
    }
767754
public function getStatementBuilder($builderClass = Select::class)
    {
        // @SOMEDAY check for instance of StatementBuilder

        /** @var StatementBuilder $statementBuilder */
        $statementBuilder = new $builderClass();
        $table = $this->getResultModel()->getTableName();

        $statementBuilder->setFrom($table);

        return $statementBuilder;
    }
862916
public function search(QueryBuilderInterface $Builder) {
        $this->serialyse($Builder);
        $statement = $this->connector->query($this->parsedQuery);
        $result    = $this->statementToArray($statement);
        $resultSetClass = $this->resultSetClassName;
        $resultSet = new $resultSetClass($result);
        $queryCount = $this->getSerialyser()->setCriteriaList($Builder)->count(true)->serialyse();
        $resultSet->setParent($this)->setCountQuery($queryCount);
        return $resultSet;
    }
649055
public function subquery( QueryBuilder $queryBuilder ) {
		$this->subqueries[] = $queryBuilder->getSPARQL( false );
		$this->usageValidator->trackDefinedVariables( implode( ' ', $queryBuilder->getSelects() ) );

		// @todo temp hack to add AS definitions to defined variables
		$regexHelper = new RegexHelper();
		$matches = $regexHelper->getMatches( 'AS \{variable}', implode( ' ', $queryBuilder->getSelects() ) );
		$this->usageValidator->trackDefinedVariables( $matches );

		return $this;
	}
1031042
private function addPerformanceJoinsToQueryBuilder(QueryBuilder $queryBuilder)
    {
        $queryBuilder
            ->select(['p', 'pa', 'pc', 'rpc', 'i'])
            ->leftJoin('p.principalImage', 'pa')
            ->leftJoin('p.priceCurrency', 'pc')
            ->leftJoin('p.reducedPriceCurrency', 'rpc')
            ->leftJoin('p.images', 'i')
            ->groupBy('p.id');
    }
1361676
public function setTotalCountByQueryBuilder(QueryBuilder $queryBuilder)
    {
        $queryBuilder
            ->select(sprintf('COUNT(%s)', $queryBuilder->getRootAliases()[0]))
            ->setMaxResults(1);

        return $this->setTotalCount(intval($queryBuilder->getQuery()->getSingleScalarResult()));
    }
1250998
public function query(QueryBuilderCache $queryBuilderCache)
    {
        // Reconnect the connection in case isn't connected yet.
        $this->reconnect();

        $result = false;
        $queryStatement = new QueryStatement($queryBuilderCache);

        $startTime = microtime(true);

        // Run the query for real
        if ($this->disableQueryExecution === false) {
            $rows = $this->platformQueryHandler($queryStatement);
            $result = new Result($rows);

            if ($this->transactionInProgress) {
                $this->transactionStatus = ($queryStatement->hasErrors() ? false : true);
            }
        }

        $queryStatement->setDuration($startTime);

        $this->queriesCache[] = $queryStatement;

        if ($queryStatement->hasErrors()) {
            if ($this->debugEnabled) {
                throw new RuntimeException($queryStatement->getLatestErrorMessage(),
                    $queryStatement->getLatestErrorCode());
            }

            if ($this->transactionInProgress) {
                $this->transactionStatus = false;
                $this->transactionInProgress = false;
            }

            return false;
        }

        return $result;
    }
650877
private function getQueryBuilderForCachingHash($queryBuilder)
    {
        return [
            $queryBuilder->getQuery()->getSQL(),
            array_map([$this, 'parameterToArray'], $queryBuilder->getParameters()->toArray()),
        ];
    }
178225
public function getQuery(QueryBuilder $queryBuilder)
    {
        $action = $this->getRule()->getAction();
        $foundType = preg_match('/\[\[(.*)\]\]/', $action, $matches);

        if ($foundType) {
            $type = $matches[1];
            $parts = explode(']]', $action);
            $action = ($foundType) ? $parts[1] : $action;

            return $queryBuilder
                ->join('l.resourceType', 'rt')
                ->andWhere('l.action = :action')
                ->andWhere('rt.name = :type')
                ->setParameter('action', $action)
                ->setParameter('type', $type);
        } else {
            return $queryBuilder
                ->andWhere('l.action = :action')
                ->setParameter('action', $action);
        }
    }
408881
public function getTree(QueryBuilder $builder)
    {
        $query = Content::with(self::$loadRelations);

        if (optional($builder->getFilter('only_categories'))->getValue()) {
            $query->join('content_types as ct', 'contents.type_id', '=', 'ct.id');
            $query->where('ct.name', 'category');
        }

        $builder = (new QueryBuilder())->orderBy('translations.title', 'asc');

        $query->orderBy('level', 'ASC');

        $builder->applySorts($query, 'contents');

        $results = $query->distinct()->get(['contents.*']);
        $trees   = (new Content)->buildTree($results, true);
        if ($trees === null) {
            return collect([]);
        }
        if (!$trees instanceof Collection) {
            return collect([$trees]);
        }
        return $trees;
    }
1092597
protected function getConditionStringFromQueryBuilder(QueryBuilder $query)
    {
        $initialQueryChunks = explode('where ', $query->toSql());

        if (count($initialQueryChunks) == 1) {
            throw new InvalidArgumentException(
                'The query builder instance must have a where clause to build a condition string from'
            );
        }

        $queryChunks = explode('?', $initialQueryChunks[1]);
        $chunkCount  = count($queryChunks);
        $bindings    = $query->getBindings();
        $whereString = '';

        for ($i = 0; $i < $chunkCount; $i++) {

            $whereString .= $queryChunks[ $i ];

            if (isset($bindings[ $i ])) {

                if (gettype($bindings[ $i ]) === 'string') {
                    $whereString .= '"' . $bindings[ $i ] . '"';
                }
            }
        }

        return $whereString;
    }
566543
private function getQuerySelectQuery(): QueryBuilder
    {
        $query = $this->connection->createQueryBuilder();
        $query->select('DISTINCT q.*, qt.*')
            ->from('ngbm_collection_query', 'q')
            ->innerJoin(
                'q',
                'ngbm_collection_query_translation',
                'qt',
                $query->expr()->andX(
                    $query->expr()->eq('qt.query_id', 'q.id'),
                    $query->expr()->eq('qt.status', 'q.status')
                )
            );

        return $query;
    }
539552
protected function addJoinTablesToQueryBuilder(QueryBuilder $queryBuilder)
    {
        $objectManager = $this->getObjectManager();
        $entityAlias   = $this->getEntityClassAlias();
        $classMetaData = $objectManager->getClassMetadata($this->getEntityClass());

        $assocMappings = $classMetaData->getAssociationMappings();

        foreach ($assocMappings as $fieldName => $assocMapping) {
            $join  = $entityAlias . '.' . $fieldName;
            $alias = self::JOIN_ALIAS_PREFIX . $fieldName;

            $queryBuilder->addSelect($alias);
            $queryBuilder->leftJoin($join, $alias);
        }
    }