From bab196e60b727c762d0b2f02cc7b03bc70d5d83f Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:15:58 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=BB=84=E5=8D=B7=E5=A4=A7=E8=A7=84?= =?UTF-8?q?=E6=A8=A1=E9=80=89=E9=A2=98=E6=94=B9=E7=94=A8=E6=B8=B8=E6=A0=87?= =?UTF-8?q?=E5=88=86=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/__tests__/unit/exam-selection.test.ts | 17 +++++++++++++++++ src/lib/exam/exam.ts | 8 ++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/__tests__/unit/exam-selection.test.ts b/src/__tests__/unit/exam-selection.test.ts index f6161230..6b623204 100644 --- a/src/__tests__/unit/exam-selection.test.ts +++ b/src/__tests__/unit/exam-selection.test.ts @@ -69,4 +69,21 @@ describe('selectSourceItems 结果与知识点筛选', () => { }); expect(picked).toHaveLength(3); }); + + it('大规模候选题使用主键游标继续分页,避免 offset 重复扫描', async () => { + const firstPage = Array.from({ length: 500 }, (_, index) => candidate(`page-1-${index}`, '函数', null)); + const secondPage = [candidate('page-2-0', '函数', null)]; + mocks.findMany.mockResolvedValueOnce(firstPage).mockResolvedValueOnce(secondPage); + + const picked = await selectSourceItems('u1', { ...baseSelection, count: 1 }); + + expect(picked).toHaveLength(1); + expect(mocks.findMany).toHaveBeenCalledTimes(2); + expect(mocks.findMany.mock.calls[1][0]).toMatchObject({ + cursor: { id: 'page-1-499' }, + skip: 1, + take: 500, + orderBy: { id: 'asc' }, + }); + }); }); diff --git a/src/lib/exam/exam.ts b/src/lib/exam/exam.ts index 31943431..c0a51d30 100644 --- a/src/lib/exam/exam.ts +++ b/src/lib/exam/exam.ts @@ -167,11 +167,14 @@ export async function selectSourceItems(userId: string, selection: ExamSelection }> = []; // 只有原题直出需要判断题干;标签、最近一次作答和计数都在每个小批次内读取。 // 这样即使错题本超过 1000 道,也不会让 Prisma 把全部父级 ID 放进一次关联查询。 - for (let skip = 0; ; skip += EXAM_SELECTION_RELATION_BATCH_SIZE) { + // 使用主键游标而不是不断增加 offset,避免大错题本在后续分页中重复扫描, + // 同时让一次选题过程中发生新增/删除时仍保持分页边界稳定。 + let cursor: { id: string } | undefined; + for (;;) { const page = await prisma.errorItem.findMany({ where, orderBy: { id: 'asc' }, - skip, + ...(cursor ? { cursor, skip: 1 } : {}), take: EXAM_SELECTION_RELATION_BATCH_SIZE, select: { id: true, @@ -191,6 +194,7 @@ export async function selectSourceItems(userId: string, selection: ExamSelection }); candidates.push(...page); if (page.length < EXAM_SELECTION_RELATION_BATCH_SIZE) break; + cursor = { id: page[page.length - 1].id }; } let items = candidates.map(({ _count, practiceRecords, tags, ...item }) => ({ ...item,