Skip to content

Commit 9bf28d5

Browse files
committed
perf(cleanup): Optimize fetching all document to cleanup
Do that in one query instead of ending up doing N+1 queries. Signed-off-by: Carl Schwan <carlschwan@kde.org>
1 parent 95ea143 commit 9bf28d5

File tree

3 files changed

+21
-7
lines changed

3 files changed

+21
-7
lines changed

lib/Cron/Cleanup.php

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,7 @@ public function __construct(
3636
*/
3737
protected function run($argument): void {
3838
$this->logger->debug('Run cleanup job for text documents');
39-
foreach ($this->documentService->getAll() as $document) {
40-
if ($this->sessionService->countAllSessions($document->getId()) > 0) {
41-
// Do not reset if there are any sessions left
42-
// Inactive sessions will get removed further down and will trigger a reset next time
43-
continue;
44-
}
45-
39+
foreach ($this->documentService->getAllWithNoActiveSession() as $document) {
4640
try {
4741
$this->documentService->resetDocument($document->getId());
4842
} catch (DocumentHasUnsavedChangesException) {

lib/Db/DocumentMapper.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,22 @@ public function findAll(): Generator {
5454
}
5555
}
5656

57+
public function findAllWithNoActiveSessions(): Generator {
58+
$qb = $this->db->getQueryBuilder();
59+
$result = $qb->select('d.*')
60+
->from($this->getTableName(), 'd')
61+
->leftJoin('d', 'text_sessions', 's', $qb->expr()->eq('s.document_id', 'd.id'))
62+
->where($qb->expr()->isNull('s.id'))
63+
->executeQuery();
64+
try {
65+
while ($row = $result->fetch()) {
66+
yield $this->mapRowToEntity($row);
67+
}
68+
} finally {
69+
$result->closeCursor();
70+
}
71+
}
72+
5773
public function countAll(): int {
5874
$qb = $this->db->getQueryBuilder();
5975
$qb->select($qb->func()->count('id'))

lib/Service/DocumentService.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,10 @@ public function getAll(): \Generator {
463463
return $this->documentMapper->findAll();
464464
}
465465

466+
public function getAllWithNoActiveSession(): \Generator {
467+
return $this->documentMapper->findAllWithNoActiveSessions();
468+
}
469+
466470
/**
467471
* @throws NotPermittedException
468472
* @throws NotFoundException

0 commit comments

Comments
 (0)