Skip to content

Commit

Permalink
fix: speed up the listPastEvents query ⚡️ (#684)
Browse files Browse the repository at this point in the history
  • Loading branch information
ramiAbdou authored Dec 15, 2024
1 parent fbfe70c commit 988b84a
Showing 1 changed file with 40 additions and 11 deletions.
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

0 comments on commit 988b84a

Please sign in to comment.