LoginSignup
0
0

Prismaでcreateしたときに身に覚えのないUnique制約エラーが発生した件

Posted at

はじめに

PrismaにてCreateを行った際、UniqueKeyが重複していないのにUnique制約エラーが発生しました。

環境

  • Docker
  • PostgreSQL
  • TypeScript
  • nest.js
  • Table定義
model User {
  id                                         Int        @default(autoincrement())                         
  type                                       Type
  name                                       String

  @@unique(fields: [name, deliveryType])
}

エラーが発生するコード

以下のコードを実行するとエラーが発生する。
DBも確認したが、UniqueKeyの重複はなかった。

export const UserList: User[] = [
  {
    id: 1,
    type: Type.Hoge,
    name: '山田',
  },
  {
    id: 1,
    type: Type.Huga,
    name: '田山',
  },
];


for (const user of UserList) {
   await prisma.user.create({
      data:user
    });
}

原因と解決策

CreateやUpsertするときにIDを指定すると、idの自動インクリメントが狂います。
https://github.com/prisma/prisma/discussions/5256

idを指定しないよう修正したのが以下です。

export const UserList: User[] = [
  {
    id: 1,
    type: Type.Hoge,
    name: '山田',
  },
  {
    id: 1,
    type: Type.Huga,
    name: '田山',
  },
];


for (const user of UserList) {
await prisma.user.create({
  data: {
    name: user.name,
    deliveryType: user.type,
  },
});
}

おわり

上記により、手動での検証では問題がないのに自動テストの時だけエラーとなる現象が発生していました。
挙動が変わることを知らず、はまりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0