Commit dac25abd authored by Shinya Maeda's avatar Shinya Maeda

Optimize the query on Environment Detail page

This commit adds the database index to optimize the
query on Environment Detail page.

Changelog: performance
parent c47fce53
......@@ -46,7 +46,7 @@ class Deployment < ApplicationRecord
scope :for_project, -> (project_id) { where(project_id: project_id) }
scope :for_projects, -> (projects) { where(project: projects) }
scope :visible, -> { where(status: %i[running success failed canceled blocked]) }
scope :visible, -> { where(status: VISIBLE_STATUSES) }
scope :stoppable, -> { where.not(on_stop: nil).where.not(deployable_id: nil).success }
scope :active, -> { where(status: %i[created running]) }
scope :upcoming, -> { where(status: %i[blocked running]) }
......@@ -58,6 +58,7 @@ class Deployment < ApplicationRecord
scope :ordered, -> { order(finished_at: :desc) }
VISIBLE_STATUSES = %i[running success failed canceled blocked].freeze
FINISHED_STATUSES = %i[success failed canceled].freeze
state_machine :status, initial: :created do
......
# frozen_string_literal: true
class AddIndexOnVisibleDeployments < Gitlab::Database::Migration[1.0]
disable_ddl_transaction!
INDEX_NAME = 'index_deployments_for_visible_scope'
def up
add_concurrent_index :deployments,
[:environment_id, :finished_at],
order: { finished_at: :desc },
where: 'status IN (1, 2, 3, 4, 6)',
name: INDEX_NAME
end
def down
remove_concurrent_index_by_name :deployments, INDEX_NAME
end
end
47b87d4ea5d081904d561e461a266fe20dfcc1f771126340cf14c84302d3383d
\ No newline at end of file
......@@ -27408,6 +27408,8 @@ CREATE UNIQUE INDEX index_deployment_clusters_on_cluster_id_and_deployment_id ON
CREATE INDEX index_deployment_merge_requests_on_merge_request_id ON deployment_merge_requests USING btree (merge_request_id);
CREATE INDEX index_deployments_for_visible_scope ON deployments USING btree (environment_id, finished_at DESC) WHERE (status = ANY (ARRAY[1, 2, 3, 4, 6]));
CREATE INDEX index_deployments_on_archived_project_id_iid ON deployments USING btree (archived, project_id, iid);
CREATE INDEX index_deployments_on_cluster_id_and_status ON deployments USING btree (cluster_id, status);
......@@ -524,6 +524,16 @@ RSpec.describe Deployment do
is_expected.to contain_exactly(deployment1, deployment2, deployment3, deployment4, deployment5)
end
it 'has a corresponding database index' do
index = ApplicationRecord.connection.indexes('deployments').find do |i|
i.name == 'index_deployments_for_visible_scope'
end
scope_values = described_class::VISIBLE_STATUSES.map { |s| described_class.statuses[s] }.to_s
expect(index.where).to include(scope_values)
end
end
describe 'upcoming' do
......
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