Commit 9b90bbad authored by Oswaldo Ferreira's avatar Oswaldo Ferreira

Refactor plain SQL to active record relations 🚀

parent 567ab58d
...@@ -35,6 +35,12 @@ class Issue < ActiveRecord::Base ...@@ -35,6 +35,12 @@ class Issue < ActiveRecord::Base
has_many :issue_assignees has_many :issue_assignees
has_many :assignees, class_name: "User", through: :issue_assignees has_many :assignees, class_name: "User", through: :issue_assignees
has_many :referenced_issue_links, class_name: 'IssueLink', foreign_key: :source_id
has_many :referred_by_issue_links, class_name: 'IssueLink', foreign_key: :target_id
has_many :referenced_issues, through: :referenced_issue_links, source: :target
has_many :referred_by_issues, through: :referred_by_issue_links, source: :source
validates :project, presence: true validates :project, presence: true
scope :in_projects, ->(project_ids) { where(project_id: project_ids) } scope :in_projects, ->(project_ids) { where(project_id: project_ids) }
......
...@@ -26,21 +26,13 @@ module IssueLinks ...@@ -26,21 +26,13 @@ module IssueLinks
def issues def issues
return @issues if defined?(@issues) return @issues if defined?(@issues)
# TODO: Simplify query using AR referenced_issues = @issue.referenced_issues.select('issues.*', 'issue_links.id AS issue_links_id')
@issues = Issue.find_by_sql( referred_by_issues = @issue.referred_by_issues.select('issues.*', 'issue_links.id AS issue_links_id')
<<-SQL.strip_heredoc union = Gitlab::SQL::Union.new([referenced_issues, referred_by_issues])
SELECT issues.*, issue_links.id as issue_links_id FROM issues
INNER JOIN issue_links ON issue_links.target_id = issues.id
WHERE issue_links.source_id = #{@issue.id} AND issues.deleted_at IS NULL
UNION ALL
SELECT issues.*, issue_links.id as issue_links_id FROM issues
INNER JOIN issue_links ON issue_links.source_id = issues.id
WHERE issue_links.target_id = #{@issue.id} AND issues.deleted_at IS NULL
ORDER BY issue_links_id
SQL
)
# TODO: Try to use SQL instead Array#select sql = "#{union.to_sql} ORDER BY issue_links_id"
@issues = Issue.find_by_sql(sql)
@issues = Ability.issues_readable_by_user(@issues, @current_user) @issues = Ability.issues_readable_by_user(@issues, @current_user)
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