From 39ced1b8e4f088e2806721247ac56349c15f1ef8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Wed, 2 Sep 2020 18:15:18 +0200 Subject: [PATCH] feat(core): add `expr` helper to allow custom expressions in EM API Allows to get around strict `FilterQuery` typing when we need to use some SQL functions or expressions. ```ts em.find(Book2, { [expr('upper(title)')]: ['B1', 'B2'] }); // no TS errors ``` Related: #802 --- packages/core/src/utils/QueryHelper.ts | 2 ++ tests/EntityManager.postgre.test.ts | 14 +++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/core/src/utils/QueryHelper.ts b/packages/core/src/utils/QueryHelper.ts index 52ab549c0de4..9d77b51d3126 100644 --- a/packages/core/src/utils/QueryHelper.ts +++ b/packages/core/src/utils/QueryHelper.ts @@ -199,3 +199,5 @@ export class QueryHelper { } } + +export const expr = (sql: string) => sql; diff --git a/tests/EntityManager.postgre.test.ts b/tests/EntityManager.postgre.test.ts index ac87c39b9c61..696a9df42f77 100644 --- a/tests/EntityManager.postgre.test.ts +++ b/tests/EntityManager.postgre.test.ts @@ -1,6 +1,6 @@ import { v4 } from 'uuid'; import { - Collection, Configuration, EntityManager, LockMode, MikroORM, QueryFlag, QueryOrder, Reference, Utils, Logger, ValidationError, wrap, UniqueConstraintViolationException, + Collection, Configuration, EntityManager, LockMode, MikroORM, QueryFlag, QueryOrder, Reference, Utils, Logger, ValidationError, wrap, expr, UniqueConstraintViolationException, TableNotFoundException, NotNullConstraintViolationException, TableExistsException, SyntaxErrorException, NonUniqueFieldNameException, InvalidFieldNameException, } from '@mikro-orm/core'; import { PostgreSqlDriver, PostgreSqlConnection } from '@mikro-orm/postgresql'; @@ -1151,6 +1151,18 @@ describe('EntityManagerPostgre', () => { expect(test.id).toBeDefined(); }); + test('find with custom function', async () => { + const author = new Author2('name', 'email'); + const b1 = new Book2('b1', author); + const b2 = new Book2('b2', author); + const b3 = new Book2('b3', author); + await orm.em.persistAndFlush([b1, b2, b3]); + orm.em.clear(); + + const books = await orm.em.find(Book2, { [expr('upper(title)')]: ['B1', 'B2'] }); + expect(books).toHaveLength(2); + }); + test('find by joined property', async () => { const author = new Author2('Jon Snow', 'snow@wall.st'); const book1 = new Book2('My Life on The Wall, part 1', author);