Skip to content

Commit

Permalink
fix(query-builder): validate missing onConflict calls
Browse files Browse the repository at this point in the history
Also allows calling `onConflict()` without parameter.

Closes #1803
  • Loading branch information
B4nan committed May 13, 2021
1 parent 0a0622a commit 30392bc
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
14 changes: 11 additions & 3 deletions packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,19 +250,27 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {
return this;
}

onConflict(fields: string | string[]): this {
onConflict(fields: string | string[] = []): this {
this._onConflict = this._onConflict || [];
this._onConflict.push({ fields: Utils.asArray(fields) });
return this;
}

ignore(): this {
this._onConflict![this._onConflict!.length - 1].ignore = true;
if (!this._onConflict) {
throw new Error('You need to call `qb.onConflict()` first to use `qb.ignore()`');
}

this._onConflict[this._onConflict.length - 1].ignore = true;
return this;
}

merge(data?: EntityData<T> | Field<T>[]): this {
this._onConflict![this._onConflict!.length - 1].merge = data;
if (!this._onConflict) {
throw new Error('You need to call `qb.onConflict()` first to use `qb.merge()`');
}

this._onConflict[this._onConflict.length - 1].merge = data;
return this;
}

Expand Down
23 changes: 23 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1228,6 +1228,29 @@ describe('QueryBuilder', () => {

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]);

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

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

const qb5 = orm.em.createQueryBuilder(Author2)
.insert({
createdAt: timestamp,
email: 'ignore@example.com',
name: 'John Doe',
updatedAt: timestamp,
});
expect(() => qb5.ignore()).toThrow('You need to call `qb.onConflict()` first to use `qb.ignore()`');
expect(() => qb5.merge()).toThrow('You need to call `qb.onConflict()` first to use `qb.merge()`');
});

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

0 comments on commit 30392bc

Please sign in to comment.