get drizzle to correctly infer type with limit 1
If you do something simple like this:
Drizzle seems to infer the type of user as an array , in spite of specifying limit(1) which should only return one row from the users table.
What is the best way to get the correct type of user, which should be
18 Replies
add an
.executeTakeFirst()
at the end :-)#limit still returns an array, so the type is correct
not seeing this as an option anywhere in the docs, can you point me to it?
I don't thinkg there is an executeTakeFirst method on a select statement in drizzle
Anyway, drizzle has no way of knowing if your database will return one value or cero values, so the best next thing is to return an array as your driver is doing.
If drizzle were to return an user instead of an array, how would expect its behavior if the array returned from the db is empty? Return null, undefined or throw an error?
Take a look at this very informative thread from one of the drizzle team members: https://x.com/bloberenober/status/1644798759002357762?s=20
Dan (@bloberenober)
A lot of requests we receive about @DrizzleOrm are related to the "convenience" APIs - stuff that is present in a lot of popular ORMs and that, for a lot of people, differentiates "ORMs" from "query builders". Let me share our vision of it and a bit of Drizzle history.
Likes
116
Twitter
Just read it, I understand the approach Drizzle is taking and why they don't provide convenience APIs.
So how would you propose handling this very common use case of needing to return just the one row? Do something like this:
Or would you do something else? I guess that was my original question in the first place, how are people handling this case in their own code?
There are several options, one is the one you just described. Which will be
user | undefined
You could do:
This will be user
, you would have to handle the case when it doesn't find anything and throwsgot it, thanks for your help and sharing the thread
Have you seen the convenience API we now have with drizzle?
The relational query API
Drizzle Queries - DrizzleORM
Drizzle ORM | %s
Yep, I've had a look but for the sake of separating concerns I prefer to only use that for relational queries. I try to keep all non-relational queries using select, insert, etc.
I'm aware that you could use a findFirst() from there but didn't want to use that when I'm not querying relations
sounds good
yes yes, I'm sorry my mindset was on the wrong project (kysely).
In drizzle you can do:
Doesn't this work?
looks nifty ... did you try it ? Don't know if then is only executed if the [] has results
It worked well for me
That's a nice trick, I didn't think of that