Brendonovich / prisma-client-rust

Type-safe database access for Rust
https://prisma.brendonovich.dev
Apache License 2.0
1.76k stars 104 forks source link

Required fields referenced by optional relations are wrongly removed from create #282

Closed SamCullin closed 1 year ago

SamCullin commented 1 year ago

Summary

There seems to be an issue with the generated SDK when a field is used in a relation that is not required.

Example

Schema

model project {
    // Fields
    name       String   @unique
    main_workspace_name String?

    // Relations
    main_workspace workspace? @relation("primary_workspace", fields: [name, main_workspace_name], references: [project_name, name])
    workspaces workspace[]

    @@unique([name, main_workspace_name])
}

model workspace {
    // Fields
    name       String   @default("default")
    project_name String

    // Relations
    project      project @relation(fields: [project_name], references: [name], onDelete: Cascade)
    is_primary_workspace project? @relation("primary_workspace")

    @@unique([project_name, name])

}

Outputs

This will generate the incorrect .project().create(...) function signature.

pub fn create(self, _params: Vec<SetParam>) -> Create<'a>

If main_workspace_name and main_workspace are made required the generated signature is as follows.

pub fn create(self, main_workspace: super::workspace::UniqueWhereParam, _params: Vec<SetParam>) -> Create<'a>

Result

In both cases, there is no way to set the required field of name without using the vec![Set] arguments but this throws validation errors.

Workaround

The current workaround for anyone running into this issue is to create

let project = prisma::project::create_unchecked(...);
let created = client.project().create_many(vec![project]).exec().await?;
let project = client.project().find_unque(....).exec().await?;

note: this will only work for people who have a way to create a unique query from the data they used in the

Discord chat record

Brendonovich commented 1 year ago

This should be fixed on rev = "f8ec79ad532b0bbca0d90dcaa6ecc895c82b87c3"

Brendonovich commented 1 year ago

Out of curiosity I plugged this schema into prisma client JS and I got this

image

Turns out that the JS client would actually give you the same problem if you wanted to use the checked version. I'm not sure if that's a bug or a feature, but I'd like to keep consistency. I think I'll add a create_unchecked method that's similar to the create_many you're doing. EDIT: implemented in rev = "3d1451ac4036b13ed4590a08696692a4d2dbbc14"