Skip to content

Commit

Permalink
feat(query-builder): allow joins on update queries
Browse files Browse the repository at this point in the history
Closes #6150
  • Loading branch information
B4nan committed Oct 20, 2024
1 parent 87d0602 commit 782e227
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1470,6 +1470,7 @@ export class QueryBuilder<
break;
case QueryType.UPDATE:
qb.update(this._data);
this.helper.processJoins(qb, this._joins, joinSchema);
this.helper.updateVersionProperty(qb, this._data);
break;
case QueryType.DELETE:
Expand Down Expand Up @@ -1796,6 +1797,7 @@ export class QueryBuilder<
(subSubQuery as Dictionary).__raw = true; // tag it as there is now way to check via `instanceof`
const method = this.flags.has(QueryFlag.UPDATE_SUB_QUERY) ? 'update' : 'delete';
this._cond = {}; // otherwise we would trigger validation error
this._joins = {}; // included in the subquery

this[method](this._data as EntityData<Entity>).where({
[Utils.getPrimaryKeyHash(meta.primaryKeys)]: { $in: subSubQuery },
Expand Down
12 changes: 12 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1560,6 +1560,18 @@ describe('QueryBuilder', () => {
expect(qb.getParams()).toEqual(['test 123', 123]);
});

test('update query with joins', async () => {
const qb = orm.em.createQueryBuilder(Publisher2, 'p');
qb.update({ name: 'test 123', type: PublisherType.GLOBAL })
.join('p.books', 'b', { title: 'foo' })
.where({ 'b.author': 123 });
expect(qb.getQuery()).toEqual('update `publisher2` as `p` ' +
'inner join `book2` as `b` on `p`.`id` = `b`.`publisher_id` and `b`.`title` = ? ' +
'set `name` = ?, `type` = ? ' +
'where `b`.`author_id` = ?');
expect(qb.getParams()).toEqual(['foo', 'test 123', PublisherType.GLOBAL, 123]);
});

test('trying to call qb.update/delete() after qb.where() will throw', async () => {
const err1 = 'You are trying to call `qb.where().update()`. Calling `qb.update()` before `qb.where()` is required.';
expect(() => orm.em.qb(Publisher2).where({ id: 123, type: PublisherType.LOCAL }).update({ name: 'test 123', type: PublisherType.GLOBAL })).toThrow(err1);
Expand Down

0 comments on commit 782e227

Please sign in to comment.