drizzle-team / drizzle-team/drizzle-orm
[BUG]: Cannot use SQL.Aliased from SubQuery in GroupBy
- Dominant language
- TypeScript
- Stars
- 35.8k
- Forks
- 1.6k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 4
Description
### Report hasn't been filed before.
- [X] I have verified that the bug I'm about to report hasn't been filed before.
### What version of `drizzle-orm` are you using?
0.36.3
### What version of `drizzle-kit` are you using?
0.28.1
### Other packages
drizzle-zod@0.5.1
### Describe the Bug
I'm unable to use a `SQL.Aliased` from a subquery in the groupBy of a select. The ts error states that groupBy can only take columns:
```
Type 'Aliased' is missing the following properties from type 'SQLiteColumn, object>': table, name, keyAsName, primary, and 17 more.ts(2769)
```
This is a simple sample, with a messages table (sender -> receiver), where I'm trying to get the latest message sent/received by the current user with all their friends. It fails on `.groupBy(friendMessages.friendId)` with the error above:
```ts
import * as t from "drizzle-orm/sqlite-core";
import { sqliteTable } from "drizzle-orm/sqlite-core";
// messages table for sending text messages sender->receiver (by id) at timestamp
const Message = sqliteTable("messages", {
id: t.int().primaryKey(),
ts: t.int({ mode: "timestamp" }),
senderId: t.int().notNull(),
receiverId: t.int().notNull(),
content: t.text(),
});
// get list of all messages sent to and from the current user, return other user as friend
const friendMessages = db
.select({
id: Message.id,
ts: Message.ts,
friendId: sql`CASE
WHEN ${Message.senderId} = ${user.id} THEN ${Message.receiverId}
ELSE ${Message.senderId}
END`.as("friendId"),
})
.from(Message)
.where(or(eq(Message.senderId, user.id), eq(Message.receiverId, user.id)))
.as("friendMessages");
// group by friend uid to get the last message sent from/to the current user by each of their friends
const lastMessages = db
.select()
.from(friendMessages)
.groupBy(friendMessages.friendId)
.orderBy(desc(friendMessages.ts))
.as("lastMessages");
```
If I try to group by one of the columns, like `friendMessages.id`, it works as expected. However, it doesn't allow me to group by the friendId, which is defined by the SQL-case in the subquery. Imo this would work in raw SQL.
Contributor guide
Assessment
This issue has not been assessed yet.