Prisma: Model with three unique index fields referencing optional fields
I got a question regarding unique indexes with optional values. I have a schema like this:
model Thread {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
body String
user User @relation(fields: [userId], references: [id])
userId Int
likes Like[] @relation("ThreadsOnLikes")
}
model Like {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id])
userId Int
thread Thread? @relation("ThreadsOnLikes", fields: [threadId], references: [id])
threadId Int?
comment Comment? @relation("CommentsOnLikes", fields: [commentId], references: [id])
commentId Int?
@@unique([userId, threadId, commentId])
}
And inside a resolver I want to for example delete a like from a user for a specific threadId like so:
await db.thread.update({
where: { id: input.id },
data: {
likes: {
delete: {
userId_threadId_commentId: { userId: session.userId, threadId: input.id },
},
}
}
})
But when I try to execute that mutation, prisma throws the following error:
Argument commentId for data.likes.delete.userId_threadId_commentId.commentId is missing.
When I add it to the delete argument with , commentId: null it states this error:
Argument commentId: Got invalid value null on prisma.updateOneThread. Provided null, expected Int.
Although inside the database the comment_id field is actually null . Is this a bug or how is this fixable?
From the docs:
All fields that make up the unique constraint must be mandatory fields. The following model is not valid because id could be null:
model User {
firstname Int
lastname Int
id Int?
@@unique([firstname, lastname, id])
}
The reason for this behavior is that all connectors consider null values to be distinct, which means that two rows that look identical are considered unique:
firstname | lastname | id
-----------+----------+------
John | Smith | null
John | Smith | null
I am not sure why Prisma is unable to validate schema beforehand in "compile time", maybe it is a bug, so I suggest you to maybe create an issue on Github?