Skip to content

Commit 70597fe

Browse files
authored
[O2B-1544] Fix pagination for filtered envs and add a test (#2096)
* Replaced the two-query pattern with a single queryBuilder in GetAllEnvironmentsUseCase. The previous approach was redundant following Sequelize performance improvements; furthermore, the original implementation's logic was flawed which resulted in the pagination bug.
1 parent 55062b6 commit 70597fe

2 files changed

Lines changed: 50 additions & 33 deletions

File tree

lib/usecases/environment/GetAllEnvironmentsUseCase.js

Lines changed: 14 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -69,18 +69,11 @@ class GetAllEnvironmentsUseCase {
6969
const { filter, page = {} } = query;
7070
const { limit = ApiConfig.pagination.limit, offset = 0 } = page;
7171

72-
/**
73-
* Prepare a query builder with ordering, limit and offset
74-
*
75-
* @return {QueryBuilder} the created query builder
76-
*/
77-
const prepareQueryBuilder = () => dataSource.createQueryBuilder()
72+
const queryBuilder = dataSource.createQueryBuilder()
7873
.orderBy('updatedAt', 'desc')
7974
.limit(limit)
8075
.offset(offset);
8176

82-
const fetchQueryBuilder = prepareQueryBuilder();
83-
8477
if (filter) {
8578
const {
8679
ids: idsExpression,
@@ -90,38 +83,36 @@ class GetAllEnvironmentsUseCase {
9083
created,
9184
} = filter;
9285

93-
const filterQueryBuilder = prepareQueryBuilder();
94-
9586
if (created) {
9687
const from = created.from !== undefined ? created.from : 0;
9788
const to = created.to !== undefined ? created.to : Date.now();
98-
filterQueryBuilder.where('createdAt').between(from, to);
89+
queryBuilder.where('createdAt').between(from, to);
9990
}
10091

10192
if (idsExpression) {
10293
const filters = idsExpression.split(',').map((id) => id.trim());
10394

10495
// Filter should be like with only one filter
10596
if (filters.length === 1) {
106-
filterQueryBuilder.where('id').substring(filters[0]);
97+
queryBuilder.where('id').substring(filters[0]);
10798
}
10899

109100
// Filters should be exact with more than one filter
110101
if (filters.length > 1) {
111-
filterQueryBuilder.andWhere({ id: { [Op.in]: filters } });
102+
queryBuilder.andWhere({ id: { [Op.in]: filters } });
112103
}
113104
}
114105

115106
if (currentStatusExpression) {
116107
const filters = currentStatusExpression.split(',').map((status) => status.trim());
117108

118109
// Filter the environments by current status using the subquery
119-
filterQueryBuilder.literalWhere(
110+
queryBuilder.literalWhere(
120111
`${ENVIRONMENT_LATEST_HISTORY_ITEM_SUBQUERY} IN (:filters)`,
121112
{ filters },
122113
);
123114

124-
filterQueryBuilder.includeAttribute({
115+
queryBuilder.includeAttribute({
125116
query: ENVIRONMENT_LATEST_HISTORY_ITEM_SUBQUERY,
126117
alias: 'currentStatus',
127118
});
@@ -157,7 +148,7 @@ class GetAllEnvironmentsUseCase {
157148
* Use OR condition to match subsequences ending with either DESTROYED or DONE
158149
* Filter the environments by using LIKE for subsequence matching
159150
*/
160-
filterQueryBuilder.literalWhere(
151+
queryBuilder.literalWhere(
161152
`(${ENVIRONMENT_STATUS_HISTORY_SUBQUERY} LIKE :statusFiltersWithDestroyed OR ` +
162153
`${ENVIRONMENT_STATUS_HISTORY_SUBQUERY} LIKE :statusFiltersWithDone)`,
163154
{
@@ -166,17 +157,17 @@ class GetAllEnvironmentsUseCase {
166157
},
167158
);
168159

169-
filterQueryBuilder.includeAttribute({
160+
queryBuilder.includeAttribute({
170161
query: ENVIRONMENT_STATUS_HISTORY_SUBQUERY,
171162
alias: 'statusHistory',
172163
});
173164
} else {
174-
filterQueryBuilder.literalWhere(
165+
queryBuilder.literalWhere(
175166
`${ENVIRONMENT_STATUS_HISTORY_SUBQUERY} LIKE :statusFilters`,
176167
{ statusFilters: `%${statusFilters.join(',')}%` },
177168
);
178169

179-
filterQueryBuilder.includeAttribute({
170+
queryBuilder.includeAttribute({
180171
query: ENVIRONMENT_STATUS_HISTORY_SUBQUERY,
181172
alias: 'statusHistory',
182173
});
@@ -190,30 +181,20 @@ class GetAllEnvironmentsUseCase {
190181

191182
// Check that the final run numbers list contains at least one valid run number
192183
if (finalRunNumberList.length > 0) {
193-
filterQueryBuilder.include({
184+
queryBuilder.include({
194185
association: 'runs',
195186
where: {
196187
// Filter should be like with only one filter and exact with more than one filter
197188
runNumber: { [finalRunNumberList.length === 1 ? Op.substring : Op.in]: finalRunNumberList },
198189
},
199190
});
200191
}
201-
};
202-
203-
const filteredEnvironmentsIds = (await EnvironmentRepository.findAll(filterQueryBuilder)).map(({ id }) => id);
204-
// If no environments match the filter, return an empty result
205-
if (filteredEnvironmentsIds.length === 0) {
206-
return {
207-
count: 0,
208-
environments: [],
209-
};
210192
}
211-
fetchQueryBuilder.where('id').oneOf(filteredEnvironmentsIds);
212193
}
213194

214-
fetchQueryBuilder.include({ association: 'runs' });
215-
fetchQueryBuilder.include({ association: 'historyItems' });
216-
const { count, rows } = await EnvironmentRepository.findAndCountAll(fetchQueryBuilder);
195+
queryBuilder.include({ association: 'runs' });
196+
queryBuilder.include({ association: 'historyItems' });
197+
const { count, rows } = await EnvironmentRepository.findAndCountAll(queryBuilder);
217198
return {
218199
count,
219200
environments: rows.map((environment) => environmentAdapter.toEntity(environment)),

test/lib/usecases/environment/GetAllEnvironmentsUseCase.test.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,4 +225,40 @@ module.exports = () => {
225225
expect(environments).to.be.an('array');
226226
expect(environments.length).to.be.equal(0); // Environments from seeders
227227
});
228+
229+
it('should return correct total count and all filtered results across pages', async () => {
230+
const totalMatchingFilter = 6; // 'RUNNING, ERROR' matches 6 environments at this point
231+
const limit = 2;
232+
233+
// First page
234+
getAllEnvsDto.query = { page: { limit, offset: 0 }, filter: { currentStatus: 'RUNNING, ERROR' } };
235+
const page1 = await new GetAllEnvironmentsUseCase().execute(getAllEnvsDto);
236+
237+
expect(page1.count).to.be.equal(totalMatchingFilter);
238+
expect(page1.environments).to.be.an('array');
239+
expect(page1.environments.length).to.be.equal(limit);
240+
241+
// Second page
242+
getAllEnvsDto.query = { page: { limit, offset: 2 }, filter: { currentStatus: 'RUNNING, ERROR' } };
243+
const page2 = await new GetAllEnvironmentsUseCase().execute(getAllEnvsDto);
244+
245+
expect(page2.count).to.be.equal(totalMatchingFilter);
246+
expect(page2.environments).to.be.an('array');
247+
expect(page2.environments.length).to.be.equal(limit);
248+
249+
// Third page
250+
getAllEnvsDto.query = { page: { limit, offset: 4 }, filter: { currentStatus: 'RUNNING, ERROR' } };
251+
const page3 = await new GetAllEnvironmentsUseCase().execute(getAllEnvsDto);
252+
253+
expect(page3.count).to.be.equal(totalMatchingFilter);
254+
expect(page3.environments).to.be.an('array');
255+
expect(page3.environments.length).to.be.equal(limit);
256+
257+
// Collect all environment IDs and verify no duplicates and all present
258+
const allIds = [page1, page2, page3].flatMap(({ environments })=> environments.map(({ id }) => id));
259+
260+
expect(allIds.length).to.be.equal(totalMatchingFilter);
261+
expect(new Set(allIds).size).to.be.equal(totalMatchingFilter);
262+
expect(allIds).to.have.members(['SomeId', 'newId', 'CmCvjNbg', 'EIDO13i3D', '8E4aZTjY', 'Dxi029djX']);
263+
});
228264
};

0 commit comments

Comments
 (0)