Skip to content

Commit

Permalink
fix(query-builder): allow passing array of keys to `qb.onConflict().m…
Browse files Browse the repository at this point in the history
…erge()`

Related: #1774
  • Loading branch information
B4nan committed May 12, 2021
1 parent b33be4a commit e4a1cf0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
4 changes: 2 additions & 2 deletions packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {
private _orderBy: QueryOrderMap = {};
private _groupBy: Field<T>[] = [];
private _having: Dictionary = {};
private _onConflict?: { fields: string[]; ignore?: boolean; merge?: EntityData<T>; where?: QBFilterQuery<T> }[];
private _onConflict?: { fields: string[]; ignore?: boolean; merge?: EntityData<T> | Field<T>[]; where?: QBFilterQuery<T> }[];
private _limit?: number;
private _offset?: number;
private _joinedProps = new Map<string, PopulateOptions<any>>();
Expand Down Expand Up @@ -261,7 +261,7 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {
return this;
}

merge(data?: EntityData<T>): this {
merge(data?: EntityData<T> | Field<T>[]): this {
this._onConflict![this._onConflict!.length - 1].merge = data;
return this;
}
Expand Down
15 changes: 14 additions & 1 deletion tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1180,7 +1180,7 @@ describe('QueryBuilder', () => {
expect(qb3.getParams()).toEqual([123]);
});

test('insert on conflict ignore/merge', async () => {
test('insert on conflict ignore/merge (GH #1774)', async () => {
const qb0 = orm.em.createQueryBuilder(Author2);
qb0.insert({ email: 'ignore@example.com', name: 'John Doe' }).onConflict('email').ignore();
expect(qb0.getQuery()).toEqual('insert ignore into `author2` (`email`, `name`) values (?, ?)');
Expand Down Expand Up @@ -1215,6 +1215,19 @@ describe('QueryBuilder', () => {

expect(qb2.getQuery()).toEqual('insert into `author2` (`created_at`, `email`, `name`, `updated_at`) values (?, ?, ?, ?) on duplicate key update `created_at` = values(`created_at`), `email` = values(`email`), `name` = values(`name`), `updated_at` = values(`updated_at`)');
expect(qb2.getParams()).toEqual([timestamp, 'ignore@example.com', 'John Doe', timestamp]);

const qb3 = orm.em.createQueryBuilder(Author2)
.insert({
createdAt: timestamp,
email: 'ignore@example.com',
name: 'John Doe',
updatedAt: timestamp,
})
.onConflict('email')
.merge(['name']);

expect(qb3.getQuery()).toEqual('insert into `author2` (`created_at`, `email`, `name`, `updated_at`) values (?, ?, ?, ?) on duplicate key update `name` = values(`name`)');
expect(qb3.getParams()).toEqual([timestamp, 'ignore@example.com', 'John Doe', timestamp]);
});

test('insert many query', async () => {
Expand Down

0 comments on commit e4a1cf0

Please sign in to comment.