Browse Source

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.
pull/5858/head
Sven Günther 3 days ago
parent
commit
094b508358
  1. 27
      apps/api/src/services/market-data/market-data.service.ts

27
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
});
}
});
}
}

Loading…
Cancel
Save