Skip to content

Commit

Permalink
feature/MTCE-357-fix-results-count-when-large-dataset-is-enabled
Browse files Browse the repository at this point in the history
* more precise pagination
  • Loading branch information
alexandrtspl committed Feb 17, 2025
1 parent 2fc1e4b commit 62ac865
Showing 1 changed file with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ trait DoctrineCommonPaginatorTrait
{
use DatabaseCommonPaginatorTrait;

private const MORE_PRECISE_ROWS_COUNT = 100000;
private ?string $fromAlias = null;

private ?int $totalItems = null;
Expand Down Expand Up @@ -133,6 +134,29 @@ private function fetchItemsUsingQuery(OrmQueryBuilder|DbalQueryBuilder $queryBui
return $this->fetchResults($queryBuilder);
}

/**
* @throws \Doctrine\DBAL\Exception
*/
private function getMorePreciseCount(string $sql, ?int $count): ?int
{
if ($count !== null && $count > self::MORE_PRECISE_ROWS_COUNT) {
return $count;
}

$matches = u($sql)->match('/FROM (?P<table>[a-z_]+)/i');

$sql = \sprintf(
'SELECT COUNT(*) FROM (SELECT 1 FROM %s LIMIT %d) AS t',
$matches['table'],
self::MORE_PRECISE_ROWS_COUNT + 1
);

/** @var int|false $result */
$result = $this->getConnection()->executeQuery($sql)->fetchOne();

return $result !== false ? (int)$result : null;
}

/**
* @throws \Doctrine\DBAL\Exception
*/
Expand Down Expand Up @@ -189,7 +213,11 @@ private function getTotalItemsForLargeDataset(OrmQueryBuilder|DbalQueryBuilder $
$matches = u($queryPlan)
->match('/rows=(\d+)/');

return isset($matches[1]) ? (int)$matches[1] : null;
$count = isset($matches[1]) ? (int)$matches[1] : null;

return $platform instanceof PostgreSQLPlatform
? $this->getMorePreciseCount($sql, $count)
: $count;
}

return null;
Expand Down

0 comments on commit 62ac865

Please sign in to comment.