drizzle-team / drizzle-team/drizzle-orm

[FEATURE]: first() method for the non-relational query builder

Open
#3,279 2 comments 10 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

### Describe what you want

Our codebase unfortunately didn't start out with the [`noUncheckedIndexed`](https://www.typescriptlang.org/tsconfig/#noUncheckedIndexedAccess) typescript rule, and in many cases we were selecting one row. So we had a lot of code like:

```ts
const [row] = await db
.select()
.from(table)
.where(eq(table.id, id))
.limit(1)
```

This is dangerous code: `row` has a non-nullable type that assumes that a row was found, so the rest of the function around it isn't required to deal with the falsiness. Once realizing this, we've been switching to this:

```ts
const row = await db
.select()
.from(table)
.where(eq(table.id, id))
.limit(1)
.then(r => r.at(0))
```

This has the correct types - `row` is potentially undefined. But it breaks from our usage of `await` for everything and sticks in a little `.then()` like the old days. We could parenthesize the await like

```ts
const row = (await db
.select()
.from(table)
.where(eq(table.id, id))
.limit(1)).at(0)
```

But then you've got some parenthesis and it just feels overcomplicated, right? I'd adore an API like

```ts
const row = await db
.select()
.from(table)
.where(eq(table.id, id))
.limit(1)
.first()
```

Or even an API like `.at(0)` instead of `.first()`, but that doesn't require breaking the query syntax. I suspect the reason why drizzle doesn't have this is because then this query wouldn't compose with others if it was used as a subquery, but this could be something that has no effect on the `.toSQL()` value of the given query.

We're adopting the relational api slowly, which does have this method, but there's a lot of code that would be tough to port and could benefit from a clean API for this issue!

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.