Skip to content

Commit 46e8b80

Browse files
committed
Faster endpoints
1 parent 7f92f4a commit 46e8b80

3 files changed

Lines changed: 13 additions & 1 deletion

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
-- It's very common to query by sessionId, userId, projectId, branchId, and eventStartedAt at the same time.
2+
-- We can use a composite index to speed up the query.
3+
-- Sadly we can't add this to the Prisma schema itself because Prisma does not understand composite indexes of JSONB fields.
4+
-- So we have to add it manually.
5+
-- (This is similar to the older idx_event_userid_projectid_branchid_eventstartedat index, but with sessionId added.)
6+
CREATE INDEX idx_event_sessionid_userid_projectid_branchid_eventstartedat ON "Event" ((data->>'projectId'), (data->>'branchId'), (data->>'userId'), (data->>'sessionId'), "eventStartedAt");

apps/backend/src/app/api/latest/auth/sessions/crud.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ export const sessionsCrudHandlers = createLazyProxy(() => createCrudHandlers(ses
4949
? Prisma.sql`data->>'sessionId' = ANY(${Prisma.sql`ARRAY[${Prisma.join(refreshTokenObjs.map(s => s.id))}]`})`
5050
: Prisma.sql`FALSE`}
5151
AND "systemEventTypeIds" @> '{"$session-activity"}'
52+
AND data->>'userId' = ${query.user_id}
53+
AND data->>'projectId' = ${auth.tenancy.project.id}
54+
AND COALESCE(data->>'branchId', 'main') = ${auth.tenancy.branchId}
5255
GROUP BY data->>'sessionId'
5356
)
5457
SELECT e.data->>'sessionId' as "sessionId",

apps/backend/src/app/api/latest/users/crud.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,10 @@ export const getUsersLastActiveAtMillis = async (projectId: string, branchId: st
210210
const events = await prisma.$queryRaw<Array<{ userId: string, lastActiveAt: Date }>>`
211211
SELECT data->>'userId' as "userId", MAX("eventStartedAt") as "lastActiveAt"
212212
FROM ${sqlQuoteIdent(schema)}."Event"
213-
WHERE data->>'userId' = ANY(${Prisma.sql`ARRAY[${Prisma.join(userIds)}]`}) AND data->>'projectId' = ${projectId} AND COALESCE("data"->>'branchId', 'main') = ${branchId} AND "systemEventTypeIds" @> '{"$user-activity"}'
213+
WHERE data->>'userId' = ANY(${Prisma.sql`ARRAY[${Prisma.join(userIds)}]`})
214+
AND data->>'projectId' = ${projectId}
215+
AND COALESCE("data"->>'branchId', 'main') = ${branchId}
216+
AND "systemEventTypeIds" @> '{"$user-activity"}'
214217
GROUP BY data->>'userId'
215218
`;
216219

0 commit comments

Comments
 (0)