Get type for select query?

Hey guys, is there a way to infer the "select" type for a given table? for example:
async getUsers(selectColumns: ?) {
return this.db.select(selectColumns).from(users)
}
async getUsers(selectColumns: ?) {
return this.db.select(selectColumns).from(users)
}
I have a UsersService class with getUsers method. I want callers to be able to select specific columns. Is is possible to achieve this type safety and autocomplete without directly using the drizzle client?
5 Replies
Andrii Sherman
@Dan Kochetov
Doron Torangy
Doron TorangyOP2y ago
Is this question maybe related to this? https://github.com/drizzle-team/drizzle-orm/issues/504 If so where can I find that API layer?
Doron Torangy
Doron TorangyOP12mo ago
@Dan Kochetov any news about this one?
Dan
Dan12mo ago
import { SelectedFields } from 'drizzle-orm/pg-core';

async function getUsers<T extends SelectedFields>(fields: T) {
return db.select(fields).from(users);
}
import { SelectedFields } from 'drizzle-orm/pg-core';

async function getUsers<T extends SelectedFields>(fields: T) {
return db.select(fields).from(users);
}
Doron Torangy
Doron TorangyOP12mo ago
This works, but I noticed that we lose $dynamic query for some reason.
async getUsersWithProjection<T extends SelectedFields>(filters: UsersFilters, fields: T) {
const qb = this.db.select(fields).from(users).$dynamic()
return this.withUsersFilter(qb, filters).execute()
^ -- The types of '_.dynamic' are incompatible between these types.
Type 'boolean' is not assignable to type 'true'.
}

private withUsersFilter<T extends PgSelect>(qb: T, filters: UsersFilters) {
return qb.where(...)
}
async getUsersWithProjection<T extends SelectedFields>(filters: UsersFilters, fields: T) {
const qb = this.db.select(fields).from(users).$dynamic()
return this.withUsersFilter(qb, filters).execute()
^ -- The types of '_.dynamic' are incompatible between these types.
Type 'boolean' is not assignable to type 'true'.
}

private withUsersFilter<T extends PgSelect>(qb: T, filters: UsersFilters) {
return qb.where(...)
}
Want results from more Discord servers?
Add your server