From b088a2ee6edb05ee5ccf103c2b2a2fe2a7721049 Mon Sep 17 00:00:00 2001 From: Kristofor Carle Date: Thu, 11 Dec 2025 14:53:08 -0500 Subject: [PATCH] fix prisma session race condition error --- src/queries/sql/sessions/saveSessionData.ts | 36 ++++++++------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/src/queries/sql/sessions/saveSessionData.ts b/src/queries/sql/sessions/saveSessionData.ts index 74093177..cce6cd28 100644 --- a/src/queries/sql/sessions/saveSessionData.ts +++ b/src/queries/sql/sessions/saveSessionData.ts @@ -46,31 +46,23 @@ export async function relationalQuery({ createdAt, })); - const existing = await client.sessionData.findMany({ - where: { - sessionId, - }, - select: { - id: true, - sessionId: true, - dataKey: true, - }, - }); - for (const data of flattenedData) { const { sessionId, dataKey, ...props } = data; - const record = existing.find(e => e.sessionId === sessionId && e.dataKey === dataKey); - if (record) { - await client.sessionData.update({ - where: { - id: record.id, - }, - data: { - ...props, - }, - }); - } else { + // Try to update existing record using compound where clause + // This is safer than using id from a previous query due to race conditions + const updateResult = await client.sessionData.updateMany({ + where: { + sessionId, + dataKey, + }, + data: { + ...props, + }, + }); + + // If no record was updated, create a new one + if (updateResult.count === 0) { await client.sessionData.create({ data, });