Skip to content

Commit

Permalink
Make Paginator-internal query cacheable in the query cache
Browse files Browse the repository at this point in the history
Make the `Paginator`-internal query (`... WHERE ... IN (id, id2, id3...)`) cacheable in the query cache again.

When the Paginator creates the internal subquery that does the actual result limiting, it has to take DBAL type conversions for the identifier column of the paginated root entity into account (doctrine#7820, fixed in doctrine#7821).

In order to perform this type conversion, we need to know the DBAL type class for the root entity's identifier, and we have to derive it from a given (arbitrary) DQL query. This requires DQL parsing and inspecting the AST, so doctrine#7821 placed the conversion code in the `WhereInWalker` where all the necessary information is available.

The problem is that type conversion has to happen every time the paginator is run, but the query that results from running `WhereInWalker` would be kept in the query cache. This was reported in doctrine#7837 and fixed by doctrine#7865, by making this particular query expire every time. The query must not be cached, since the necessary ID type conversion happens as a side-effect of running the `WhereInWalker`.

The Paginator internal query that uses `WhereInWalker` has its DQL re-parsed and transformed in every request. In addition to the processing overhead, this may also waste opcache memory (doctrine#9917).

This PR moves the code that determines the DBAL type out of `WhereInWalker` into a dedicated SQL walker class, `RootTypeWalker`.

`RootTypeWalker` uses a ~hack~  clever trick to report the type back: It sets the type as the resulting "SQL" string. The benefit is that `RootTypeWalker` results can be cached in the query cache themselves. Only the first time a given DQL query has to be paginated, we need to run this walker to find out the root entity's ID type. After that, the type will be returned from the query cache.

With the type information being provided, `Paginator` can take care of the necessary conversions by itself. This happens every time the Paginator is used.

The internal query that uses `WhereInWalker` can be cached again since it no longer has side effects.
  • Loading branch information
mpdude committed Jan 23, 2023
1 parent 8b28543 commit 7e82cbb
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 35 deletions.
18 changes: 16 additions & 2 deletions lib/Doctrine/ORM/Tools/Pagination/Paginator.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,10 @@ public function getIterator()
$this->appendTreeWalker($whereInQuery, WhereInWalker::class);
$whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, count($ids));
$whereInQuery->setFirstResult(0)->setMaxResults(null);
$whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $ids);
$whereInQuery->setCacheable($this->query->isCacheable());
$whereInQuery->useQueryCache(false);

$databaseIds = $this->convertWhereInIdentifiersToDatabaseValue($ids);
$whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $databaseIds);

$result = $whereInQuery->getResult($this->query->getHydrationMode());
} else {
Expand Down Expand Up @@ -265,4 +266,17 @@ private function unbindUnusedQueryParams(Query $query): void

$query->setParameters($parameters);
}

private function convertWhereInIdentifiersToDatabaseValue(array $identifiers): array
{
$query = $this->cloneQuery($this->query);
$query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, RootTypeWalker::class);

$type = $query->getSQL();
$connection = $this->query->getEntityManager()->getConnection();

return array_map(static function ($id) use ($connection, $type) {
return $connection->convertToDatabaseValue($id, $type);
}, $identifiers);
}
}
48 changes: 48 additions & 0 deletions lib/Doctrine/ORM/Tools/Pagination/RootTypeWalker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Tools\Pagination;

use Doctrine\ORM\Query\AST;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Utility\PersisterHelper;
use RuntimeException;

use function count;
use function reset;

/**
* Infers the DBAL type of the #Id (identifier) column of the given query's root entity, and
* returns it in place of a real SQL statement.
*
* Obtaining this type is a necessary intermediate step for \Doctrine\ORM\Tools\Pagination\Paginator.
* We can best do this from a tree walker because it gives us access to the AST.
*
* Returning the type instead of a "real" SQL statement is a slight hack. However, it has the
* benefit that the DQL -> root entity id type resolution can be cached in the query cache.
*/
class RootTypeWalker extends SqlWalker
{
public function walkSelectStatement(AST\SelectStatement $AST): string
{
// Get the root entity and alias from the AST fromClause
$from = $AST->fromClause->identificationVariableDeclarations;

if (count($from) > 1) {
throw new RuntimeException('Can only process queries that select only one FROM component');
}

$fromRoot = reset($from);
$rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable;
$rootClass = $this->getMetadataForDqlAlias($rootAlias);
$identifierFieldName = $rootClass->getSingleIdentifierFieldName();

return PersisterHelper::getTypeOfField(
$identifierFieldName,
$rootClass,
$this->getQuery()
->getEntityManager()
)[0];
}
}
33 changes: 0 additions & 33 deletions lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,9 @@
use Doctrine\ORM\Query\AST\SimpleArithmeticExpression;
use Doctrine\ORM\Query\AST\WhereClause;
use Doctrine\ORM\Query\TreeWalkerAdapter;
use Doctrine\ORM\Utility\PersisterHelper;
use RuntimeException;

use function array_map;
use function assert;
use function count;
use function is_array;
use function reset;

/**
Expand Down Expand Up @@ -80,15 +76,6 @@ public function walkSelectStatement(SelectStatement $AST)
$arithmeticExpression,
[new InputParameter(':' . self::PAGINATOR_ID_ALIAS)]
);

$this->convertWhereInIdentifiersToDatabaseValue(
PersisterHelper::getTypeOfField(
$identifierFieldName,
$rootClass,
$this->_getQuery()
->getEntityManager()
)[0]
);
} else {
$expression = new NullComparisonExpression($pathExpression);
}
Expand Down Expand Up @@ -130,24 +117,4 @@ public function walkSelectStatement(SelectStatement $AST)
);
}
}

private function convertWhereInIdentifiersToDatabaseValue(string $type): void
{
$query = $this->_getQuery();
$identifiersParameter = $query->getParameter(self::PAGINATOR_ID_ALIAS);

assert($identifiersParameter !== null);

$identifiers = $identifiersParameter->getValue();

assert(is_array($identifiers));

$connection = $this->_getQuery()
->getEntityManager()
->getConnection();

$query->setParameter(self::PAGINATOR_ID_ALIAS, array_map(static function ($id) use ($connection, $type) {
return $connection->convertToDatabaseValue($id, $type);
}, $identifiers));
}
}

0 comments on commit 7e82cbb

Please sign in to comment.