Skip to content

Commit

Permalink
fix(core): allow raw fragments as keys with multiple conditions
Browse files Browse the repository at this point in the history
Closes #5112
  • Loading branch information
B4nan committed Jan 10, 2024
1 parent 7bf986c commit d0d5de8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/knex/src/query/QueryBuilderHelper.ts
Expand Up @@ -521,16 +521,21 @@ export class QueryBuilderHelper {
}

private processObjectSubCondition(cond: any, key: string, qb: Knex.QueryBuilder, method: 'where' | 'having', m: 'where' | 'orWhere' | 'having', type: QueryType): void {
// grouped condition for one field
let value = cond[key];
const size = Utils.getObjectKeysSize(value);

if (Utils.isPlainObject(value) && size === 0) {
return;
}

// grouped condition for one field, e.g. `{ age: { $gte: 10, $lt: 50 } }`
if (size > 1) {
const subCondition = Object.entries(value).map(([subKey, subValue]) => ({ [key]: { [subKey]: subValue } }));
const rawField = RawQueryFragment.getKnownFragment(key);
const subCondition = Object.entries(value).map(([subKey, subValue]) => {
key = rawField?.clone().toString() ?? key;
return ({ [key]: { [subKey]: subValue } });
});

return subCondition.forEach(sub => this.appendQueryCondition(type, sub, qb, '$and', method));
}

Expand Down
10 changes: 10 additions & 0 deletions tests/issues/GHx6.test.ts
Expand Up @@ -93,3 +93,13 @@ test('raw fragments with populateOrderBy on relation', async () => {
'left join `job` as `j1` on `t0`.`custom_name` = `j1`.`id` ' +
'order by t0.created desc, j1.DateCompleted desc');
});

test('raw fragments with multiple items in filter', async () => {
const mock = mockLogger(orm);
await orm.em.findAll(Tag, {
where: {
[raw('id')]: { $gte: 10, $lte: 50 },
},
});
expect(mock.mock.calls[0][0]).toMatch('select `t0`.* from `tag` as `t0` where id >= 10 and id <= 50');
});

0 comments on commit d0d5de8

Please sign in to comment.