I have an upsert fail: ``` Unique constraint fail...
# orm-help
p
I have an upsert fail:
Copy code
Unique constraint failed on the constraint: `stats_company_id_day_stat_type_context_key`
Isn’t the idea of the upsert it doesn’t fail but does the update, then?? I’m doing:
Copy code
prisma.stats.upsert({
      create: stat,
      update: stat,
      where: {
        company_id_day_stat_type_context: {
          company_id: companyId,
          day: stat.day,
          context: stat.context || "",
          stat_type: stat.stat_type,
        },
      },
    });
n
upsert will update only if the where conditions match with a record. It seems that no record is matching and consequently when upsert tries to insert the record, some unique constraint must be failing.
p
thanks for replying
but if no record exists, the insert should work, right?
n
yes if there is no record then new record should be inserted
p
yes, and that should work, otherwise it should do an update, right?
this is the only index (and id, but that’s autogenerated)
n
Can you share your models? I can try to replicate it
p
I was doing this:
Copy code
const toUpsert = stats.map((stat) => {
    return prisma.stats.upsert({
      create: stat,
      // update: stat,
      update: {},
      where: {
        company_id_day_stat_type_context: {
          company_id: stat.company_id,
          day: stat.day,
          context: stat.context || "",
          stat_type: stat.stat_type,
        },
      },
    });
  });
  await Promise.all(toUpsert);
and I think we have a race condition, as described in https://github.com/prisma/prisma/issues/3242
as prisma (unfortunately) doesn’t do “real” upserts but select and insert, and can’t properly handle the concurrent requests
(there will be about 60-70 stats)
btw this is the model:
Copy code
model stats {
  id         String   @id @default(uuid()) @db.Char(36)
  company_id String   @db.Char(36)
  day        DateTime @db.Date
  stat_type  StatType
  stat_value Int
  context    String? //Map or location or not, when full company
  created    DateTime @default(now())
  updated_at DateTime @updatedAt
  company    company  @relation(fields: [company_id], references: [id])

  /// Only one unique stat per day per context per company
  @@unique([company_id, day, stat_type, context])
  @@index([day, company_id])
  @@index([context])
}