From 094b5083583f91b3d724b8c3a7b9e21afbff4115 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sven=20G=C3=BCnther?= Date: Mon, 27 Oct 2025 17:11:32 +0100 Subject: [PATCH] Fix P2002 unique constraint error in replaceAllForSymbol Replace Promise.all with createMany to handle duplicate dates in the data array when atomically replacing market data. The previous implementation used multiple parallel create() operations which caused a P2002 unique constraint violation when the data array contained duplicate dates (e.g., when market prices are forward-filled for non-trading days). Changes: - Replace Promise.all of individual create() operations with createMany() - Add skipDuplicates: true to silently handle duplicate records - Add data.length check to avoid empty createMany call This maintains the atomic transaction behavior while efficiently handling batch inserts with potential duplicates. --- .../market-data/market-data.service.ts | 27 +++++++++---------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/apps/api/src/services/market-data/market-data.service.ts b/apps/api/src/services/market-data/market-data.service.ts index ea15fc9cd..e046bc8dd 100644 --- a/apps/api/src/services/market-data/market-data.service.ts +++ b/apps/api/src/services/market-data/market-data.service.ts @@ -228,21 +228,18 @@ export class MarketDataService { } }); - const upsertPromises = data.map( - ({ dataSource, date, marketPrice, state }) => { - return prisma.marketData.create({ - data: { - dataSource: dataSource as DataSource, - date: date as Date, - marketPrice: marketPrice as number, - state: state as MarketDataState, - symbol: symbol as string - } - }); - } - ); - - await Promise.all(upsertPromises); + if (data.length > 0) { + await prisma.marketData.createMany({ + data: data.map(({ dataSource, date, marketPrice, state }) => ({ + dataSource: dataSource as DataSource, + date: date as Date, + marketPrice: marketPrice as number, + state: state as MarketDataState, + symbol: symbol as string + })), + skipDuplicates: true + }); + } }); } }