Skip to content

Commit

Permalink
feat(core): validate wrong placement of collection operators
Browse files Browse the repository at this point in the history
  • Loading branch information
B4nan committed Mar 2, 2024
1 parent 7b6b363 commit c35e705
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
12 changes: 8 additions & 4 deletions packages/knex/src/query/ObjectCriteriaNode.ts
Expand Up @@ -29,10 +29,14 @@ export class ObjectCriteriaNode<T extends object> extends CriteriaNode<T> {

if (this.shouldAutoJoin(qb, nestedAlias)) {
if (keys.some(k => ['$some', '$none', '$every'].includes(k))) {
// ignore collection operators when used on a non-relational property - this can happen when they get into
// populateWhere via `infer` on m:n properties with select-in strategy
if (!this.prop?.targetMeta) {
return {};
if (![ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(this.prop!.kind)) {
// ignore collection operators when used on a non-relational property - this can happen when they get into
// populateWhere via `infer` on m:n properties with select-in strategy
if (this.parent?.parent) { // we validate only usage on top level
return {};
}

throw new Error(`Collection operators can be used only inside a collection property context, but it was used for ${this.getPath()}.`);
}

const $and: Dictionary[] = [];
Expand Down
21 changes: 21 additions & 0 deletions tests/features/collection/populate-where-infer.test.ts
Expand Up @@ -122,3 +122,24 @@ test('$every with populateWhere: infer', async () => {
'left join `server` as `s1` on `u0`.`id` = `s1`.`user_id` ' +
'where `u0`.`id` not in (select `u0`.`id` from `user` as `u0` inner join `server` as `s1` on `u0`.`id` = `s1`.`user_id` where not (`s1`.`name` != \'test\'))');
});

test('disallow $every on top level', async () => {
const mock = mockLogger(orm);

await expect(orm.em.fork().find(
User,
{
$every: {
servers: {
name: {
$ne: 'test',
},
},
},
},
{
populate: ['servers'],
populateWhere: 'infer',
},
)).rejects.toThrow('Collection operators can be used only inside a collection property context, but it was used for User.id.');
});

0 comments on commit c35e705

Please sign in to comment.