Skip to content

Commit

Permalink
perf(query-typeorm): Custom count implementation for better performance
Browse files Browse the repository at this point in the history
  • Loading branch information
TriPSs committed Feb 9, 2024
1 parent 63d3248 commit eb89f32
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion packages/query-typeorm/src/services/typeorm-query.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,27 @@ export class TypeOrmQueryService<Entity>
qb.withDeleted()
}

return qb.getCount()
// Check if we have any relation that could return the same record twice, if not than we create
// our own count as TypeORM still decides to add "DISTINCT" to it which makes it slow
const hasManyRelation = qb.expressionMap.joinAttributes.some((join) => join.isMany)
if (hasManyRelation) {
// If we have relations than just do what TypeORM does
return qb.getCount()
}

// This is the same as TypeORM does it with the exception that the select is always COUNT(1)
const result = (await qb
.orderBy()
.groupBy()
.offset(undefined)
.limit(undefined)
.skip(undefined)
.take(undefined)
.select('COUNT(1)', 'cnt')
.setOption('disable-global-order')
.execute()) as { cnt?: number }[]

return result?.[0]?.cnt ?? 0
}

/**
Expand Down

0 comments on commit eb89f32

Please sign in to comment.