drizzle-team / drizzle-team/drizzle-orm

[BUG]: raw SQL fields selected from subqueries should not require manually-defined aliases

Open
#2,683 6 comments 14 reactions 0 assignees View on GitHub
enhancement qb/crud
Dominant language
TypeScript
Stars
35.8k
Forks
1.6k
Avg merge
2d 7h
Merged PRs (30d)
4

Description

### What version of `drizzle-orm` are you using?

0.32.1

### What version of `drizzle-kit` are you using?

_No response_

### Describe the Bug

GENERIC CASE: I ran into this while doing a simple subquery, generally of the form `db.select().from(subquery).orderBy(something)`, where the subquery includes raw SQL fields.

SPECIFIC REASON: I'm using Postgres, and wanted to use a `DISTINCT ON` query, but have those results sorted by a different column from the distinct expression. The most straightforward way to do this is as above, just using a subquery to get the final sort order. (This is not an uncommon pattern for advanced querying using `DISTINCT ON`; see [this StackOverflow question/discussion](https://stackoverflow.com/questions/9795660/postgresql-distinct-on-with-different-order-by).)

I am effectively selecting the most recently created row belonging to each login session (most recent activity record for each session), and then ordering those based on when they were created (when the activity occurred). (It's actually a bit more complex than that in practice, this is a slightly simplified example.)

The key being that I am not doing any complex selection/filtering on the outer query, it's just a re-ordering of the existing rows from the subquery. See simplified example code below.

```typescript
const distinctQuery = trx
.selectDistinctOn([activitySchema.sessionId], {
createdAt: activitySchema.createdAt,
customerName: sql`${activitySchema.user} ->> 'name'`,
customerPhone: sql`${activitySchema.user} ->> 'phone'`,
// ... many other fields, both existing columns and derived values like above ...
})
.from(activitySchema)
.where(and(whereClauses))
.orderBy(activitySchema.sessionId, desc(activitySchema.createdAt))
.as('distinct_on_query');
const results = await trx
.select()
.from(distinctQuery)
.orderBy(desc(distinctQuery.createdAt));
```

This results in the following error:

> Error: You tried to reference "customerName" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.

### Expected behavior

I would expect a default alias to be created for such columns, using the names provided in the subquery's `.select()` object (in the example above, "customerName" and "customerPhone").

### Environment & setup

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.