Skip to content

Commit

Permalink
feat(sql): add execute() method to SqlEntityManager
Browse files Browse the repository at this point in the history
Shortcut to `em.driver.execute()`, which as opposed to `em.getConnection().execute()` converts errors to custom exceptions.
  • Loading branch information
B4nan committed Aug 9, 2020
1 parent 2c30679 commit e389d40
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
8 changes: 6 additions & 2 deletions packages/knex/src/SqlEntityManager.ts
@@ -1,5 +1,5 @@
import Knex from 'knex';
import { AnyEntity, EntityManager, EntityName, EntityRepository, Utils } from '@mikro-orm/core';
import Knex, { QueryBuilder as KnexQueryBuilder, Raw } from 'knex';
import { AnyEntity, EntityData, EntityManager, EntityName, EntityRepository, QueryResult, Utils } from '@mikro-orm/core';
import { AbstractSqlDriver } from './AbstractSqlDriver';
import { QueryBuilder } from './query';
import { SqlEntityRepository } from './SqlEntityRepository';
Expand All @@ -21,6 +21,10 @@ export class SqlEntityManager<D extends AbstractSqlDriver = AbstractSqlDriver> e
return this.getConnection(type).getKnex();
}

async execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | KnexQueryBuilder | Raw, params: any[] = [], method: 'all' | 'get' | 'run' = 'all'): Promise<T> {
return this.getDriver().execute(queryOrKnex, params, method, this.getTransactionContext());
}

getRepository<T extends AnyEntity<T>, U extends EntityRepository<T> = SqlEntityRepository<T>>(entityName: EntityName<T>): U {
return super.getRepository<T, U>(entityName);
}
Expand Down
7 changes: 7 additions & 0 deletions tests/EntityManager.mysql.test.ts
Expand Up @@ -1976,6 +1976,13 @@ describe('EntityManagerMySql', () => {
await expect(driver.execute('select uuid from author2')).rejects.toThrow(InvalidFieldNameException);
});

test('em.execute()', async () => {
const res1 = await orm.em.execute('insert into author2 (name, email) values (?, ?)', ['name', 'email']);
expect(res1).toMatchObject({ affectedRows: 1, insertId: 1 });
const res2 = await orm.em.execute('select 1 as count');
expect(res2).toMatchObject([{ count: 1 }]);
});

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

});

0 comments on commit e389d40

Please sign in to comment.