diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 00000000..33d1ddc8 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-10-22 - Optimizing Distinct Counts in Prisma +**Learning:** Prisma's `.count()` API does not support the `distinct` argument in this project's version, which prevents us from doing `prisma.model.count({ distinct: ['field'] })`. We were working around this by fetching all rows to Node.js and deduplicating them with a `Set`. +**Action:** To compute a distinct count at the database level and avoid O(N) memory/network usage, use `.findMany({ distinct: ['field'], select: { field: true } })` followed by calling `.length` on the results. This pushes the deduplication to the database engine. diff --git a/src/server/api/routers/judging.ts b/src/server/api/routers/judging.ts index f206af8e..fe75a4ff 100644 --- a/src/server/api/routers/judging.ts +++ b/src/server/api/routers/judging.ts @@ -2126,9 +2126,11 @@ export const judgingRouter = createTRPCRouter({ }); if (duplicate) throw new TRPCError({ code: "CONFLICT", message: "This judge already has that scoring scope." }); + // ⚡ Bolt: Pushing deduplication to the database to reduce memory and network overhead. + // Expected impact: Faster database query and reduced Node.js memory footprint. const projectCount = await ctx.prisma.judgingAssignment - .findMany({ where: { judgeId: judge.id }, select: { projectId: true } }) - .then(rows => new Set(rows.map(row => row.projectId)).size); + .findMany({ where: { judgeId: judge.id }, distinct: ["projectId"], select: { projectId: true } }) + .then(rows => rows.length); const alreadyVisits = await ctx.prisma.judgingAssignment.count({ where: { judgeId: judge.id, projectId: assignment.projectId }, });