OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Prevent N+1 issue when displaying project activities
Christophe Bliardc1202db64a0e
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rbindex dd66be72967..d585765b4f4 100644--- a/app/controllers/activities_controller.rb+++ b/app/controllers/activities_controller.rb@@ -91,6 +91,12 @@ class ActivitiesController < ApplicationControllerdef respond_html(events)@events_by_day = events.group_by { |e| e.event_datetime.in_time_zone(User.current.time_zone).to_date }+ @journals_by_id = Journal+ .includes(:data, :customizable_journals, :attachable_journals, :bcf_comment)+ .find(events.pluck(:event_id))+ .then { |journals| ::API::V3::Activities::ActivityEagerLoadingWrapper.wrap(journals) }+ .index_by(&:id)+render layout: !request.xhr?enddiff --git a/app/models/changeset.rb b/app/models/changeset.rbindex 4009afd998f..755610e3a06 100644--- a/app/models/changeset.rb+++ b/app/models/changeset.rb@@ -28,6 +28,7 @@class Changeset < ApplicationRecordbelongs_to :repository+ has_one :project, through: :repositorybelongs_to :userhas_many :file_changes, class_name: 'Change', dependent: :delete_allhas_and_belongs_to_many :work_packages@@ -92,8 +93,6 @@ class Changeset < ApplicationRecordendend- delegate :project, to: :repository-def authoruser || committer.to_s.split('<').firstenddiff --git a/app/models/wiki_content.rb b/app/models/wiki_content.rbindex 39154eaee69..a0c3de7ce3e 100644--- a/app/models/wiki_content.rb+++ b/app/models/wiki_content.rb@@ -30,6 +30,7 @@ class WikiContent < ApplicationRecordextend DeprecatedAliasbelongs_to :page, class_name: 'WikiPage'+ has_one :project, through: :pagebelongs_to :author, class_name: 'User'acts_as_journalized@@ -52,8 +53,6 @@ class WikiContent < ApplicationRecordpage.visible?(user)end- delegate :project, to: :page-def attachmentspage.nil? ? [] : page.attachmentsenddiff --git a/app/views/activities/index.html.erb b/app/views/activities/index.html.erbindex fab3ca7713d..21c60bf99af 100644--- a/app/views/activities/index.html.erb+++ b/app/views/activities/index.html.erb@@ -38,6 +38,7 @@ See COPYRIGHT and LICENSE files for more details.<h3 class="op-project-activity-days--header"><%= format_activity_day(day) %></h3><ul class="op-project-activity-list"><% @events_by_day[day].sort { |x, y| y.event_datetime <=> x.event_datetime }.each_with_index do |e, index| -%>+ <% journal = @journals_by_id[e.event_id] %><li class="op-project-activity-list--item"><div class="op-project-activity-list--item-title">@@ -57,10 +58,10 @@ See COPYRIGHT and LICENSE files for more details.</div><% end -%>- <% if e.journal.details.any? -%>+ <% if journal.details.any? -%><ul class="op-project-activity-list--item-details">- <% e.journal.details.each do |detail| -%>- <li class="op-project-activity-list--item-detail"><%= e.journal.render_detail(detail) %></li>+ <% journal.details.each do |detail| -%>+ <li class="op-project-activity-list--item-detail"><%= journal.render_detail(detail) %></li><% end -%></ul><% end -%>diff --git a/lib/api/v3/activities/activity_eager_loading_wrapper.rb b/lib/api/v3/activities/activity_eager_loading_wrapper.rbindex 86c2eccc594..db1963d7d25 100644--- a/lib/api/v3/activities/activity_eager_loading_wrapper.rb+++ b/lib/api/v3/activities/activity_eager_loading_wrapper.rb@@ -73,14 +73,20 @@ module APIenddef journable_by_type_and_id(journals)- journals.map(&:journable_type).uniq.each_with_object(Hash.new([])) do |class_name, hash|- hash[class_name] = class_name- .constantize- .where(id: journals.map(&:journable_id))- .includes(:project)- .group_by(&:id)- .transform_values(&:first)- end+ journals+ .group_by(&:journable_type)+ .each_with_object({}) do |(journable_type, journable_type_journals), hash|+ journable_ids = journable_type_journals.map(&:journable_id).uniq+ hash[journable_type] = journable_type+ .constantize+ .where(id: journable_ids)+ .includes(includes_for(journable_type))+ .index_by(&:id)+ end+ end++ def includes_for(journable_type)+ journable_type == 'Project' ? [] : [:project]enddef data_by_type_and_id(journals)@@ -89,13 +95,12 @@ module API# * previous has already been loaded by #set_predecessorjournals.group_by(&:data_type)- .each_with_object(Hash.new({})) do |(class_name, class_journals), hash|- hash[class_name] = class_name- .constantize- .find(data_ids(class_journals))- .group_by(&:id)- .transform_values(&:first)- end+ .each_with_object({}) do |(data_type, data_type_journals), hash|+ hash[data_type] = data_type+ .constantize+ .find(data_ids(data_type_journals))+ .index_by(&:id)+ endenddef predecessors_by_type_and_id(journals)@@ -119,14 +124,13 @@ module API.from(<<~SQL.squish(SELECT DISTINCT ON (predecessors.journable_type, predecessors.journable_id, current.version)- predecessors.*+ predecessors.*FROM- #{Journal.arel_table.grouping(Arel::Nodes::ValuesList.new(current)).as('current(journable_type, journable_id, version)').to_sql}+ #{Journal.arel_table.grouping(Arel::Nodes::ValuesList.new(current)).as('current(journable_type, journable_id, version)').to_sql}JOIN journals predecessors- ON- current.journable_type = predecessors.journable_type- AND current.journable_id = predecessors.journable_id- AND current.version > predecessors.version+ ON current.journable_type = predecessors.journable_type+ AND current.journable_id = predecessors.journable_id+ AND current.version > predecessors.versionORDER BY predecessors.journable_type, predecessors.journable_id, current.version, predecessors.version DESC) AS journalsSQLdiff --git a/modules/meeting/app/models/meeting_content.rb b/modules/meeting/app/models/meeting_content.rbindex 7f66b95175c..2bddf2f126f 100644--- a/modules/meeting/app/models/meeting_content.rb+++ b/modules/meeting/app/models/meeting_content.rb@@ -31,6 +31,8 @@ class MeetingContent < ApplicationRecordinclude OpenProject::Journal::AttachmentHelperbelongs_to :meeting+ # Show the project on activity and search views+ has_one :project, through: :meetingbelongs_to :author, class_name: 'User'acts_as_attachable(@@ -69,7 +71,4 @@ class MeetingContent < ApplicationRecord.where(version:).first.dataend-- # Show the project on activity and search views- delegate :project, to: :meetingenddiff --git a/spec/factories/changeset_factory.rb b/spec/factories/changeset_factory.rbindex f5623d235ee..23db983c76d 100644--- a/spec/factories/changeset_factory.rb+++ b/spec/factories/changeset_factory.rb@@ -29,7 +29,13 @@FactoryBot.define dofactory :changeset dosequence(:revision) { |n| n.to_s }- committed_on { Time.now }- commit_date { Date.today }+ committed_on { Time.current }+ commit_date { Date.current }++ after(:build, :create) do |changeset, evaluator|+ next if evaluator.overrides?(:project)++ changeset.project ||= changeset.repository&.project+ endendenddiff --git a/spec/lib/api/v3/activities/activity_eager_loading_wrapper_spec.rb b/spec/lib/api/v3/activities/activity_eager_loading_wrapper_spec.rbnew file mode 100644index 00000000000..90bb8c49a3d--- /dev/null+++ b/spec/lib/api/v3/activities/activity_eager_loading_wrapper_spec.rb@@ -0,0 +1,121 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2022 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#++++require 'spec_helper'++RSpec.describe API::V3::Activities::ActivityEagerLoadingWrapper, with_settings: { journal_aggregation_time_minutes: 0 } do+ shared_let(:user) { create(:user) }+ shared_let(:project) { create(:project) }+ shared_let(:work_package) { create(:work_package, project:, author: user) }+ shared_let(:meeting) { create(:meeting, project:, author: user) }++ describe '.wrap' do+ it 'returns wrapped journals with relations eager loaded' do+ 9.times { |i| work_package.update(subject: "Subject ##{i}") }++ journals = Journal.for_work_package+ wrapped_journals = described_class.wrap(journals)++ expect(wrapped_journals.size).to eq(journals.size)+ wrapped_journals.each do |loaded_journal|+ expect(loaded_journal.__getobj__.instance_variables).to include(:@predecessor)+ %i[journable data].each do |association|+ expect(loaded_journal.association_cached?(association)).to be true+ end+ end+ end++ it 'can wrap Project journals' do+ expect(project.journals).to be_wrappable+ end++ it 'can wrap Document journals' do+ document = create(:document, project:)+ expect(document.journals).to be_wrappable+ end++ it 'can wrap TimeEntry journals' do+ time_entry = create(:time_entry, project:, work_package:, user:)+ expect(time_entry.journals).to be_wrappable+ end++ it 'can wrap Meeting journals' do+ expect(meeting.journals).to be_wrappable+ end++ it 'can wrap MeetingAgenda journals' do+ meeting_agenda = create(:meeting_agenda, meeting:)+ expect(meeting_agenda.journals).to be_wrappable+ end++ it 'can wrap MeetingMinutes journals' do+ meeting_minutes = create(:meeting_minutes, meeting:)+ expect(meeting_minutes.journals).to be_wrappable+ end++ it 'can wrap Budget journals' do+ budget = create(:budget, project:, author: user)+ expect(budget.journals).to be_wrappable+ end++ it 'can wrap WorkPackage journals' do+ expect(work_package.journals).to be_wrappable+ end++ it 'can wrap Changeset journals' do+ changeset = create(:changeset, repository: create(:repository_git, project:))+ expect(changeset.journals).to be_wrappable+ end++ it 'can wrap News journals' do+ news = create(:news, project:, author: user)+ expect(news.journals).to be_wrappable+ end++ it 'can wrap WikiContent journals' do+ wiki_content = create(:wiki_content, author: user)+ expect(wiki_content.journals).to be_wrappable+ end++ it 'can wrap Message journals' do+ message = create(:message, author: user)+ expect(message.journals).to be_wrappable+ end+ end+end++RSpec::Matchers.define :be_wrappable do+ match do |journals|+ wrapped_journals = described_class.wrap(journals)+ wrapped_journals.size == journals.size+ end++ failure_message do |journals|+ "expected that wrapped size of journals would match the size of journals (#{journals.size})"+ end+end