question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Upsert errors with compound unique key with Date on MySQL: `Query ... is required to return data, but found no record(s)`

See original GitHub issue

Discussed in https://github.com/prisma/prisma/discussions/12730

<div type='discussions-op-text'>

Originally posted by hirasaki1985 April 8, 2022 Hi, there.

I have a error. I tried to use upsert function with the multi @@unique key. Could you please tell me how to deal with it?

schema.prisma

model UserActiveHistorySummary {
  summary_date                 DateTime                        @db.Date
  user_id                      String                          @db.VarChar(255)
  login_count                  Int                             @default(0)
  created_at                   DateTime                        @default(now()) @db.DateTime(0)
  updated_at                   DateTime                        @default(now()) @db.DateTime(0)
  users                        User                            @relation(fields: [user_id], references: [user_id], onDelete: Cascade, map: "fk_uash_user_id_users_user_id")

  @@unique([summary_date, user_id], map: "uq_uahs_summary_date_user_id")
  @@index([summary_date, login_count], map: "idx_uahs_summary_date_login_count")
  @@index([summary_date], map: "idx_uahs_summary_date")
  @@index([user_id], map: "idx_uahs_user_id")

  @@map("user_active_history_summaries")
}

source code

  const prisma = new PrismaClient()

  await prisma.userActiveHistorySummary.upsert({
    where: {
      summary_date_user_id: {
        summary_date: '2022-03-29T00:00:00+09:00',
        user_id: 'shimizu_test',
      },
    },
    create: {
      summary_date: '2022-03-29T00:00:00+09:00',
      user_id: 'shimizu_test',
      login_count: 3,
    },
    update: {
      login_count: 7,
    },
  })

console error

/Users/hirasaki/work/couger/sources/Ludens-analytics/server/node_modules/@prisma/client/runtime/index.js:45582
        throw new PrismaClientUnknownRequestError(message, this.client._clientVersion);
              ^
PrismaClientUnknownRequestError: 
Invalid `prisma.userActiveHistorySummary.upsert()` invocation:


  Query upsertOneUserActiveHistorySummary is required to return data, but found no record(s).
    at Object.request (/Users/hirasaki/work/couger/sources/Ludens-analytics/server/node_modules/@prisma/client/runtime/index.js:45582:15)
    at async PrismaClient._request (/Users/hirasaki/work/couger/sources/Ludens-analytics/server/node_modules/@prisma/client/runtime/index.js:46405:18) {
  clientVersion: '3.12.0'
}

generated table schema.

-- CreateTable
CREATE TABLE `user_active_history_summaries` (
    `summary_date` DATE NOT NULL,
    `user_id` VARCHAR(255) NOT NULL,
    `login_count` INTEGER NOT NULL DEFAULT 0,
    `created_at` DATETIME(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
    `updated_at` DATETIME(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),

    INDEX `idx_uahs_summary_date_login_count`(`summary_date`, `login_count`),
    INDEX `idx_uahs_summary_date`(`summary_date`),
    INDEX `idx_uahs_user_id`(`user_id`),
    UNIQUE INDEX `uq_uahs_summary_date_user_id`(`summary_date`, `user_id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

package.json

  "dependencies": {
    "@prisma/client": "^3.12.0",
  }
```</div>

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:3
  • Comments:27 (11 by maintainers)

github_iconTop GitHub Comments

2reactions
ulevitskycommented, Sep 9, 2022

It’s not unique to upserts, happens on creates as well.

Here’s a distilled repro based on @pimeys code:

schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model UserActiveHistorySummary {
  summary_date                 DateTime                        @db.Date
  user_id                      String                          @db.VarChar(255)

  @@id([summary_date, user_id]) // or @@unique
}

index.js

import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient({
  log: ["query", "info", "warn", "error"],
})

async function main() {
  const data = await prisma.userActiveHistorySummary.create({
    data: {
      summary_date: "2022-03-29T00:00:00+09:00",
      user_id: "test",
    },
  })

  console.log(data)
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })

1reaction
KnutHelstadcommented, Nov 1, 2022

OK. I can open a new issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

MySQL duplicate entry error even though there is no duplicate ...
When the DML operations are applied, it is possible to encounter a duplicate key entry error (ERROR 1062 (23000): Duplicate entry), even if...
Read more >
How to INSERT If Row Does Not Exist (UPSERT) in MySQL
This means that an INSERT IGNORE statement which contains a duplicate value in a UNIQUE index or PRIMARY KEY field does not produce...
Read more >
13.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be inserted would cause a duplicate value in a UNIQUE...
Read more >
mysql - 1062 Duplicate entry but there are no duplicates?
If you try INSERT a duplicate values for a primary key (or a unique index) you will always get that error. There are...
Read more >
INSERT ON DUPLICATE KEY UPDATE - MariaDB
If more than one unique index is matched, only the first is updated. It is not recommended to use this statement on tables...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found