Skip to content

Commit

Permalink
fix(knex): fully qualify sub-query order-by fields (#2835)
Browse files Browse the repository at this point in the history
Co-authored-by: Asi Farran <asi@schmallo.com>
Co-authored-by: Martin Adámek <banan23@gmail.com>
  • Loading branch information
3 people committed Mar 8, 2022
1 parent 89f298d commit f74dc73
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,7 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {
for (const orderMap of this._orderBy) {
for (const [field, direction] of Object.entries(orderMap)) {
orderBy.push({
[`min(${this.ref(field)})`]: direction,
[`min(${this.ref(this.helper.mapper(field, this.type))})`]: direction,
});
}
}
Expand Down
6 changes: 6 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2613,6 +2613,12 @@ describe('QueryBuilder', () => {
expect(sql).toBe(expected);
});

test('sub-query order-by fields are always fully qualified', () => {
const expected = 'select `e0`.*, `books`.`uuid_pk` as `books__uuid_pk`, `books`.`created_at` as `books__created_at`, `books`.`title` as `books__title`, `books`.`price` as `books__price`, `books`.price * 1.19 as `books__price_taxed`, `books`.`double` as `books__double`, `books`.`meta` as `books__meta`, `books`.`author_id` as `books__author_id`, `books`.`publisher_id` as `books__publisher_id` from `author2` as `e0` inner join `book2` as `books` on `e0`.`id` = `books`.`author_id` where `e0`.`id` in (select `e0`.`id` from (select `e0`.`id` from `author2` as `e0` inner join `book2` as `books` on `e0`.`id` = `books`.`author_id` group by `e0`.`id` order by min(`e0`.`id`) desc limit 10) as `e0`) order by `e0`.`id` desc';
const sql = orm.em.createQueryBuilder(Author2).select('*').joinAndSelect('books','books').orderBy({ id: QueryOrder.DESC }).limit(10).getFormattedQuery();
expect(sql).toBe(expected);
});

afterAll(async () => orm.close(true));

});

0 comments on commit f74dc73

Please sign in to comment.