Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: speed up the listPastEvents query ⚡️ #684

Merged
merged 2 commits into from
Dec 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 40 additions & 11 deletions packages/core/src/modules/events/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,25 +199,55 @@ type ListPastEventsInput = {
export async function listPastEvents({ timezone }: ListPastEventsInput) {
const records = await db
.selectFrom('events')
.leftJoin('eventAttendees', 'eventAttendees.eventId', 'events.id')
.leftJoin('students', 'students.id', 'eventAttendees.studentId')
.leftJoin(
(eb) => {
return eb
.selectFrom('eventAttendees')
.select(['eventId', ({ fn }) => fn.count('email').as('attendees')])
.groupBy('eventId')
.as('attendees');
},
(join) => {
return join.onRef('attendees.eventId', '=', 'events.id');
}
)
.leftJoin(
(eb) => {
return eb
.selectFrom('eventAttendees')
.leftJoin('students', 'students.id', 'eventAttendees.studentId')
.select([
'eventId',
'profilePicture',
({ ref }) => {
const field = sql<number>`row_number() over (partition by ${ref('eventId')} order by ${ref('eventAttendees.createdAt')} asc)`;

return field.as('rank');
},
])
.where('students.profilePicture', 'is not', null)
.as('pictures');
},
(join) => {
return join
.onRef('pictures.eventId', '=', 'events.id')
.on('pictures.rank', '<=', 3);
}
)
.select([
'events.endTime',
'events.id',
'events.name',
'events.recordingLink',
'events.startTime',
({ fn }) => {
return fn.max('attendees.attendees').as('attendeesCount');
},
({ ref }) => {
const field = sql<string>`string_agg(${ref('students.profilePicture')}, ',' order by ${ref('eventAttendees.createdAt')} asc)`;
const field = sql<string>`string_agg(${ref('profilePicture')}, ',')`;

return field.as('profilePictures');
},
({ fn }) => {
return fn
.count<string>('eventAttendees.email')
.distinct()
.as('attendeesCount');
},
])
.where('events.endTime', '<=', new Date())
.where('events.hidden', '=', false)
Expand All @@ -240,8 +270,7 @@ export async function listPastEvents({ timezone }: ListPastEventsInput) {

const profilePictures = (_profilePictures || '')
.split(',')
.filter(Boolean)
.slice(0, 3);
.filter(Boolean);

return {
...record,
Expand Down
Loading