drizzle-team / drizzle-team/drizzle-orm

[BUG]: Subqueries lose alias for `sql` calculated fields

Open
#3,096 7 comments 4 reactions 1 assignee Claimed by @L-Mario564 View on GitHub
bug bug/fixed-in-beta db/sqlite 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.34.1

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

0.25.0

### Describe the Bug

When I select join with a subquery and select a field that was calculated using the `sql` operator, the resulting query loses its alias and only selects with the field alias.

Lets take this example, I have the following subquery:

```
const subQuery = db
.select({
identifier: table.id,
sqlCol: sql`'some value'`.as('sqlCol'),
})
.from(table)
.as('subQuery')
```

The subquery alias is `subQuery` and the calculated field is called `sqlCol`.

I am using it in the following query:

```
db.select({
identifier: subQuery.identifier,
sqlCol: subQuery.sqlCol,
})
.from(table)
.leftJoin(subQuery, eq(subQuery.identifier, 1))
```

This results in the following SQL statement being executed:

```
select "subQuery"."id", "sqlCol" from "measurement" left join (select "id", 'some value' as "sqlCol" from "measurement") "subQuery" on "subQuery"."id" = ?
```

As you can see, the `id` field still has the subQuery alias and is selected using `"subQuery"."id"`, the SQL field however is only selected through `"sqlCol"`.

This makes it impossible to have multiple subqueries with the same alias for SQL fields.

### Expected behavior

All fields selected from a subquery should be prefixed with the subquery alias, including calculated fields with the `sql` function

### Environment & setup

I am using expo-sqlite (v14.0.6) during this test

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.