drizzle-team / drizzle-team/drizzle-orm

[FEATURE]:Add support for value lists

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

Description

### Feature hasn't been suggested before.

- [x] I have verified this feature I'm about to request hasn't been suggested before.

### Describe the enhancement you want to request

Values list can appear anywhere a select can appear, not only during `insert`s ([source](https://www.postgresql.org/docs/current/queries-values.html)).

I made a simple helper to make it easy to use those value lists but it doesn't currently type the sql parameters.

```typescript
// TODO: type values (everything is a `text` for now)
export function values(items: Record[]) {
const [firstProp, ...props] = Object.keys(items[0]);
const values = items
.map((x) => {
let ret = sql`(${x[firstProp]}`;
for (const val of props) {
ret = sql`${ret}, ${x[val]}`;
}
return sql`${ret})`;
})
.reduce((acc, x) => sql`${acc}, ${x}`);
const valueNames = [firstProp, ...props].join(", ");

return {
as: (name: string) => {
return sql`(values ${values}) as ${sql.raw(name)}(${sql.raw(valueNames)})`;
},
};
}
```

It can be used like this (notice the casts in sql because `values` can't know the type of the columns):

```typescript
const retVideos = await db
.insert(entryVideoJoin)
.select(
db
.select({
entry: sql`vids.entryPk::integer`.as("entry"),
video: sql`${videos.pk}`.as("video"),
})
.from(values(vids).as("vids"))
.innerJoin(videos, eq(videos.id, sql`vids.videoId::uuid`)),
)
.onConflictDoNothing()
.returning({
slug: entryVideoJoin.slug,
entryPk: entryVideoJoin.entry,
});
```

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.