Skip to content

Commit

Permalink
Fixed bug on paginating ORDER BY queries
Browse files Browse the repository at this point in the history
In some cases, the paginator can give the wrong result when an explicit
ORDER BY clause collides with the field that Paginate is trying to
select in order to limit the query.

Example: User belongsTo group, where group 1 has 4 users. The following
DQL will, when paginated, return only a single user and not all 4 users.

SELECT u FROM User u LEFT JOIN u.group g WHERE g.name = 'Some group' ORDER BY g.id ASC

Paginate will issue a select for the User.id but adds the ORDER BY
clause in the resultset. But the ScalarHydrator simply overwrites the
User.id with the Group.id, causing the query to fail.

This update ensures that the LimitSubQuery uses unique column aliases to
fix the issue.
  • Loading branch information
sandermarechal committed Oct 10, 2011
1 parent 0f0ff09 commit 8999bea
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/DoctrineExtensions/Paginate/LimitSubqueryWalker.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

use Doctrine\ORM\Query\TreeWalkerAdapter,
Doctrine\ORM\Query\AST\SelectStatement,
Doctrine\ORM\Query\AST\SimpleSelectExpression,
Doctrine\ORM\Query\AST\SelectExpression,
Doctrine\ORM\Query\AST\PathExpression,
Doctrine\ORM\Query\AST\AggregateExpression;

Expand All @@ -35,6 +35,10 @@
*/
class LimitSubqueryWalker extends TreeWalkerAdapter
{
/**
* @var int Counter for generating unique order column aliases
*/
private $_aliasCounter = 0;

/**
* Walks down a SelectStatement AST node, modifying it to retrieve DISTINCT ids
Expand Down Expand Up @@ -68,7 +72,7 @@ public function walkSelectStatement(SelectStatement $AST)
$pathExpression->type = PathExpression::TYPE_STATE_FIELD;

$AST->selectClause->selectExpressions = array(
new SimpleSelectExpression($pathExpression)
new SelectExpression($pathExpression, '_dctrn_id')
);

if (isset($AST->orderByClause)) {
Expand All @@ -79,7 +83,7 @@ public function walkSelectStatement(SelectStatement $AST)
$item->expression->field
);
$pathExpression->type = PathExpression::TYPE_STATE_FIELD;
$AST->selectClause->selectExpressions[] = new SimpleSelectExpression($pathExpression);
$AST->selectClause->selectExpressions[] = new SelectExpression($pathExpression, '_dctrn_ord' . $this->_aliasCounter++);
}
}

Expand Down

0 comments on commit 8999bea

Please sign in to comment.