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
[#45414] [AppSignal] SearchController#index response time is very slow (more than 2 min)
Dombi Attila7a251bde0c81
diff --git a/app/models/work_package.rb b/app/models/work_package.rbindex 4ef83ce8ccb..47a442927f2 100644--- a/app/models/work_package.rb+++ b/app/models/work_package.rb@@ -140,21 +140,26 @@ class WorkPackage < ApplicationRecordacts_as_searchable columns: ['subject',"#{table_name}.description",- "#{Journal.table_name}.notes"],+ {+ name: "#{Journal.table_name}.notes",+ scope: -> { Journal.for_work_package.where("journable_id = #{table_name}.id") }+ }],tsv_columns: [{table_name: Attachment.table_name,column_name: 'fulltext',- normalization_type: :text+ normalization_type: :text,+ scope: -> { Attachment.where(container_type: name).where("container_id = #{table_name}.id") }},{table_name: Attachment.table_name,column_name: 'file',- normalization_type: :filename+ normalization_type: :filename,+ scope: -> { Attachment.where(container_type: name).where("container_id = #{table_name}.id") }}],- include: %i(project journals attachments),- references: %i(projects journals attachments),+ include: %i(project journals),+ references: %i(projects),date_column: "#{quoted_table_name}.created_at",# sort by id so that limited eager loading doesn't break with postgresqlorder_column: "#{table_name}.id"@@ -580,7 +585,7 @@ class WorkPackage < ApplicationRecordprivate_class_method :count_and_group_bydef set_attachments_error_details- if invalid_attachment = attachments.detect { |a| !a.valid? }+ if invalid_attachment = attachments.detect(&:invalid?)errors.messages[:attachments].first << " - #{invalid_attachment.errors.full_messages.first}"endenddiff --git a/db/migrate/20230328154645_add_gin_trgm_index_on_journals_and_custom_values.rb b/db/migrate/20230328154645_add_gin_trgm_index_on_journals_and_custom_values.rbnew file mode 100644index 00000000000..2d5f706d484--- /dev/null+++ b/db/migrate/20230328154645_add_gin_trgm_index_on_journals_and_custom_values.rb@@ -0,0 +1,33 @@+class AddGinTrgmIndexOnJournalsAndCustomValues < ActiveRecord::Migration[7.0]+ def change+ safe_enable_pg_trgm_extension++ if extensions.include?('pg_trgm')+ add_index(:journals, :notes, using: 'gin', opclass: :gin_trgm_ops)+ add_index(:custom_values, :value, using: 'gin', opclass: :gin_trgm_ops)+ end+ end++ private++ def safe_enable_pg_trgm_extension+ enable_extension("pg_trgm")+ rescue StandardError => e+ raise unless e.message =~ /pg_trgm/++ # Rollback the transaction in order to recover from the error.+ ActiveRecord::Base.connection.execute 'ROLLBACK'++ warn <<~MESSAGE+++ \e[33mWARNING:\e[0m Could not find the `pg_trgm` extension for PostgreSQL.+ In order to benefit from this performance improvement, please install the postgresql-contrib module+ for your PostgreSQL installation and re-run this migration.++ Read more about the contrib module at `https://www.postgresql.org/docs/current/contrib.html` .+ To re-run this migration use the following command `bin/rails db:migrate:redo VERSION=20230328154645`++ MESSAGE+ end+enddiff --git a/lib_static/plugins/acts_as_searchable/lib/acts_as_searchable.rb b/lib_static/plugins/acts_as_searchable/lib/acts_as_searchable.rbindex 60f79d2e721..9f0d1ce6438 100644--- a/lib_static/plugins/acts_as_searchable/lib/acts_as_searchable.rb+++ b/lib_static/plugins/acts_as_searchable/lib/acts_as_searchable.rb@@ -47,11 +47,10 @@ module Redmineself.searchable_options = optionsif searchable_options[:columns].nil?- raise 'No searchable column defined.'- elsif !searchable_options[:columns].is_a?(Array)- searchable_options[:columns] = [] << searchable_options[:columns]+ raise ArgumentError, 'No searchable column defined.'end+ searchable_options[:columns] = Array(searchable_options[:columns])searchable_options[:tsv_columns] ||= []searchable_options[:project_key] ||= "#{table_name}.project_id"@@ -83,41 +82,25 @@ module Redmine# projects argument can be either nil (will search all projects), a project or an array of projects# Returns the results and the results countdef search(tokens, projects = nil, options = {})- tokens = [] << tokens unless tokens.is_a?(Array)+ tokens = Array(tokens)projects = [] << projects unless projects.nil? || projects.is_a?(Array)find_order = "#{searchable_options[:order_column]} " + (options[:before] ? 'DESC' : 'ASC')- columns = searchable_options[:columns]-- tsv_columns = searchable_options[:tsv_columns]-- token_clauses = columns.map { |column| "(LOWER(#{column}) LIKE ?)" }+ token_clauses = searchable_column_conditionsif OpenProject::Database.allows_tsv?- tsv_clauses = tsv_columns.map do |tsv_column|- OpenProject::FullTextSearch.tsv_where(tsv_column[:table_name],- tsv_column[:column_name],- tokens.join(' '),- normalization: tsv_column[:normalization_type])- end+ tsv_clauses = searchable_tsv_column_conditions(tokens)endif searchable_options[:search_custom_fields]- searchable_custom_field_ids = CustomField.where(type: "#{name}CustomField",- searchable: true).pluck(:id)- if searchable_custom_field_ids.any?- custom_field_sql = "#{table_name}.id IN (SELECT customized_id FROM #{CustomValue.table_name}" +- " WHERE customized_type='#{name}' AND customized_id=#{table_name}.id AND LOWER(value) LIKE ?" +- " AND #{CustomValue.table_name}.custom_field_id IN (#{searchable_custom_field_ids.join(',')}))"- token_clauses << custom_field_sql- end+ token_clauses += Array(searchable_custom_fields_conditions)end- sql = (['(' + token_clauses.join(' OR ') + ')'] * tokens.size).join(' AND ')+ sql = (["(#{token_clauses.join(' OR ')})"] * tokens.size).join(' AND ')if tsv_clauses.present?- sql << (' OR ' + tsv_clauses.join(' OR '))+ sql << (" OR #{tsv_clauses.join(' OR ')}")endfind_conditions = [sql, *(tokens.map { |w| "%#{w.downcase}%" } * token_clauses.size).sort]@@ -147,6 +130,8 @@ module Redmine[results, results_count]end+ private+def searchable_projects_conditionprojects = if searchable_options[:permission].nil?Project.visible_by(User.current)@@ -156,6 +141,58 @@ module Redmine"#{searchable_options[:project_key]} IN (#{projects.select(:id).to_sql})"end++ def searchable_column_conditions+ searchable_options[:columns].map do |column|+ name, scope = column.is_a?(Hash) ? column.values_at(:name, :scope) : column+ match_condition = "(#{Arel.sql(name)} ILIKE ?)"++ if scope+ subquery_condition(scope, match_condition)+ else+ match_condition+ end+ end+ end++ def searchable_tsv_column_conditions(tokens)+ searchable_options[:tsv_columns].map do |tsv_column|+ tsv_condition =+ OpenProject::FullTextSearch.tsv_where(tsv_column[:table_name],+ tsv_column[:column_name],+ tokens.join(' '),+ normalization: tsv_column[:normalization_type])+ if tsv_column[:scope]+ subquery_condition(tsv_column[:scope], tsv_condition)+ else+ tsv_condition+ end+ end+ end++ def searchable_custom_fields_conditions+ searchable_custom_field_ids = CustomField.where(type: "#{name}CustomField",+ searchable: true).pluck(:id)+ if searchable_custom_field_ids.any?+ custom_field_condition =+ CustomValue.select('1').where(customized_type: name)+ .where("customized_id=#{table_name}.id AND value ILIKE ?")+ .where(custom_field_id: searchable_custom_field_ids)++ "EXISTS ( #{custom_field_condition.to_sql} )"+ end+ end++ def subquery_condition(scope_clause, match_condition)+ raise ArgumentError, ":scope must be an instance of Proc" unless scope_clause.is_a?(Proc)++ scope = scope_clause.call+ unless scope.is_a?(ActiveRecord::Relation)+ raise ArgumentError, ":scope must return an instance of ActiveRecord::Relation"+ end++ "EXISTS ( #{scope.select('1').where(match_condition).to_sql} )"+ endendendend