[BUG]: Incorrect type when using a condition in relational query
What version of drizzle-orm are you using?
0.27.0
What version of drizzle-kit are you using?
0.19.1
Describe the Bug
The type from this query:
should be:
But instead, it's this:
Expected behavior
No response
Environment & setup
No response
This is better, but the desired type here is a possible undefined.
I'm not sure if this is a bug or a fr, I searched the docs for this, but found none.
It's a type bug, will fix.
While we wait for the official fix, I've come up with a temporary workaround for the issue. This should be useful if you're encountering the same problem.
First, copy & store this type somewhere:
/**
* @param T The type of the result of the query.
* @param Table The drizzle schema of the table that is being joined
* @param K The key of the relation in the results
*/
export type FixQCondition<
T extends Array<T[number]>,
Table extends AnyTable,
K extends keyof T[number],
Bad = Table["_"]["model"]["select"],
Data = (T[number][K] extends Array<unknown> ? T[number][K][number] : never)
> = {
[TK in keyof T[number]]: TK extends K
? (Data extends Bad ? never : Data)[] | undefined
: T[number][TK];
}[];
Then you can use it like this:
const result = db.query.room.findMany({"Your conditional query" });
type Corrected = FixQCondition<typeof result, typeof children, "children">;
return result as Corrected;
For findFirst:
const result = db.query.room.findFirst({"Your conditional query" });
type Corrected = FixQCondition<typeof result[], typeof children, "children">[number]
return result as Corrected;
Caveat: If you have multiple conditional joins, it will get even more messy:
type FixChildren = FixQCondition<typeof result, typeof children, "children">;
type FixUpdates = FixQCondition<FixChildren, typeof updates, "updates">;
type FixTasks = FixQCondition<FixUpdates, typeof tasks, "tasks">;
Issue still exists on v0.28.2, temporary fix still works.
I think this bug should be fixed ASAP, it affects a popular use case of an ORM. And it is still here after more than half of year!
still around :(
it gives me wrong types when I try to use a conditional expression in the "with" property (relations)
Version: drizzle-orm 0.42.0
We're also having a type problem when conditionally including a related entity:
const pet = await db.query.pets.findFirst({
with: {
...(shouldIncludeOwner && { owner: true }),
},
});
if (pet) {
const owner = pet.owner;
// ^ owner should be inferred as `typeof Owner | undefined` but its inferred as `typeof Owner`
}
I can confirm this bug is still around in [email protected];
const enrichedComments =
await db.query.comments.findMany({
with: {
author: currentUserId
? {
with: {
followers: {
where: eq(follows.followerId, currentUserId),
},
},
}
: true,
},
where: eq(comments.articleId, article.id),
orderBy: (comments, { desc }) => [desc(comments.createdAt)],
});
const firstComment = enrichedComments[0];
if (firstComment) {
const followers = firstComment.author?.followers;
}
The type for followers is:
const followers: {
createdAt: Date;
updatedAt: Date;
followerId: string;
followedId: string;
}[]
Whereas it should be:
const followers: {
createdAt: Date;
updatedAt: Date;
followerId: string;
followedId: string;
}[] | undefined
Schema:
import { relations } from "drizzle-orm";
import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { articles } from "@/articles/articles.schema";
import { comments } from "@/comments/comments.schema";
import { follows } from "@/profiles/profiles.schema";
export const users = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom(),
email: text("email").notNull().unique(),
username: text("username").unique().notNull(),
bio: text("bio"),
image: text("image"),
password: text("password").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at")
.notNull()
.defaultNow()
.$onUpdate(() => new Date()),
});
export const usersRelations = relations(users, ({ many }) => ({
// These are the people who FOLLOW me
followers: many(follows, {
relationName: "following", // I am the followedId in those rows
}),
// These are the people I FOLLOW
following: many(follows, {
relationName: "followers", // I am the followerId in those rows
}),
comments: many(comments),
articles: many(articles),
}));
Funny enough, this is also an issue with Prisma:
https://github.com/prisma/prisma/issues/20871 https://github.com/prisma/prisma/issues/20816#issuecomment-1873448080
This is still a bug in RQBv2 (@[email protected])
Hey everyone!
I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.
I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!
We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.
First branch is drizzle-kit rewrite
All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439
As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.
What's left here:
- We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the
sridissue here as well). - We are finishing commutative migrations for all dialects.
- We are finishing up the command, so the migration flow will be as simple as
drizzle-kit upfor you.
Where it brings us:
- We are getting drizzle-kit into a new good shape where we can call it
[email protected]!
Timeline:
- We need ~2 weeks to finish all of the above and send this branch to beta for testing.
Second big branch is a complex one with several HUGE updates
- Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)
TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k
You can read more about it here.
What's left here:
- We have 1 issue with TS that is already in progress of being fixed. The issue and Post about fixing.
Where it brings us:
- We are getting drizzle-orm into a new good shape where we can call it
[email protected]!
Breaking changes:
- We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.
Third branch is adding support for CockroachDB and MSSQL dialects
Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.
Summary
All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.
We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).
We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.
Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!
Timelines
We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!