Skip to content

Commit

Permalink
fix: make project ui query optimized
Browse files Browse the repository at this point in the history
  • Loading branch information
sjaanus committed Dec 11, 2024
1 parent 8c189ca commit 9312f03
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/lib/features/project/project-read-model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ afterAll(async () => {
beforeEach(async () => {
await projectStore.deleteAll();
await flagStore.deleteAll();
await eventStore.deleteAll();
});

test("it doesn't count flags multiple times when they have multiple events associated with them", async () => {
Expand Down
22 changes: 15 additions & 7 deletions src/lib/features/project/project-read-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,14 @@ export class ProjectReadModel implements IProjectReadModel {
userId?: number,
): Promise<ProjectForUi[]> {
const projectTimer = this.timer('getProjectsForAdminUi');
let projects = this.db(TABLE)
let projects = this.db
.with('latest_events', (qb) => {
qb.select('project', 'feature_name')
.max('created_at as last_updated')
.whereNotNull('feature_name')
.from('events')
.groupBy('project', 'feature_name');
})
.leftJoin('features', 'features.project', 'projects.id')
.leftJoin(
'last_seen_at_metrics',
Expand All @@ -95,13 +102,14 @@ export class ProjectReadModel implements IProjectReadModel {
'project_settings.project',
'projects.id',
)
.leftJoin('events', (join) => {
join.on('events.feature_name', '=', 'features.name').andOn(
'events.project',
.leftJoin('latest_events', (join) => {
join.on(
'latest_events.feature_name',
'=',
'projects.id',
);
'features.name',
).andOn('latest_events.project', '=', 'projects.id');
})
.from(TABLE)
.orderBy('projects.name', 'asc');

if (query?.archived === true) {
Expand All @@ -122,7 +130,7 @@ export class ProjectReadModel implements IProjectReadModel {
'projects.id, projects.name, projects.description, projects.health, projects.created_at, ' +
'count(DISTINCT features.name) FILTER (WHERE features.archived_at is null) AS number_of_features, ' +
'MAX(last_seen_at_metrics.last_seen_at) AS last_usage, ' +
'MAX(events.created_at) AS last_updated',
'MAX(latest_events.last_updated) AS last_updated',
),
'project_settings.project_mode',
'projects.archived_at',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

exports.up = function (db, callback) {
db.runSql(
`
CREATE INDEX idx_events_project_feature_created
ON events (project, feature_name, created_at DESC);
`,
callback,
);
};

exports.down = function (db, callback) {
db.runSql(
`
DROP INDEX idx_events_project_feature_created;
`,
callback,
);
};

0 comments on commit 9312f03

Please sign in to comment.