Skip to content

Commit

Permalink
fix(core): support calling em.findAndCount() on virtual entities wi…
Browse files Browse the repository at this point in the history
…th `orderBy`

Closes #4628
  • Loading branch information
B4nan committed Aug 24, 2023
1 parent 2f65bc8 commit 7f328ac
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/core/src/EntityManager.ts
Expand Up @@ -1196,11 +1196,13 @@ export class EntityManager<D extends IDatabaseDriver = IDatabaseDriver> {
Entity extends object,
Hint extends string = never,
>(entityName: EntityName<Entity>, where: FilterQuery<Entity> = {} as FilterQuery<Entity>, options: CountOptions<Entity, Hint> = {}): Promise<number> {
options = { ...options };
const em = this.getContext(false);
entityName = Utils.className(entityName);
where = await em.processWhere(entityName, where, options as FindOptions<Entity, Hint>, 'read') as FilterQuery<Entity>;
options.populate = em.preparePopulate(entityName, options) as unknown as Populate<Entity>;
em.validator.validateParams(where);
delete (options as FindOptions<Entity>).orderBy;

const cached = await em.tryCache<Entity, number>(entityName, options.cache, [entityName, 'em.count', options, where]);

Expand Down
44 changes: 44 additions & 0 deletions tests/features/virtual-entities/GH4628.test.ts
@@ -0,0 +1,44 @@
import { Entity, PrimaryKey, Property, SimpleLogger } from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/postgresql';
import { mockLogger } from '../../bootstrap';

@Entity()
class Book {

@PrimaryKey()
id!: number;

@Property()
title!: string;

}

@Entity({ expression: 'select title from book' })
class BookSimple {

@Property()
title!: string;

}

let orm: MikroORM;

beforeAll(async () => {
orm = await MikroORM.init({
dbName: 'virtual_entities',
entities: [Book, BookSimple],
loggerFactory: options => new SimpleLogger(options),
});
await orm.schema.refreshDatabase();
});
beforeEach(async () => orm.schema.clearDatabase());
afterAll(async () => orm.close(true));

test('virtual entities (postgres)', async () => {
const mock = mockLogger(orm);
await orm.em.findAndCount(BookSimple, {}, { orderBy: { title: 1 } });
expect(mock.mock.calls.map(r => r[0]).sort()).toEqual([
`[query] select * from (select title from book) as "b0" order by "b0"."title" asc`,
`[query] select count(*) as count from (select title from book) as "b0"`,
]);
});

0 comments on commit 7f328ac

Please sign in to comment.