prisma nested writes throw unknown args - postgresql

I have the shorten schema like that:
model PATIENT {
patient_id Int #id #default(autoincrement())
patient_name String
patient_identity_card BigInt #unique
password String
wallet_id Int?
birthday DateTime
address String
status_id Int
gender String #default("Nam")
phone String #default("0935438280")
current_treatment_place_id Int
avatar_url String?
treatment_place TREATMENT_PLACE #relation(fields: [current_treatment_place_id], references: [place_id])
status PATIENT_STATUS #relation(fields: [status_id], references: [status_id])
card CART?
patient_passive_contact PATIENT_CONTACT[] #relation("ActiveContact_referredToPatient")
patient_active_contact PATIENT_CONTACT[] #relation("PassiveContact_referredToPatient")
BE_MANAGED_HISTORY BE_MANAGED_HISTORY[]
}
model BE_MANAGED_HISTORY {
place_id Int
patient_id Int
time DateTime
status_id Int
status PATIENT_STATUS #relation(fields: [status_id], references: [status_id])
patient PATIENT #relation(fields: [patient_id], references: [patient_id])
place TREATMENT_PLACE #relation(fields: [place_id], references: [place_id])
change_type_id Int
change_type CHANGE_MANAGED_HISTORY_TYPE #relation(fields: [change_type_id], references: [type_id])
##id([place_id, patient_id, time])
}
I want to create a BE_MANAGED_HISTORY record and through it create a PATIENT record with needed information. The nested writes below:
const res = await prisma.BE_MANAGED_HISTORY.create({
data: {
place_id: treatmentPlaceId,
time: new Date(startDate),
status_id: patientStatus,
change_type_id: 1,
patient: {
create: {
patient_name: patientName,
gender,
birthday: new Date(birthday),
patient_identity_card: identity,
password: hashedPassword,
phone,
address,
status_id: patientStatus,
current_treatment_place_id: treatmentPlaceId,
avatar_url: avatarUrl,
}
}
},
})
But prisma throws an error:
Unknown arg patient in data.patient for type BE_MANAGED_HISTORYUncheckedCreateInput. Did you mean patient_id?
Argument patient_id for data.patient_id is missing.
So can I create an beManagedHistory and create an patient inside nested writes?

We have to create a PATIENT record first, and nested in it creating a BE_MANAGED_HISTORY record.

Related

Unique constraint failed on the constraint: `Bug_authorId_key`

I am trying to implement a relation querie with Prisma ORM but this error does not allow.
My system consists in a bugtracker, where the user can report bugs. So I'm linking the User with the bugs. When I try to create a new data this error appears: "Unique constraint failed on the constraint: Bug_authorId_key"
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model User {
id Int #id #default(autoincrement())
name String
email String #unique
password String
role String #default("User")
bugs Bug[]
teamId Int?
team Team? #relation(fields: [teamId], references: [id])
}
model Team {
id Int #id #default(autoincrement())
name String
users User[]
admins Admin[]
}
model Admin {
id Int #id #default(autoincrement())
name String
email String #unique
password String
role String #default("Admin")
teamId Int?
team Team? #relation(fields: [teamId], references: [id])
}
model Bug {
id Int #id #default(autoincrement())
title String
description String
status String
authorId Int
author User #relation(fields: [authorId], references: [id])
}
const bug = await prisma.bug.create({
data: {
title: req.body.title,
status: req.body.status,
description: req.body.description,
author: {
connect: {id: req.body.authorId}
}
}
})

Delete lots of entries results in a timeout

When I run:
const results = await prisma.result.deleteMany({
where: {
typebotId: 'ckzqqer3j002509l3np5x3v2y',
},
})
It runs forever and then times out. (I'm expecting it to delete more than 6.000 results)
Here is my prisma schema:
model Typebot {
id String #id #default(cuid())
createdAt DateTime #default(now())
updatedAt DateTime #default(now()) #updatedAt
icon String?
name String
publishedTypebotId String?
publishedTypebot PublicTypebot?
results Result[]
folderId String?
folder DashboardFolder? #relation(fields: [folderId], references: [id])
groups Json
variables Json[]
edges Json
theme Json
settings Json
publicId String? #unique
customDomain String? #unique
collaborators CollaboratorsOnTypebots[]
invitations Invitation[]
webhooks Webhook[]
workspaceId String
workspace Workspace #relation(fields: [workspaceId], references: [id], onDelete: Cascade)
}
model Result {
id String #id #default(cuid())
createdAt DateTime #default(now())
updatedAt DateTime #default(now()) #updatedAt
typebotId String
typebot Typebot #relation(fields: [typebotId], references: [id], onDelete: Cascade)
answers Answer[]
variables Json[]
isCompleted Boolean
logs Log[]
}
model Log {
id String #id #default(cuid())
createdAt DateTime #default(now())
resultId String
result Result #relation(fields: [resultId], references: [id], onDelete: Cascade)
status String
description String
details String?
}
model Answer {
createdAt DateTime #default(now())
resultId String
result Result #relation(fields: [resultId], references: [id], onDelete: Cascade)
blockId String
groupId String
variableId String?
content String
##unique([resultId, blockId, groupId])
}
Here are the logs:
prisma:info Starting a postgresql pool with 21 connections in PgBouncer mode.
Query: BEGIN
Params: []
Duration: 10ms
Query: DEALLOCATE ALL
Params: []
Duration: 11ms
Query: SELECT "public"."Result"."id" FROM "public"."Result" WHERE "public"."Result"."typebotId" = $1 OFFSET $2
Params: ["ckzqqer3j002509l3np5x3v2y",0]
Duration: 159ms
Query: SELECT "public"."Result"."id" FROM "public"."Result" WHERE "public"."Result"."typebotId" = $1
Params: ["ckzqqer3j002509l3np5x3v2y"]
Duration: 129ms
Query: DELETE FROM "public"."Result" WHERE "public"."Result"."id" IN ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$70,$71,$72,$73,$74,$75,$7 [...] 0","cl4frxblq433409lb3l95czep","cl4frgs4r487909ks862a3vf2","cl4frww25009609mpgbv0ntqf","cl4frgs0u487309ks3ugw514j","cl4frgsvn097909k0epcxy9me","cl4frhil4108309k0pop31n8p","cl4frwwa1313909k0vfb9tpbo","cl4frgx5l282409lbvdk1gwz1","cl4frgzc2100209k0k8ve0471","cl4frx4pi429709lbhpekm640","cl4frhu63294109lbbxsclv2l","cl4frjhk9307309lbm8e02obi","cl4frx5nl643709kst8fmob1e","cl4frx984432009lbmp3sxqd6","cl4frkjiq142909k0n37881vv","cl4frjihk310109lb6tnne9jc","cl4frxffr436209lbkaj3gh9f","cl4frkkd7145209k051m5bflf"]
Duration: 120041ms
Query: ROLLBACK
Params: []
Duration: 11ms
How can I optimize this query?
I also tried:
const results =
await prisma.$queryRaw`DELETE FROM "Result" WHERE "Result"."typebotId"='ckzqqer3j002509l3np5x3v2y'`
It also times out 😔

Upsert: Help in finalizing the command, gettings two errors

My models:
model Show {
id Int #id #default(autoincrement())
tvmazeId Int
name String
type Type #relation(fields: [typeId], references: id)
typeId Int
language Language #relation(fields: [languageId], references: id)
languageId Int
genres GenresOnShows[]
status Status #relation(fields: [statusId], references: id)
statusId Int
runtime Int?
premiered DateTime?
ended DateTime?
network Network? #relation(fields: [networkId], references: id)
country Country? #relation(fields: [countryId], references: id)
countryId Int
networkId Int
webchannel Webchannel? #relation(fields: [webchannelId], references: id)
webchannelId Int
tvrageId String? #unique
thetvdbId String? #unique
imdbId String? #unique
imageMed String? #unique
imageOrig String? #unique
summary String
}
model Status {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Type {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Language {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Country {
id Int #id #default(autoincrement())
name String #unique
code String #unique
timezone String
shows Show[]
}
model Network {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Webchannel {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Genre {
id Int #id #default(autoincrement())
name String #unique
shows GenresOnShows[]
}
model GenresOnShows {
show Show #relation(fields: [showId], references: [id])
showId Int
genre Genre #relation(fields: [genreId], references: [id])
genreId Int
##id([showId, genreId])
}
What i try is getting show information from an api and populate the database. The problem is, that i need to populate related tables (like network, country, etc.) in the same action.
Here is how i get for example the country:
const country = await prisma.country.upsert(
{
where: {
name: show["network"]["country"]["name"]
},
update: {},
create: {
name: show["network"]["country"]["name"],
code: show["network"]["country"]["code"],
timezone: show["network"]["country"]["timezone"],
}
}
)
and heres the statement i use to try to update the show:
const showInDb = await prisma.show.upsert(
{
where: {
tvmazeId: show["id"]
},
update: {
typeId: {connect: {type}},
languageId: {connect: {language}},
genreConnectOrCreate: genreConnectOrCreate,
statusId: {connect: {status}},
networkId: {connect: {network}},
countryId: {connect: {country}},
webchannelId: {connect: {webchannel}},
name: show["name"],
runtime: parseInt(show["runtime"]),
premiered: new Date(show["premiered"]),
ended: new Date(show["ended"]),
tvrageId: show["externals"]["tvrage"].toString(),
tvdbId: show["externals"]["thetvdb"],
imdbId: show["externals"]["imdb"],
tvmazeId: show["id"],
imageMed: show["image"]["medium"],
imageOrig: show["image"]["original"],
summary: show["summary"]
},
create: {
typeId: {connect: {type}},
languageId: {connect: {language}},
genreConnectOrCreate: genreConnectOrCreate,
statusId: {connect: {status}},
networkId: {connect: {network}},
countryId: {connect: {country}},
webchannelId: webchannel,
name: show["name"],
runtime: parseInt(show["runtime"]),
premiered: new Date(show["premiered"]),
ended: new Date(show["ended"]),
tvmazeId: show["id"],
tvrageId: show["externals"]["tvrage"].toString(),
tvdbId: show["externals"]["thetvdb"],
imdbId: show["externals"]["imdb"],
imageMed: show["image"]["medium"],
imageOrig: show["image"]["original"],
summary: show["summary"]
}
}
)
I tried with the ID (for example countryId aswell as country itself). The error i get when using countryId is:
Unknown arg countryId in update.countryId for type ShowUpdateInput. Did you mean country?
if i use country:
Unknown arg country in update.country.connect.country for type CountryWhereUniqueInput. Did you mean code?
I also tried to privde the country without the connect like so:
country: country,
what is the correct way to do that?

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?

prisma2 how to relate one-to-many and many-to-one?

I need some help to understqnd how to set my data modelisation.
What i'm trying to do is :
Reference a group ID in User model. A user can only be in one group, this is what i've done below.
Reference in Group Model all users that are inside a group. This is what I need help with.
model User {
id String #id #default(uuid())
email String #unique
role Role #default(USER)
group Group? #relation(fields: [group_id], references: [id], onDelete: SetNull)
group_id String
created_at DateTime #default(now())
updated_at DateTime #updatedAt
##map("user")
}
model Group {
id String #id #default(uuid())
name String
users User[]
created_at DateTime #default(now())
updated_at DateTime #updatedAt
deleted Boolean #default(false)
##map("group")
}
How can I make this list of User when I already have users User[] for the relation in User model ?
(BTW i've read the doc but i'm totally lost...)
I think your code is correct, you can use prisma-client to test
This is an example of this relation
model Agents {
id Int #id #default(autoincrement()) #db.UnsignedInt
name String? #db.VarChar(255)
owner String? #db.VarChar(255)
address String? #db.Text
lat String? #db.VarChar(10)
lng String? #db.VarChar(10)
tel String? #db.VarChar(13)
mobile String? #db.VarChar(11)
workTime String? #db.VarChar(255)
province Provinces #relation(fields: [provinceId], references: [id])
provinceId Int #db.UnsignedInt
createDateTime DateTime #default(now()) #db.Timestamp(0)
updateDateTime DateTime? #db.Timestamp(0)
##index([provinceId], name: "provinceId")
##map(name: "agents")
}
model Provinces {
id Int #id #default(autoincrement()) #db.UnsignedInt
name String? #db.VarChar(255)
coords String? #db.Text
createDateTime DateTime #default(now()) #db.Timestamp(0)
updateDateTime DateTime? #db.Timestamp(0)
agents Agents[]
##map(name: "provinces")
}