From dc21805077103e6f8cfdab020f418a643114faeb Mon Sep 17 00:00:00 2001 From: billlzzz10 <208072329+billlzzz10@users.noreply.github.com> Date: Thu, 23 Jul 2026 17:28:19 +0000 Subject: [PATCH] perf(admin): resolve N+1 query in CSV import route Instead of making a database query for each row in the CSV to check if the prompt exists, the route now fetches all existing prompts matching the CSV titles in a single bulk query and stores them in a memory Set for O(1) lookups. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> --- src/app/api/admin/import-prompts/route.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/app/api/admin/import-prompts/route.ts b/src/app/api/admin/import-prompts/route.ts index 8efd7b3a..5fa11ea8 100644 --- a/src/app/api/admin/import-prompts/route.ts +++ b/src/app/api/admin/import-prompts/route.ts @@ -196,18 +196,25 @@ export async function POST(request: NextRequest) { let skipped = 0; const errors: string[] = []; + // ⚡ Bolt Optimization: Prevent N+1 query by fetching existing titles in bulk + const titlesToImport = rows.map((r) => r.act).filter(Boolean); + const existingPrompts = await db.prompt.findMany({ + where: { title: { in: titlesToImport } }, + select: { title: true }, + }); + const existingTitles = new Set(existingPrompts.map((p) => p.title)); + for (const row of rows) { try { - // Check if prompt with same title already exists - const existing = await db.prompt.findFirst({ - where: { title: row.act }, - }); - - if (existing) { + // Check if prompt with same title already exists (O(1) memory lookup) + if (existingTitles.has(row.act)) { skipped++; continue; } + // Add to set to prevent duplicates if CSV has duplicate titles + existingTitles.add(row.act); + // Get or create contributor user const authorId = await getOrCreateContributor(row.contributor);