diff --git a/drizzle-orm/src/mysql-core/query-builders/insert.ts b/drizzle-orm/src/mysql-core/query-builders/insert.ts index fe9f7d7ba..5a9afaa8a 100644 --- a/drizzle-orm/src/mysql-core/query-builders/insert.ts +++ b/drizzle-orm/src/mysql-core/query-builders/insert.ts @@ -16,8 +16,8 @@ import type { Placeholder, Query, SQLWrapper } from '~/sql/sql.ts'; import { Param, SQL, sql } from '~/sql/sql.ts'; import type { InferModelFromColumns } from '~/table.ts'; import { Table } from '~/table.ts'; -import { mapUpdateSet, orderSelectedFields } from '~/utils.ts'; -import type { AnyMySqlColumn, MySqlColumn } from '../columns/common.ts'; +import { mapUpdateSet } from '~/utils.ts'; +import type { AnyMySqlColumn } from '../columns/common.ts'; import type { SelectedFieldsOrdered } from './select.types.ts'; import type { MySqlUpdateSetSource } from './update.ts'; @@ -252,7 +252,7 @@ export class MySqlInsertBase< returning.push({ field: value, path: [key] }); } } - this.config.returning = orderSelectedFields(this.config.table[Table.Symbol.Columns]); + this.config.returning = returning; return this as any; } diff --git a/integration-tests/tests/mysql/mysql-common.ts b/integration-tests/tests/mysql/mysql-common.ts index 45b96f391..1d3789943 100644 --- a/integration-tests/tests/mysql/mysql-common.ts +++ b/integration-tests/tests/mysql/mysql-common.ts @@ -3445,6 +3445,23 @@ export function tests(driver?: string) { expect(result).toStrictEqual([{ id: 1 }]); }); + test('insert $returningId: serial as id, not first column', async (ctx) => { + const { db } = ctx.mysql; + + const usersTableDefNotFirstColumn = mysqlTable('users2', { + name: text('name').notNull(), + id: serial('id').primaryKey(), + }); + + const result = await db.insert(usersTableDefNotFirstColumn).values({ name: 'John' }).$returningId(); + + expectTypeOf(result).toEqualTypeOf<{ + id: number; + }[]>(); + + expect(result).toStrictEqual([{ id: 1 }]); + }); + test('insert $returningId: serial as id, batch insert', async (ctx) => { const { db } = ctx.mysql;