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

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>

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 4
  • Comments: 27 (11 by maintainers)

Most upvoted comments

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

OK. I can open a new issue.

Thanks for that clarification @Simonpedro. Although there is a Date in your data, I don’t think that would fit our current theory why Prisma can not retrieve the data it just created. I think you could preemptively already post in https://github.com/prisma/prisma/issues/15264 that you are in the same/similar boat to make sure when we close this issue because we fix the primary key Date problem, your problem still is recorded somewhere. You should be fine just copying your information your shared here into that issue. Thanks!

model shipment_entry {
  client                      String                      @default(dbgenerated("(current_setting('app.client'::text))::character varying(16)")) @db.VarChar(16)
  warehouse                   String                      @default(dbgenerated("(current_setting('app.warehouse'::text))::character varying(16)")) @db.VarChar(16)
  id                          String                      @id(map: "PK_Shipment_Entry__id") @db.VarChar(64)
  notes                       String?
  is_validated                Boolean                     @default(false)
  created_date                DateTime                    @default(now()) @db.Timestamptz(6)
  arrived_date                DateTime?                   @db.Timestamptz(6)
  created_by                  String?                     @default(dbgenerated("(current_setting('app.user'::text))::uuid")) @db.Uuid
  client_warehouse_allocation client_warehouse_allocation @relation(fields: [client, warehouse], references: [client_code, warehouse_code], onDelete: NoAction, onUpdate: NoAction, map: "FK_ShipmentEntry_2_ClientWarehouseAllocation")
  users                       users?                      @relation(fields: [created_by], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_Shipment_Entry__created_by_Users__id")
}

I also have a trigger on my pg db.

create or replace function shipment_entry_custom_id_generator() returns trigger as $$
	begin
		new.id = (select 
					current_setting('app.client') || current_setting('app.warehouse') || 'LPN' || LPAD(cast(count(*) + 1 as varchar(64)),8,'0') as "id"
					from 
						shipment_entry 
					where 
						client = current_setting('app.client')
						and warehouse = current_setting('app.warehouse')
				 );
		return new;
	end
	$$ language plpgsql;

I add it to the same table

create trigger shipment_entry_custom_generator_id_trigger
	before insert on shipment_entry
	for each row
	execute procedure shipment_entry_custom_id_generator(); 

However, if I drop my trigger, the operation succeeds.

Still seeing this with version 4.2.1.