Skip to content

Commit

Permalink
feat(core): add expr helper to allow custom expressions in EM API
Browse files Browse the repository at this point in the history
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
  • Loading branch information
B4nan committed Sep 2, 2020
1 parent 8477d4f commit 39ced1b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 2 additions & 0 deletions packages/core/src/utils/QueryHelper.ts
Expand Up @@ -199,3 +199,5 @@ export class QueryHelper {
}

}

export const expr = (sql: string) => sql;
14 changes: 13 additions & 1 deletion 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';
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 39ced1b

Please sign in to comment.