Skip to content

Commit 24301ba

Browse files
committed
perf: optimize querying post index
1 parent 863d652 commit 24301ba

File tree

2 files changed

+7
-14
lines changed

2 files changed

+7
-14
lines changed

framework/core/src/Api/Resource/PostResource.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,16 +129,16 @@ public function endpoints(): array
129129
$sort = $defaultExtracts['sort'];
130130
$filter = $defaultExtracts['filter'];
131131

132-
if (count($filter) > 1 || ! isset($filter['discussion']) || $sort) {
132+
if (count($filter) > 1 || ! isset($filter['discussion']) || ($sort && $sort !== ['number' => 'asc'])) {
133133
throw new BadRequestException(
134134
'You can only use page[near] with filter[discussion] and the default sort order'
135135
);
136136
}
137137

138138
$limit = $defaultExtracts['limit'];
139-
$offset = $this->posts->getIndexForNumber((int) $filter['discussion'], $near, $context->getActor());
139+
$index = $this->posts->getIndexForNumber((int) $filter['discussion'], $near, $context->getActor());
140140

141-
return max(0, $offset - $limit / 2);
141+
return max(0, $index - $limit / 2);
142142
}
143143

144144
return $defaultExtracts['offset'];
@@ -150,6 +150,7 @@ public function endpoints(): array
150150
'hiddenUser',
151151
'discussion'
152152
])
153+
->defaultSort('number')
153154
->paginate(static::$defaultLimit),
154155
];
155156
}

framework/core/src/Post/PostRepository.php

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -85,23 +85,15 @@ public function filterVisibleIds(array $ids, User $actor): array
8585
*/
8686
public function getIndexForNumber(int $discussionId, int $number, ?User $actor = null): int
8787
{
88+
/** @var Discussion $discussion */
8889
if (! ($discussion = Discussion::find($discussionId))) {
8990
return 0;
9091
}
9192

9293
$query = $discussion->posts()
9394
->whereVisibleTo($actor)
94-
->where('created_at', '<', function ($query) use ($discussionId, $number) {
95-
$query->select('created_at')
96-
->from('posts')
97-
->where('discussion_id', $discussionId)
98-
->whereNotNull('number')
99-
->take(1)
100-
101-
// We don't add $number as a binding because for some
102-
// reason doing so makes the bindings go out of order.
103-
->orderByRaw('ABS(CAST(number AS SIGNED) - '.(int) $number.')');
104-
});
95+
->where('number', '<=', $number)
96+
->orderBy('number');
10597

10698
return $query->count();
10799
}

0 commit comments

Comments
 (0)