Commit d41db64a authored by Grzegorz Bizon's avatar Grzegorz Bizon

Merge branch 'sk/27202-fix-duplicate-queries' into 'master'

Refactor count queries in Projects::EnvironmentsController

See merge request gitlab-org/gitlab!30073
parents 9df72e08 e81146fc
......@@ -27,12 +27,13 @@ class Projects::EnvironmentsController < Projects::ApplicationController
format.html
format.json do
Gitlab::PollingInterval.set_header(response, interval: 3_000)
environments_count_by_state = project.environments.count_by_state
render json: {
environments: serialize_environments(request, response, params[:nested]),
review_app: serialize_review_app,
available_count: project.environments.available.count,
stopped_count: project.environments.stopped.count
available_count: environments_count_by_state[:available],
stopped_count: environments_count_by_state[:stopped]
}
end
end
......
......@@ -152,6 +152,14 @@ class Environment < ApplicationRecord
.preload(:user, :metadata, :deployment)
end
def count_by_state
environments_count_by_state = group(:state).count
valid_states.each_with_object({}) do |state, count_hash|
count_hash[state] = environments_count_by_state[state.to_s] || 0
end
end
private
def cte_for_deployments_with_stop_action
......
---
title: Refactor count queries to single query on Projects::EnvironmentsController
merge_request: 30073
author: Sashi Kumar
type: other
......@@ -1311,4 +1311,25 @@ describe Environment, :use_clean_rails_memory_store_caching do
expect { environment.destroy }.to change { project.commit(deployment.ref_path) }.to(nil)
end
end
describe '.count_by_state' do
context 'when environments are not empty' do
let!(:environment1) { create(:environment, project: project, state: 'stopped') }
let!(:environment2) { create(:environment, project: project, state: 'available') }
let!(:environment3) { create(:environment, project: project, state: 'stopped') }
it 'returns the environments count grouped by state' do
expect(project.environments.count_by_state).to eq({ stopped: 2, available: 1 })
end
it 'returns the environments count grouped by state with zero value' do
environment2.update(state: 'stopped')
expect(project.environments.count_by_state).to eq({ stopped: 3, available: 0 })
end
end
it 'returns zero state counts when environments are empty' do
expect(project.environments.count_by_state).to eq({ stopped: 0, available: 0 })
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment