Skip to content

Commit

Permalink
fix(core): ensure correct aliasing when auto-joining PKs in group con…
Browse files Browse the repository at this point in the history
…ditions

Closes #1734
  • Loading branch information
B4nan committed Apr 26, 2021
1 parent 1ba49fe commit 38775e6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/knex/src/query/ObjectCriteriaNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,15 @@ export class ObjectCriteriaNode extends CriteriaNode {
const operator = Utils.isOperator(field);
const customExpression = ObjectCriteriaNode.isCustomExpression(field);
const virtual = childNode.prop?.persist === false;
const primaryKey = this.metadata.find(this.entityName)?.primaryKeys.includes(field);
// if key is missing, we are inside group operator and we need to prefix with alias
const primaryKey = this.key && this.metadata.find(this.entityName)!.primaryKeys.includes(field);

if (childNode.shouldInline(payload)) {
const childAlias = qb.getAliasForJoinPath(childNode.getPath());
this.inlineChildPayload(o, payload, field, alias, childAlias);
} else if (childNode.shouldRename(payload)) {
o[childNode.renameFieldToPK(qb)] = payload;
} else if (primaryKey || virtual || operator || customExpression || field.includes('.') || ![QueryType.SELECT, QueryType.COUNT].includes(qb.type)) {
} else if (primaryKey || virtual || operator || customExpression || field.includes('.') || ![QueryType.SELECT, QueryType.COUNT].includes(qb.type ?? QueryType.SELECT)) {
o[field] = payload;
} else {
o[`${alias}.${field}`] = payload;
Expand Down
16 changes: 16 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1948,6 +1948,22 @@ describe('QueryBuilder', () => {
expect(sql3).toBe("update `my_schema`.`author2` force index(custom_email_index_name) set `name` = '...' where `favourite_book_uuid_pk` in ('1', '2', '3')");
});

test('$or operator inside auto-joined relation', async () => {
const query = {
author: {
$or: [
{ id: 123 },
{ name: { $like: `%jon%` } },
],
},
};
const expected = "select `e0`.*, `e0`.price * 1.19 as `price_taxed` from `book2` as `e0` left join `author2` as `e1` on `e0`.`author_id` = `e1`.`id` where (`e1`.`id` = 123 or `e1`.`name` like '%jon%')";
const sql1 = orm.em.createQueryBuilder(Book2).select('*').where(query).getFormattedQuery();
expect(sql1).toBe(expected);
const sql2 = orm.em.createQueryBuilder(Book2).where(query).getFormattedQuery();
expect(sql2).toBe(expected);
});

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

});

0 comments on commit 38775e6

Please sign in to comment.