drizzle-team / drizzle-team/drizzle-orm

[BUG]: Column type is undefined when using conditional select on subquery

Open
#3,515 0 comments 2 reactions 0 assignees View on GitHub
improvement qb/crud
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.30.4

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

0.20.14

### Other packages

_No response_

### Describe the Bug

When we *conditionnally* `.select()` a field in a subquery, the resulting column type is `undefined`.

```
const subQuery = db.select({
id: users.id,
...(withName && { name: users.name }),
}).from(users).as('sub')
```

The type of `subQuery.name` is `undefined` and cannot be used directly into another query without casting:

```
await db.select({
id: users.id,
...(withName ? { name: subQuery.name as unknown as typeof users.name } : {}), // KO, need casting
// ^? name?: undefined
}).from(subQuery)
```

[Playground link](https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgEysAXugNgUzgXzgDMoIQ4ByVDbHAWmhAHoA7CZeyAZxgHMocXCgG4AUKEixEcMLwAqAQwBGuADRwuONAqzqYOAB7xCJMpWqZcDKM1l0AxtBwjRow5PiOWPOAFdNUFxwALwy8sq4ABQU-lpC6giicHDAyABcGlrAOtGpFACUAHRgaCAKUACeANI4FZH5qklwLAogOBn6RtEtbQWFbDAAcr5YWPWN+Pliol4+yEohKGiWOJEIhApBCiwV+a4zEN7wAO7AMAAWg63tcEoQELjbiwBC948skQCyCheFUNvIMj1PYHI4aXxKACKvi0FUW80Kmlw9hgayaqQysUChVSjWShQJkVOFyubTgADJydIejcsVx+tcCA04EwmHAADx0OhwLzIM7AQ46TLI+CHcFKACOMMqokmhVMIEidKKm2iXAhBVcCmOCjOKCUiJwIrRyQxfgC9NxTQJhSJZ0ujIA-NTrhl1VDpRUGWTNn4WABrNjHFhwX0wCpgHAQIjmuLevCEDLrZmsuBVADy6hYOBwyB5mxgwBYvFEqeS5Yrlar1YrAD1HbKigrIu7obCQdrdfAEUicCiTSl0rHsVb8YTiQ6yc6kDTMRb4wQ4EnJupU+mqo35aRFcrREA)

**Expected behavior**: The resulting column type should not be undefined and can be used in another query

Also tested with latest version of drizzle-orm 0.36.1
Tested with Typescript versions 5.4.4 and 5.6.3

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.