Skip to content

Commit

Permalink
fix(query-builder): fix calling qb.count('id', true).getCount()
Browse files Browse the repository at this point in the history
Closes #3182
  • Loading branch information
B4nan committed Jun 5, 2022
1 parent ff85817 commit a97324a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/knex/src/query/QueryBuilder.ts
Expand Up @@ -529,6 +529,11 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {
* Executes count query (without offset and limit), returning total count of results
*/
async getCount(field?: string | string[], distinct?: boolean): Promise<number> {
if (this.type === QueryType.COUNT) {
const res = await this.execute<{ count: number }>('get', false);
return res ? +res.count : 0;
}

const qb = this.clone();
qb.count(field, distinct ?? qb.hasToManyJoins()).limit(undefined).offset(undefined).orderBy([]);
const res = await qb.execute<{ count: number }>('get', false);
Expand Down
5 changes: 5 additions & 0 deletions tests/QueryBuilder.test.ts
Expand Up @@ -1370,6 +1370,11 @@ describe('QueryBuilder', () => {
await qb.where({ price: orm.em.raw('price + 1') }).getCount();
});

test('gh issue 3182', async () => {
const qb = orm.em.createQueryBuilder(Author2);
await qb.count('id', true).getCount();
});

test('update query with JSON type and raw value', async () => {
const qb = orm.em.createQueryBuilder(Book2);
const raw = qb.raw<any>(`jsonb_set(payload, '$.{consumed}', ?)`, [123]);
Expand Down

0 comments on commit a97324a

Please sign in to comment.