You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
"Error validating: The relation field ... uses the scalar fields .... At least one of those fields is required. Hence the relation field must be required as well." is too restrictive when using composite keys #6042
I have to say first, that I really fell in love with Prisma. it is such an awesome tool, thanks! 🙏
Bug description
When using composite keys the existence of relation fields is too strict. It can be optional if one of the key fields is optional - not all of them. I can better explain by example.
How to reproduce
This schema is working:
model Object {
objectId Int @id
name String
parentId Int?
parent Object? @relation(fields: [parentId], references: [objectId])
}
parentId is optional and so is parent.
However my data model is more complex and there is no single unique column:
model ObjectCompositeKey {
clientId Int
objectId Int
name String
parentId Int?
parent ObjectCompositeKey? @relation(fields: [clientId, parentId], references: [clientId, objectId])
@@id([clientId, objectId])
}
This schema is not working and I receive the error:
Error validating: The relation field `parent` uses the scalar fields clientId, parentId. At least one of those fields is required. Hence the relation field must be required as well.
Expected behavior
However, from my point of view the error is wrong. As soon as one of the scalar fields is optional, the relation field has to be optional as well.
It works if a make the parent relation field required, but that's not what I as parentId is optional and it would prevent me from inserting rows without parent.
Environment & setup
prisma : 2.18.0
@prisma/client : 2.18.0
Current platform : windows
Query Engine : query-engine da6fafb57b24e0b61ca20960c64e2d41f9e8cff1 (at ..\node_modules\@prisma\engines\query-engine-windows.exe)
Migration Engine : migration-engine-cli da6fafb57b24e0b61ca20960c64e2d41f9e8cff1 (at ..\node_modules\@prisma\engines\migration-engine-windows.exe)
Introspection Engine : introspection-core da6fafb57b24e0b61ca20960c64e2d41f9e8cff1 (at ..\node_modules\@prisma\engines\introspection-engine-windows.exe)
Format Binary : prisma-fmt da6fafb57b24e0b61ca20960c64e2d41f9e8cff1 (at ..\node_modules\@prisma\engines\prisma-fmt-windows.exe)
Studio : 0.356.0
Preview Features : createMany, groupBy
Reacted by David Vins, Dario Ielardi and Nick Schmitt
We just ran into this as well today and not sure why it's tagged as discussion and not acknowledged as a bug.
It incorrectly prevents building optional relationships with compound keys. For example, in a multi-tenant database use case , that ensures tenant scope in all relationships, e.g. someEntity SomeEntity? @relation(fields:[tenantId, someEntityId], references: [tenantId, some EntityId] throws a schema error.
Herein tenantId is a required field in both entity models, but a relationship existing between them is completely optional. But this throws an error when trying to use SomeEntity? when someEntityId is optional on the current entity model.
Reacted by Tom Carchrae, some-user123, Dario Ielardi, Luiz Felipe Marinho and JeanPSF
Thanks for reporting and commenting on this issue.
The relationfield being required when at least one of scalar fields underlying the foreign key is required stems from a time when the scalar fields were not exposed and could not separately be written to. When that was the case not writing the relation meant you would get a runtime error when creating a row since the required field was not set. Unfortunately, that also means you got an error if you read and the relation was not set (because a non-client source wrote to the db).
Since we now expose the scalar fields and allow them to be written directly this is no longer the case. We can now switch the inference logic to what you proposed: If at least one underlying scalar field is optional, the whole relation becomes optional. That means no more errors if the relation is not set. And when writing you do not need to specify the relationfield (and thereby valid values for all underlying scalars) but you can instead write to only the required underlying scalars using the uncheckedScalarInputs feature.
@do4gr thank you for the accurate description. I'm glad there's nothing at this point preventing this kind of optional relations, since that's exactly what we need right now. I'd also be willing to open a PR and work on the fix myself.
From what I can see, this is the code we need to change:
If I correctly understood what you said, we now need to enforce the relation field to be optional if at least one of the relations fields is optional. Something like:
let at_least_one_underlying_field_is_optional = rel_info
.fields.iter().filter_map(|base_field| model.find_scalar_field(&base_field)).any(|f| !f.is_required());if at_least_one_underlying_field_is_optional && field.is_required(){
errors.push_error(DatamodelError::new_validation_error(&format!("The relation field `{}` uses the scalar fields {}. At least one of those fields is optional. Hence the relation field must be optional as well.",&field.name,
rel_info.fields.join(", ")),
ast_field.span));}
Also, we should replace the relative test with a new appropriate one.
If you can confirm this is all correct and there's nothing more to do I'll open a PR asap. Thank you for your time.
Thanks for reporting and commenting on this issue.
The relationfield being required when at least one of scalar fields underlying the foreign key is required stems from a time when the scalar fields were not exposed and could not separately be written to. When that was the case not writing the relation meant you would get a runtime error when creating a row since the required field was not set. Unfortunately, that also means you got an error if you read and the relation was not set (because a non-client source wrote to the db).
Since we now expose the scalar fields and allow them to be written directly this is no longer the case. We can now switch the inference logic to what you proposed: If at least one underlying scalar field is optional, the whole relation becomes optional. That means no more errors if the relation is not set. And when writing you do not need to specify the relationfield (and thereby valid values for all underlying scalars) but you can instead write to only the required underlying scalars using the uncheckedScalarInputs feature.
I'm candidating this for planning.
Since Prisma now allows directly writing to relation scalar fields, does that mean this section of the docs is outdated: "perform some operations that Prisma Client considers "unsafe", like directly writing relation scalar fields"
Or does Prisma still recommend NOT writing to these fields? If that's the case, why so?
Activity
Cretezy commentedon Mar 21, 2021
some-user123 commentedon Mar 23, 2021
dvins commentedon Mar 29, 2021
We just ran into this as well today and not sure why it's tagged as discussion and not acknowledged as a bug.
It incorrectly prevents building optional relationships with compound keys. For example, in a multi-tenant database use case , that ensures tenant scope in all relationships, e.g.
someEntity SomeEntity? @relation(fields:[tenantId, someEntityId], references: [tenantId, some EntityId]throws a schema error.Herein
tenantIdis a required field in both entity models, but a relationship existing between them is completely optional. But this throws an error when trying to useSomeEntity?whensomeEntityIdis optional on the current entity model.darioielardi commentedon Apr 6, 2021
We have the exact same use case described above ( optional relation in a multi tenant schema ). Is there any ETA for a fix?
do4gr commentedon Apr 7, 2021
Thanks for reporting and commenting on this issue.
The relationfield being required when at least one of scalar fields underlying the foreign key is required stems from a time when the scalar fields were not exposed and could not separately be written to. When that was the case not writing the relation meant you would get a runtime error when creating a row since the required field was not set. Unfortunately, that also means you got an error if you read and the relation was not set (because a non-client source wrote to the db).
Since we now expose the scalar fields and allow them to be written directly this is no longer the case. We can now switch the inference logic to what you proposed: If at least one underlying scalar field is optional, the whole relation becomes optional. That means no more errors if the relation is not set. And when writing you do not need to specify the relationfield (and thereby valid values for all underlying scalars) but you can instead write to only the required underlying scalars using the uncheckedScalarInputs feature.
I'm candidating this for planning.
darioielardi commentedon Apr 7, 2021
@do4gr thank you for the accurate description. I'm glad there's nothing at this point preventing this kind of optional relations, since that's exactly what we need right now. I'd also be willing to open a PR and work on the fix myself.
From what I can see, this is the code we need to change:
https://github.com/prisma/prisma-engines/blob/81578a019b5444a2c4eb90633774c488eeb6a943/libs/datamodel/core/src/transform/ast_to_dml/validate.rs#L543-L547
https://github.com/prisma/prisma-engines/blob/81578a019b5444a2c4eb90633774c488eeb6a943/libs/datamodel/core/src/transform/ast_to_dml/validate.rs#L573-582
If I correctly understood what you said, we now need to enforce the relation field to be optional if at least one of the relations fields is optional. Something like:
Also, we should replace the relative test with a new appropriate one.
If you can confirm this is all correct and there's nothing more to do I'll open a PR asap. Thank you for your time.
fixes prisma/orm#6042
Optional compound relations (#1823)
HialeahLiam commentedon Mar 13, 2024
Since Prisma now allows directly writing to relation scalar fields, does that mean this section of the docs is outdated: "perform some operations that Prisma Client considers "unsafe", like directly writing relation scalar fields"
Or does Prisma still recommend NOT writing to these fields? If that's the case, why so?
janpio commentedon Mar 13, 2024
As the documentation says, this is still true:
https://www.prisma.io/docs/orm/prisma-client/type-safety#generated-uncheckedinput-types:~:text=We%20recommend%20using%20the%20%22safe%22%20Input%20types%20whenever%20possible.
Using the "safe" APIs adds more checks and validations, and hence ensures data integrity better and can return better error messages.