Skip to content

"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

Closed
prisma/prisma-engines
#1823

Description

@some-user123

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

Activity

  1. Cretezy commented on Mar 21, 2021

    @Cretezy
  2. some-user123 commented on Mar 23, 2021

    @some-user123
    Author
  3. assigned and unassigned on Mar 25, 2021
  4. dvins commented on Mar 29, 2021

    @dvins

    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.

  5. darioielardi commented on Apr 6, 2021

    @darioielardi

    We have the exact same use case described above ( optional relation in a multi tenant schema ). Is there any ETA for a fix?

  6. added
    bug/2-confirmed
    and removed on Apr 7, 2021
  7. do4gr commented on Apr 7, 2021

    @do4gr
    Member

    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.

  8. darioielardi commented on Apr 7, 2021

    @darioielardi

    @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:

    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.

  9. added
    kind/bug
    on Apr 7, 2021
  10. added a commit that references this issue on Apr 8, 2021
    c99e15b
  11. added a commit that references this issue on Apr 9, 2021
    7926286
  12. added this to the 2.21.0 milestone on Apr 9, 2021
  13. HialeahLiam commented on Mar 13, 2024

    @HialeahLiam

    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?

  14. janpio commented on Mar 13, 2024

    @janpio
    Contributor

    As the documentation says, this is still true:

    We recommend using the "safe" Input types whenever possible.

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug/2-confirmedkind/bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions