#12625·orm

OffsetPaginator always runs the COUNT query, unlike CursorPaginator

Author: ker0xCreated Sep 20, 2026Updated Sep 28, 2026

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

OffsetPaginator::paginate() always runs the COUNT query, even when the caller only wants the rows. CursorPaginator already defers it, and the two could be symmetric.

OffsetPaginator computes the total before constructing the page:

https://github.com/doctrine/orm/blob/3.7.0/src/Tools/Pagination/OffsetPaginator.php#L88-L94

php
try {
    $totalCount = (int) array_sum(array_map('current', $this->getCountQuery($query)->getScalarResult()));
} catch (NoResultException) {
    $totalCount = 0;
}

return new WindowPage($items, $totalCount, $position);

and WindowPage takes it as an int, so there is no lazy path:

php
public function __construct(
    private readonly array $items,
    private readonly int $totalCount,
    private readonly Window $window,
) {

CursorPage, by contrast, takes a Closure and memoizes:

php
/** Memoizes the COUNT query, which is only run when asked for. */
private int|null $totalCount = null;

public function getTotalCount(): int
{
    return $this->totalCount ??= ($this->totalCountProvider)();
}

Current behavior

Fetching one page of a query that joins a collection, using only getItems():

OffsetPaginator, getItems() only -> 3 queries
  1) SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1
  2) SELECT a0_.id AS id_0, a0_.name AS name_1, b1_.id AS id_2, b1_.title AS title_3, b1_.author_id
  3) SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name

CursorPaginator, getItems() only -> 2 queries (COUNT deferred)

The third query is unused. On a large joined result set that COUNT over a DISTINCT subquery is often the most expensive of the three.

The legacy Paginator did not have this cost: it only counted when count() was called. So the migration path recommended by the 3.7 deprecation notice makes count-free pagination more expensive than the class it replaces.

Expected behavior

getTotalCount() runs the COUNT; not calling it runs nothing extra — matching CursorPage.

Why it matters

It removes the one performance regression in Paginator → OffsetPaginator, and it matters most for pagination that deliberately avoids counting:

  • "load more" / infinite scroll, which needs rows and a has-more flag, never a total;
  • lookahead pagination (fetch limit + 1, drop the extra), whose entire purpose is to paginate without a COUNT.

In Symfony UX Pagination (symfony/ux#3898) we just moved off the deprecated Paginator and this costs us one extra query per slice on collection-joined queries, including on our lookahead() strategy where the total is never read. We kept the migration anyway, since Paginator is removed in 4.0.

Possible implementation

Mirror CursorPage: pass a Closure(): int to WindowPage and memoize it there.

That changes WindowPage::__construct's second parameter type. WindowPage is final and new in 3.7, and the constructor is realistically only called by OffsetPaginator, but it is public API — so if it should stay int, an alternative is a second constructor argument or a named constructor taking the provider, keeping the current signature working.

I am happy to send a PR for whichever shape you prefer.

Standalone reproducer
php
<?php
require 'vendor/autoload.php';

use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Logging\Middleware;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\ORMSetup;
use Doctrine\ORM\Tools\Pagination\{CursorPaginator, OffsetPaginator, Window};
use Doctrine\ORM\Tools\SchemaTool;
use Psr\Log\AbstractLogger;

#[ORM\Entity]
class Author
{
    #[ORM\Id, ORM\Column, ORM\GeneratedValue] public int $id;
    #[ORM\Column] public string $name = '';
    #[ORM\OneToMany(targetEntity: Book::class, mappedBy: 'author', cascade: ['persist'])]
    public $books;
    public function __construct() { $this->books = new \Doctrine\Common\Collections\ArrayCollection(); }
}

#[ORM\Entity]
class Book
{
    #[ORM\Id, ORM\Column, ORM\GeneratedValue] public int $id;
    #[ORM\Column] public string $title = '';
    #[ORM\ManyToOne(targetEntity: Author::class, inversedBy: 'books')] public ?Author $author = null;
}

$log = new class extends AbstractLogger {
    public array $q = [];
    public function log($level, $message, array $context = []): void {
        if (str_starts_with((string) $message, 'Executing ') && isset($context['sql'])) { $this->q[] = $context['sql']; }
    }
};

$config = ORMSetup::createAttributeMetadataConfig(paths: [__DIR__], isDevMode: true);
$config->enableNativeLazyObjects(true);
$config->setMiddlewares([new Middleware($log)]);
$em = new EntityManager(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $config), $config);
new SchemaTool($em)->createSchema([$em->getClassMetadata(Author::class), $em->getClassMetadata(Book::class)]);

for ($i = 1; $i <= 8; ++$i) {
    $a = new Author(); $a->name = "A$i";
    for ($j = 1; $j <= 3; ++$j) { $b = new Book(); $b->title = "B$j"; $b->author = $a; $em->persist($b); }
    $em->persist($a);
}
$em->flush();
$em->clear();

$qb = fn () => $em->createQueryBuilder()->select('a', 'b')->from(Author::class, 'a')
    ->leftJoin('a.books', 'b')->orderBy('a.id', 'ASC');

$log->q = [];
new OffsetPaginator(fetchJoinCollection: true)->paginate($qb(), new Window(0, 5))->getItems();
echo 'OffsetPaginator, getItems() only -> ', count($log->q), " queries\n";

$em->clear();
$log->q = [];
new CursorPaginator(5)->paginate($qb(), null)->getItems();
echo 'CursorPaginator, getItems() only -> ', count($log->q), " queries\n";