Hello! Wondering if anybody can help me with an is...
# orm-help
j
Hello! Wondering if anybody can help me with an issue I've been struggling with. I have an
image
table that has a many to many relationship with both with
users
and
figures
. What I'm trying to accomplish is create those 2 resources with images attached without duplicating image entries. If I can succeed in getting
connectOrCreate
to work that would probably be what I need. As part of my experimenting I created a unique field
path_hash
on
image
that tries to uniquely identify an image using an md5 hash of the path (since I don't know the id of a potentially pre-existing image as I'm creating it) Whenever I'm creating a would-be duplicate I get this:
Copy code
Running seed command `ts-node --compiler-options {"module":"CommonJS"} prisma/seed.ts` ...
PrismaClientKnownRequestError: 
Invalid `prisma.user.upsert()` invocation:
  Unique constraint failed on the constraint: `PRIMARY`
at RequestHandler.handleRequestError [...removed file path]
code: 'P2002',
  clientVersion: '4.1.1',
  meta: { target: 'PRIMARY' }
Any ideas? I don't wanna make too much noise in the channel so I can add my models/queries in thread replies if needed
👀 1
query:
Copy code
const user = await prisma.user.upsert({
      where: {
        username,
      },
      create: {
        username,
        about,
        images: {
          create: userImages.map((image) => ({
            is_avatar: image.avatar,
            is_banner: image.banner,
            image: {
              connectOrCreate: {
                where: {
                  path_hash: image.pathHash,
                },
                create: {
                  path: image.path,
                  path_hash: image.pathHash,
                  alt: image.alt,
                  description: image.description,
                  uploaded_by_id: undefined,
                },
              },
            },
          })),
        },
      },
      update: {
        about,
        images: {
          create: userImages.map((image) => ({
            is_avatar: image.avatar,
            is_banner: image.banner,
            image: {
              connectOrCreate: {
                where: {
                  path_hash: image.pathHash,
                },
                create: {
                  path: image.path,
                  path_hash: image.pathHash,
                  alt: image.alt,
                  description: image.description,
                  uploaded_by_id: undefined,
                },
              },
            },
          })),
        },
      },
    });
User:
Copy code
model user {
  id                Int           @id @default(autoincrement())
  username          String        @unique(map: "username") @db.VarChar(255)
  about             String?       @db.Text
  created_at        DateTime?     @default(dbgenerated("(now())")) @db.DateTime(0)
  updated_at        DateTime?     @default(dbgenerated("(now())")) @db.DateTime(0)
  comments          comment[]
  figures           figure_user[]
  figures_submitted figure[]
  images            user_image[]
  image_uploads     image[]
}
user_image: (with my weird solution to avatar/banner, having each id on user with FK to image was causing problems in my schema format)
Copy code
model user_image {
  image_id  Int
  user_id   Int
  image     image   @relation(fields: [image_id], references: [id])
  user      user    @relation(fields: [user_id], references: [id])
  is_avatar Boolean
  is_banner Boolean

  @@id([image_id, user_id])
}
image:
Copy code
model image {
  id             Int            @id @default(autoincrement())
  description    String?        @db.VarChar(255)
  path           String         @db.VarChar(255)
  path_hash      String         @unique(map: "hash") @db.Char(32)
  alt            String?        @db.VarChar(255)
  created_at     DateTime?      @default(dbgenerated("(now())")) @db.DateTime(0)
  updated_at     DateTime?      @default(dbgenerated("(now())")) @db.DateTime(0)
  users          user_image[]
  figure_image   figure_image[]
  uploaded_by_id Int?
  uploaded_by    user?          @relation(fields: [uploaded_by_id], references: [id])
}
a
Hey there 👋, That seems unexpected! Would you mind creating a small reproduction repository with sample data so I can recreate this?
j
Hey there, thanks for looking at this. Let me see if I can do that
Ok I managed to repro in a smaller repo with just those tables.
.env.example
is set up for the default dockerhub mysql image with user root, port 13306 and db name: my-db •
npm i
•
npx prisma db push
•
npx prisma db seed
x 2 should trigger the error
a
I got it to work by using
connectOrCreate
for the
images
model instead of
create
so that the query doesn’t try to re-create existing
user_images
after the initial seed. That’s where the
PRIMARY
constraint error was coming from. This means you will also need to pass in the user id to your query in order to specify the correct composite id for the
user_images
.
Copy code
const user = await prisma.user.upsert({
      where: {
        username
      },
      create: {
        username,
        about,
        images: {
          connectOrCreate: userImages.map((image) => ({
            where: {
              image_id_user_id: {
                image_id: image.id,
                user_id: 1
              }
            },
            create: {
              is_avatar: image.avatar,
              is_banner: image.banner,
              image: {
                connectOrCreate: {
                  where: {
                    path_hash: image.pathHash
                  },
                  create: {
                    path: image.path,
                    path_hash: image.pathHash,
                    alt: image.alt,
                    description: image.description,
                    uploaded_by_id: undefined
                  }
                }
              }
            }
          }))
        }
      },
      update: {
        about,
        images: {
          connectOrCreate: userImages.map((image) => ({
            where: {
              image_id_user_id: {
                image_id: image.id,
                user_id: 1
              }
            },
            create: {
              is_avatar: image.avatar,
              is_banner: image.banner,
              image: {
                connectOrCreate: {
                  where: {
                    path_hash: image.pathHash
                  },
                  create: {
                    path: image.path,
                    path_hash: image.pathHash,
                    alt: image.alt,
                    description: image.description,
                    uploaded_by_id: undefined
                  }
                }
              }
            }
          }))
        }
      }
    })
j
Hey thanks a lot, I really appreciate you taking the time to help on this. The only issue I have remaining is that I don't have the ID when creating a user, only when updating. Does that mean I would need to abandon creating users with images at the same time and rather split it into 2 queries (create user then add images)?
a
You should be able to add a compound unique constraint between the
image_id
and the
username
that will still allow you to use
connectOrCreate
. That means you would have to store the
username
on the
user_image
model as well.
Copy code
model user_image {
  image_id  Int
  user_id   Int
  image     image   @relation(fields: [image_id], references: [id])
  user      user    @relation(fields: [user_id], references: [id])
  username  String
  is_avatar Boolean
  is_banner Boolean

  @@id([image_id, user_id])
  @@unique([image_id, username])
}