Commit 66d48385 authored by 🙈  jacopo beschi 🙉's avatar 🙈 jacopo beschi 🙉 Committed by Mayra Cabrera

Resolve "MembersFinder contains slow database query with OR conditions"

parent 18e3dcc6
# frozen_string_literal: true # frozen_string_literal: true
class GroupMembersFinder class GroupMembersFinder < UnionFinder
def initialize(group) def initialize(group)
@group = group @group = group
end end
...@@ -8,18 +8,18 @@ class GroupMembersFinder ...@@ -8,18 +8,18 @@ class GroupMembersFinder
# rubocop: disable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord
def execute(include_descendants: false) def execute(include_descendants: false)
group_members = @group.members group_members = @group.members
wheres = [] relations = []
return group_members unless @group.parent || include_descendants return group_members unless @group.parent || include_descendants
wheres << "members.id IN (#{group_members.select(:id).to_sql})" relations << group_members
if @group.parent if @group.parent
parents_members = GroupMember.non_request parents_members = GroupMember.non_request
.where(source_id: @group.ancestors.select(:id)) .where(source_id: @group.ancestors.select(:id))
.where.not(user_id: @group.users.select(:id)) .where.not(user_id: @group.users.select(:id))
wheres << "members.id IN (#{parents_members.select(:id).to_sql})" relations << parents_members
end end
if include_descendants if include_descendants
...@@ -27,10 +27,10 @@ class GroupMembersFinder ...@@ -27,10 +27,10 @@ class GroupMembersFinder
.where(source_id: @group.descendants.select(:id)) .where(source_id: @group.descendants.select(:id))
.where.not(user_id: @group.users.select(:id)) .where.not(user_id: @group.users.select(:id))
wheres << "members.id IN (#{descendant_members.select(:id).to_sql})" relations << descendant_members
end end
GroupMember.where(wheres.join(' OR ')) find_union(relations, GroupMember)
end end
# rubocop: enable CodeReuse/ActiveRecord # rubocop: enable CodeReuse/ActiveRecord
end end
# frozen_string_literal: true # frozen_string_literal: true
class GroupMember < Member class GroupMember < Member
include FromUnion
SOURCE_TYPE = 'Namespace'.freeze SOURCE_TYPE = 'Namespace'.freeze
belongs_to :group, foreign_key: 'source_id' belongs_to :group, foreign_key: 'source_id'
......
---
title: Improve MembersFinder query performance using UNION
merge_request: 30451
author: Jacopo Beschi @jacopo-beschi
type: performance
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