Infer type for relational query

Is there anyway to infer the type of a relational queries result? For example if I have a user who makes posts which has comments. I have a relational query which gets me all my users, their posts and their comments nested. Is there a way to infer that type? Currently constructing the type myself from the tables in the schema.
mcgrealife
mcgrealifeβ€’356d ago
@Dbeg I have achieved this by moving the query inside of a function, then using typescript's ReturnType helper.
const getUserWithPostsAndComments = async () => {
const connection = connect({...})
const db = drizzle(connection, { schema })

return db.query.users.findFirst({...})
}

export type CustomRelationType = ReturnType<typeof getUserWithPostsAndComments>
const getUserWithPostsAndComments = async () => {
const connection = connect({...})
const db = drizzle(connection, { schema })

return db.query.users.findFirst({...})
}

export type CustomRelationType = ReturnType<typeof getUserWithPostsAndComments>
I am using this pattern in nextjs api routes
Dbeg
Dbegβ€’355d ago
Oh ok yes that works! Thanks 😊 You probably were doing this but for anyone else, the return type of the async func would be a union type of the type | undefined wrapped in a promise. So this is what I did to get the exact type:
export type CustomRelationType = NonNullable<
Awaited<ReturnType<typeof getUserWithPostsAndComments>>
>;
export type CustomRelationType = NonNullable<
Awaited<ReturnType<typeof getUserWithPostsAndComments>>
>;
@mcgrealife Is this what you also had to do? or did I just do some longer for no reason. 🀣
mcgrealife
mcgrealifeβ€’355d ago
Ah yes, I should have mentioned this too! Your Awaited implementation is actually cleaner than mine!, but same idea to unwrap the promise, yes! I have been using NonNullable anytime I use the type – it is much better to use it directly in the custom type definition! Thanks for the tip @Dbeg πŸ‘
Cayter
Cayterβ€’355d ago
u guys did it wrongly let's say i'm using postgres driver
import * as schema from "./schema"; // your schema might be different path

const queryClient = postgres("postgres://postgres:adminadmin@0.0.0.0:5432/db");
const db: PostgresJsDatabase<typeof schema> = drizzle(queryClient);
import * as schema from "./schema"; // your schema might be different path

const queryClient = postgres("postgres://postgres:adminadmin@0.0.0.0:5432/db");
const db: PostgresJsDatabase<typeof schema> = drizzle(queryClient);
once you have defined your schema and the relations in the schema, the type inference will work the key point here is to ensure you declare your drizzle instance with typeof schema as the generic type well, by right the inference should work automatically without the above, i'm not sure if it's because of we split up the schema into different files
mcgrealife
mcgrealifeβ€’355d ago
Ah I see. I answered a different question. Confirmed that my relation queries definitely infer their own return types (without manual type annotation)! I answered from the context of nextjs api files. Where the export type keyword can only be used in the outer scope. So I wrap the db query in a function defined in the outer scope, invoke that function from the inner scope, but export it's return type in the outer scope. Thanks Cayter
Dbeg
Dbegβ€’354d ago
Thanks @Cayter So I do have that and I realise I poorly worded my question. I actually was wondering if there was something along the lines of drizzle infer type from a schema method but for relations querties. so say I have a post table I can do something like this
export type Post = InferModel<typeof post>;
export type Post = InferModel<typeof post>;
I now have the exact type for Post that I can use, in say props for a component. Is there a way I could get a type for what is inferred? @mcgrealife method actually worked as well where i just take the inferred return type. Did not see anything in the docs about it get an explicit type for what a relation query could return.
bloberenober
bloberenoberβ€’351d ago
Want results from more Discord servers?
Add your server
More Posts
in drizzle.config.ts: "Cannot use import statement outside a module"happens when I try to `push` ```ts import type { Config } from "drizzle-kit"; import { env } from "Error when using Drizzle (Non-abstract class 'PgSelect<TTableName, TSelection, TSelectMode, [...])I'm getting the following error when I try to use Drizzle: ```> graphql-server@1.0.0 start > npm runGenerate classes/interfaces from existing schemas?Messing around with drizzle, and I was wondering if there was any way to generate a class or interfaRelation Query - Get likes in postPlaying around with relational queries and I'm not quite getting how I'd retrieve the count of likesRelation query `extras` needs access to `with`I have a mysql table with two relations to another table. (one is for source values, one is for optiOptional filter param, coalesce to true?Is there a way to achieve this coalescing technique, but in valid drizzle sql? ```ts const filterByRelational query, Planetscale throws: `ResourceExhausted desc = Out of sort memory`SOLUTION: the problem was that I had a json column storing a massive value on each row. `code = ReInt to Float or Double db:pushHi we are working on a project that has drizzle db connected to a planetscale database. We initiallyTimestamp mode differences?What is the difference between the timestamp "mode" of "string'"and "date"?Many-to-Many Self RelationI'm looking to migrate from Prisma, but I'm having trouble trying to figure out how a many-to-many sRelations, three level nested where?Given a `User, Role, RoleToUser` many-to-many relation: ```ts export const userRelations = relationHelp with this relational query?I am trying to get all the organizations that a member is associated with. This code is working: RQB | using specific fields from a query against relationsis there a way to create a select filter that matches specific fields from a relation? say i `findMaSimulate enums with SQLite `CHECK()`I'm a heavy enum user in Postgres. Using SQLite now, wondering if anyone has come up with something Migrating from Prisma graduallyWe're in the middle of migrating away from Prisma to Drizzle which we just found out that Drizzle haselect with limit of 1Is there a cleaner way of selecting only one item with proper type safety than this? ```ts const usOption filter parametersHi! Love using drizzle so far! Had a quick question (not a bug): ``` const res = await ctx.databHow to delete with cascade?I'm using postgres with the following schema (reduced to the important parts): ``` export const worPSQL SQL query does not workUnable to achieve it with Drizzle helpers - I had to write my query in plain SQL. I'm trying to budrop tablesIs there a way to do a migration to drop tables? Other ORMs like Sequelize and Prisma have a concept