Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MySQL] Correct $returningId() implementation to correctly store selected fields #2975

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions drizzle-orm/src/mysql-core/query-builders/insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -252,7 +252,7 @@ export class MySqlInsertBase<
returning.push({ field: value, path: [key] });
}
}
this.config.returning = orderSelectedFields<MySqlColumn>(this.config.table[Table.Symbol.Columns]);
this.config.returning = returning;
return this as any;
}

Expand Down
17 changes: 17 additions & 0 deletions integration-tests/tests/mysql/mysql-common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down