Skip to content

Commit

Permalink
fix(query-builder): fix auto-joining of 1:m PKs
Browse files Browse the repository at this point in the history
Closes #857
  • Loading branch information
B4nan committed Sep 22, 2020
1 parent f084535 commit 920995f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
11 changes: 6 additions & 5 deletions packages/knex/src/query/ScalarCriteriaNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,16 @@ export class ScalarCriteriaNode extends CriteriaNode {
}

shouldJoin(): boolean {
if (!this.parent || !this.prop || [ReferenceType.SCALAR, ReferenceType.ONE_TO_MANY].includes(this.prop.reference)) {
if (!this.parent || !this.prop) {
return false;
}

if (this.prop.reference === ReferenceType.ONE_TO_ONE) {
return !this.prop.owner;
switch (this.prop.reference) {
case ReferenceType.ONE_TO_MANY: return true;
case ReferenceType.MANY_TO_MANY: return true;
case ReferenceType.ONE_TO_ONE: return !this.prop.owner;
default: return false; // SCALAR, MANY_TO_ONE
}

return this.prop.reference === ReferenceType.MANY_TO_MANY;
}

}
18 changes: 18 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1653,6 +1653,24 @@ describe('QueryBuilder', () => {
expect(sql7).toBe('select `e0`.* from `test2` as `e0` where `e0`.`book_uuid_pk` in (?)');
});

test('query by 1:m PK (GH issue 857)', async () => {
const sql0 = orm.em.createQueryBuilder(Author2).select('*').where({ books: '123' }).getQuery();
expect(sql0).toBe('select `e0`.* from `author2` as `e0` left join `book2` as `e1` on `e0`.`id` = `e1`.`author_id` where `e1`.`uuid_pk` = ?');
const expected = 'select `e0`.* from `author2` as `e0` left join `book2` as `e1` on `e0`.`id` = `e1`.`author_id` where `e1`.`uuid_pk` in (?)';
const sql1 = orm.em.createQueryBuilder(Author2).where({ books: [123] }).getQuery();
expect(sql1).toBe(expected);
const sql2 = orm.em.createQueryBuilder(Author2).where({ books: { uuid: [123] } }).getQuery();
expect(sql2).toBe(expected);
const sql3 = orm.em.createQueryBuilder(Author2).where({ books: { uuid: { $in: [123] } } }).getQuery();
expect(sql3).toBe(expected);
const sql4 = orm.em.createQueryBuilder(Author2).where({ $and: [{ books: { uuid: { $in: [123] } } }] }).getQuery();
expect(sql4).toBe(expected);
const sql5 = orm.em.createQueryBuilder(Author2).where({ $and: [{ books: [123] }] }).getQuery();
expect(sql5).toBe(expected);
const sql6 = orm.em.createQueryBuilder(Author2).where({ $and: [{ books: { uuid: [123] } }] }).getQuery();
expect(sql6).toBe(expected);
});

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

});

0 comments on commit 920995f

Please sign in to comment.