Skip to content

Commit e0f0108

Browse files
authored
feat: SQL performance optimization to count instances (#9369)
1 parent 4515925 commit e0f0108

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

src/lib/db/client-instance-store.ts

+20-11
Original file line numberDiff line numberDiff line change
@@ -253,17 +253,26 @@ export default class ClientInstanceStore implements IClientInstanceStore {
253253
}
254254

255255
async getDistinctApplicationsCount(daysBefore?: number): Promise<number> {
256-
let query = this.db.from(TABLE);
257-
if (daysBefore) {
258-
query = query.where(
259-
'last_seen',
260-
'>',
261-
subDays(new Date(), daysBefore),
262-
);
263-
}
264-
return query
265-
.countDistinct('app_name')
266-
.then((res) => Number(res[0].count));
256+
const query = this.db
257+
.from((qb) =>
258+
qb
259+
.select('app_name')
260+
.from(TABLE)
261+
.modify((qb) => {
262+
if (daysBefore) {
263+
qb.where(
264+
'last_seen',
265+
'>',
266+
subDays(new Date(), daysBefore),
267+
);
268+
}
269+
})
270+
.groupBy('app_name')
271+
.as('subquery'),
272+
)
273+
.count('* as count');
274+
275+
return query.then((res) => Number(res[0].count));
267276
}
268277

269278
async deleteForApplication(appName: string): Promise<void> {

0 commit comments

Comments
 (0)