drizzle-team / drizzle-team/drizzle-orm
[BUG]: INSERT into SELECT requires all columns but documentation says otherwise
- 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.45.1
### What version of `drizzle-kit` are you using?
0.30.6
### Other packages
_No response_
### Describe the Bug
The Insert into Select documentation https://orm.drizzle.team/docs/insert#insert-into--select provides this example:
```
const insertedEmployees = await db
.insert(employees)
.select(
db.select({ name: users.name }).from(users).where(eq(users.role, 'employee'))
)
.returning({
id: employees.id,
name: employees.name
});
```
which implies you can have a partial column list and it will work fine. However, with Postgres, Drizzle gives this error:
```
Error: Insert select error: selected fields are not the same or are in a different order compared to the table definition
at PgInsertBuilder.select
```
This should work as documented.
This hack does work:
```
const insertedEmployees = await db
.insert(employees)
.select(
db.select({ id: sql`gen_random_uuid()`.as('id'), name: users.name }).from(users).where(eq(users.role, 'employee'))
)
.returning({
id: employees.id,
name: employees.name
});
```
but there are many use cases where you cannot include all columns in your SELECT (e.g. the first select could use a selectDistinct but the second cannot because adding an explicit uuid breaks the uniqueness)
Internally I would expect the first example from the documentation to generate the following SQL in Postgres:
```
insert into employees (email)
(select name from users where role='employee');
```
I would expect the in the PgInsertBuilder to build the column list from the select or allow a way to explicitly declare it.
Contributor guide
Assessment
This issue has not been assessed yet.