drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

Feat: Allow subqueries in select fields

Open Angelelz opened this issue 1 year ago • 2 comments

close #361

  • [All] Implemented the types inference for subqueries in SelectFields
  • [All] Implemented type tests
  • [All] Implemented correct handling of subqueries in selected fields
  • [All] Added integration tests

With this PR, a user will be able to select using subqueries. The following query will be possible with proper types and mapping:

const res = await db.select({
	population: db.select({ count: count().as('count') }).from(users).where(
		eq(users.cityId, cities.id),
	).as('population'),
	name: cities.name,
}).from(cities);

// And the resulting type will be:
type Res = {
	population: number;
	name: string;
}[]

Since the subquery can only contain one column, I moved the mapping from the column to the whole subquery. That means that if the field in the subquery is a Date the user can expect a date in the types and the runtime value.

Angelelz avatar Dec 20 '23 06:12 Angelelz

This is one of the few frictions I feel writing drizzle.

Would love to see this merged 😍

MAST1999 avatar Mar 10 '24 06:03 MAST1999

I'm hitting this a lot, would love this to get live! anything i can do to help?

DianomiJH avatar May 16 '24 13:05 DianomiJH

any chance this could be resurrected and shipped? this is definitely a source of friction day to day. if not, is there a workaround to get the types working with some kind of custom helper function?

erikmunson avatar Jan 26 '25 02:01 erikmunson

bump, @erikmunson I just spent 40 minutes trying to figure out why I couldn't use this subquery to find out this PR isn't merged

JadenSWang avatar Feb 21 '25 23:02 JadenSWang