prisma-client-py icon indicating copy to clipboard operation
prisma-client-py copied to clipboard

Use strongly typed IDs

Open RobertCraigie opened this issue 4 years ago • 1 comments

Problem

Currently the following code (given that user and post have the same type for their ID field) will type check but is an obvious logical error:

post = await client.post.find_first()
assert post is not None
user = await client.user.find_unique(
    where={
        'id': post.id,
    },
)

Suggested solution

ID types should make use of NewType to show that they are distinct from the base type.

This would, however, make working with non-autogenerated IDs more annoying as you would have to explicitly wrap the ID value with the type, for example:

from prisma.types import UserID

user = await client.user.find_unique(
    where={
        'id': UserID('foo')
    },
)

RobertCraigie avatar Nov 05 '21 13:11 RobertCraigie

My 0.02 here:

(1)

This would, however, make working with non-autogenerated IDs more annoying as you would have to explicitly wrap the ID value with the type, for example: (...)

From my experience (i've written an internal framework like this), I also feared that people would find it annoying, but most ended up appreciating it. Even though it involves a little bit of boilerplate – it does make it clear what's going on.

(2)

I would also recommend to use a generic type for it. E.g. ID[User], ID[Post], etc. Then you can use stuff like ID[Any] / ID[BaseModel] / ID[object] when convenient. I worked on a very large codebase like this and it worked really well.

kkom avatar Jul 22 '23 19:07 kkom