Commit b3ee4f99 authored by Stan Hu's avatar Stan Hu
Browse files

Reduce SQL queries needed to load open merge requests

The SQL queries and memory allocation in MergeRequests::RefreshService
is dominated by queries for Project and Route loads. On staging, the
absence of an inverse relationship caused Rails to make over 1100
extraneous SQL queries for the www-gitlab-com repository.

Relates to
parent d4dd80f20ccc
......@@ -181,7 +181,7 @@
has_one :import_export_upload, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
# Merge Requests for target project should be removed with it
has_many :merge_requests, foreign_key: 'target_project_id'
has_many :merge_requests, foreign_key: 'target_project_id', inverse_of: :target_project
has_many :source_of_merge_requests, foreign_key: 'source_project_id', class_name: 'MergeRequest'
has_many :issues
has_many :labels, class_name: 'ProjectLabel'
title: Reduce SQL queries needed to load open merge requests
merge_request: 22709
type: performance
......@@ -22,7 +22,7 @@
# additional work that is strictly necessary.
merge_request_id = insert_and_return_id(attributes, project.merge_requests)
merge_request = project.merge_requests.find(merge_request_id)
merge_request = project.merge_requests.reload.find(merge_request_id)
# We use .insert_and_return_id which effectively disables all callbacks.
# Trigger iid logic here to make sure we track internal id values consistently.
......@@ -13,6 +13,20 @@
it { belong_to(:merge_user).class_name("User") }
it { belong_to(:assignee) }
it { have_many(:merge_request_diffs) }
context 'for forks' do
let!(:project) { create(:project) }
let!(:fork) { fork_project(project) }
let!(:merge_request) { create(:merge_request, target_project: project, source_project: fork) }
it 'does not load another project due to inverse relationship' do
expect(project.merge_requests.first.target_project.object_id).to eq(project.object_id)
it 'finds the associated merge request' do
expect(project.merge_requests.find( eq(merge_request)
describe '#squash_in_progress?' do
......@@ -88,6 +88,10 @@
it { have_many(:project_deploy_tokens) }
it { have_many(:deploy_tokens).through(:project_deploy_tokens) }
it 'has an inverse relationship with merge requests' do
expect(described_class.reflect_on_association(:merge_requests).has_inverse?).to eq(:target_project)
context 'after initialized' do
it "has a project_feature" do
expect( be_present
Supports Markdown
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