Skip to content

Commit

Permalink
fix(query-builder): make sure $or and $and combined works correctly
Browse files Browse the repository at this point in the history
Closes #792
  • Loading branch information
charmpitz authored Aug 31, 2020
1 parent 4e26d9b commit c8d3a34
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/knex/src/query/QueryBuilderHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,10 @@ export class QueryBuilderHelper {
appendQueryCondition(type: QueryType, cond: any, qb: KnexQueryBuilder, operator?: '$and' | '$or', method: 'where' | 'having' = 'where'): void {
Object.keys(cond).forEach(k => {
if (k === '$and' || k === '$or') {
if (operator === '$and' && k === '$or') {
return qb.andWhere(inner => this.appendGroupCondition(type, inner, k, method, cond[k]));
}

if (operator === '$or' && k === '$and') {
return qb.orWhere(inner => this.appendGroupCondition(type, inner, k, method, cond[k]));
}
Expand Down
24 changes: 24 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1240,6 +1240,30 @@ describe('QueryBuilder', () => {
const qb2 = orm.em.createQueryBuilder(Author2, 'a');
qb2.select('*').where({ $or: items.map(i => ({ $and: [i] })) });
expect(qb2.getQuery()).toEqual('select `a`.* from `author2` as `a` where ((`a`.`name` = ? and `a`.`email` = ?) or (`a`.`name` = ? and `a`.`email` = ?))');

const qb3 = orm.em.createQueryBuilder(Author2, 'a');
qb3.select('*').where({
$and: [
{ $or: [{ name: 'value1' }] },
{ $or: [{ name: 'value3' }] },
],
});
expect(qb3.getQuery()).toEqual(
'select `a`.* from `author2` as `a` ' +
'where (`a`.`name` = ?) and (`a`.`name` = ?)');


const qb4 = orm.em.createQueryBuilder(Author2, 'a');
qb4.select('*').where({
$and: [
{ $or: [{ name: 'value1', email: 'value2' }] },
{ $or: [{ name: 'value3', email: 'value4' }] },
],
});
expect(qb4.getQuery()).toEqual(
'select `a`.* from `author2` as `a` ' +
'where (`a`.`name` = ? or `a`.`email` = ?) and (`a`.`name` = ? or `a`.`email` = ?)');

});

test('select fk by operator should not trigger auto-joining', async () => {
Expand Down

0 comments on commit c8d3a34

Please sign in to comment.