Skip to content

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

Introduces the position_cache

Marcello Rocha1d346087317c
diff --git a/app/models/custom_field/order_statements.rb b/app/models/custom_field/order_statements.rb
index ccf043c36a3..73156a761c9 100644
--- a/app/models/custom_field/order_statements.rb
+++ b/app/models/custom_field/order_statements.rb
@@ -171,16 +171,10 @@ module CustomField::OrderStatements
end
def join_for_order_by_hierarchy_sql
- ancestor_item = CustomField.find(id).hierarchy_root
- self_and_descendants = ancestor_item.self_and_descendants
- total_descendants = self_and_descendants.count
- max_depth = self_and_descendants.max_by(&:depth).depth
- items = hierarchy_position_sql(ancestor_id: ancestor_item.id, total_descendants:, max_depth:)
-
join_for_order_sql(
- value: multi_value? ? "ARRAY_AGG(item.position ORDER BY item.position)" : "item.position",
- add_select: "#{multi_value? ? "ARRAY_TO_STRING(ARRAY_AGG(cv.value ORDER BY item.position), '.')" : 'cv.value'} ids",
- join: "INNER JOIN (#{items}) item ON item.id = cv.value::bigint",
+ value: multi_value? ? "ARRAY_AGG(item.position_cache ORDER BY item.position_cache)" : "item.position_cache",
+ add_select: "#{multi_value? ? "ARRAY_TO_STRING(ARRAY_AGG(cv.value ORDER BY item.position_cache), '.')" : 'cv.value'} ids",
+ join: "INNER JOIN #{CustomField::Hierarchy::Item.quoted_table_name} item ON item.id = cv.value::bigint",
multi_value:
)
end
diff --git a/app/services/custom_fields/hierarchy/hierarchical_item_service.rb b/app/services/custom_fields/hierarchy/hierarchical_item_service.rb
index 8d942105465..2123063571b 100644
--- a/app/services/custom_fields/hierarchy/hierarchical_item_service.rb
+++ b/app/services/custom_fields/hierarchy/hierarchical_item_service.rb
@@ -105,7 +105,10 @@ module CustomFields
# @param new_parent [CustomField::Hierarchy::Item] the new parent of the node
# @return [Success(CustomField::Hierarchy::Item)]
def move_item(item:, new_parent:)
- Success(new_parent.append_child(item))
+ updated_item = new_parent.append_child(item)
+ update_position_cache(new_parent.root)
+
+ Success(updated_item)
end
# Reorder the item along its siblings.
@@ -116,7 +119,6 @@ module CustomFields
return Success() if item.siblings.empty?
new_sort_order = [0, new_sort_order.to_i].max
-
return Success() if item.sort_order == new_sort_order
update_item_order(item:, new_sort_order:)
@@ -129,6 +131,10 @@ module CustomFields
raise NotImplementedError
end
+ # Returns a hash of Item => { Item => [Item] }
+ # @param item [CustomField::Hierarchy::Item] the start node
+ # @param depth [Integer] limits the max depth of the hash. see {ClosureTree#hash_tree}
+ # @return [Success({CustomField::Hierarchy::Item => Array, Hash})]
def hashed_subtree(item:, depth:)
if depth >= 0
Success(item.hash_tree(limit_depth: depth + 1))
@@ -137,6 +143,10 @@ module CustomFields
end
end
+ # Checks if an item is a descendant of another node
+ # @param item [CustomField::Hierarchy::Item] the item to be tested
+ # @param parent [CustomField::Hierarchy::Item] the node to be checked against
+ # @return [Success, Failure]
def descendant_of?(item:, parent:)
item.descendant_of?(parent) ? Success() : Failure()
end
@@ -147,6 +157,7 @@ module CustomFields
item = CustomField::Hierarchy::Item.create(custom_field: custom_field)
return Failure(item.errors) if item.new_record?
+ update_position_cache(item)
Success(item)
end
@@ -157,7 +168,8 @@ module CustomFields
item = validation[:parent].children.create(**attributes)
return Failure(item.errors) if item.new_record?
- Success(item)
+ update_position_cache(item.root)
+ Success(item.reload)
end
def update_item_attributes(item:, attributes:)
@@ -176,6 +188,37 @@ module CustomFields
target_item = item.siblings.last
target_item.append_sibling(item)
end
+
+ update_position_cache(item.root)
+ end
+
+ def update_position_cache(root)
+ sql = <<-SQL.squish
+ UPDATE hierarchical_items
+ SET position_cache = subquery.position
+ FROM (
+ SELECT hi.id
+ , SUM((1 + COALESCE(anc.sort_order, 0)) *
+ POWER(count_max.total_descendants, count_max.max_gens - depths.generations)) AS position
+ FROM hierarchical_items hi
+ INNER JOIN hierarchical_item_hierarchies hih ON hi.id = hih.descendant_id
+ JOIN hierarchical_item_hierarchies anc_h ON anc_h.descendant_id = hih.descendant_id
+ JOIN hierarchical_items anc ON anc.id = anc_h.ancestor_id
+ JOIN hierarchical_item_hierarchies depths ON depths.ancestor_id = #{root.id} AND depths.descendant_id = anc.id
+ , (
+ SELECT COUNT(1) AS total_descendants, MAX(generations) + 1 AS max_gens
+ FROM hierarchical_items hi
+ INNER JOIN hierarchical_item_hierarchies hih ON hi.id = hih.ancestor_id
+ WHERE ancestor_id = #{root.id}
+ ) count_max
+ WHERE hih.ancestor_id = #{root.id}
+ GROUP BY hi.id) as subquery
+ WHERE hierarchical_items.id = subquery.id;
+ SQL
+
+ OpenProject::Mutex.with_advisory_lock(CustomField::Hierarchy::Item, "position_update_anc_#{root.id}") do
+ CustomField::Hierarchy::Item.connection.exec_update(sql)
+ end
end
end
end
diff --git a/db/migrate/20250102161733_adds_position_cache_to_hierarchy_items.rb b/db/migrate/20250102161733_adds_position_cache_to_hierarchy_items.rb
new file mode 100644
index 00000000000..aeee65d4bd8
--- /dev/null
+++ b/db/migrate/20250102161733_adds_position_cache_to_hierarchy_items.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 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.
+#++
+
+class AddsPositionCacheToHierarchyItems < ActiveRecord::Migration[7.1]
+ def change
+ add_column :hierarchical_items, :position_cache, :bigint, null: true
+ add_index :hierarchical_items, :position_cache
+
+ reversible do |dir|
+ dir.up do
+ root_node = Struct.new(:id)
+ service = CustomFields::Hierarchy::HierarchicalItemService.new
+ sql = "select id from hierarchical_items where custom_field_id is not NULL;"
+ ActiveRecord::Base.connection.execute(sql).each do |row|
+ service.send :update_position_cache, root_node.new(**row)
+ end
+ end
+ end
+ end
+end
diff --git a/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rb b/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rb
index e88ed99bf4e..36abb4b82eb 100644
--- a/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rb
+++ b/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rb
@@ -31,8 +31,8 @@
require "spec_helper"
RSpec.describe CustomFields::Hierarchy::HierarchicalItemService do
- let(:custom_field) { create(:custom_field, field_format: "hierarchy", hierarchy_root: nil) }
- let(:invalid_custom_field) { create(:custom_field, field_format: "text", hierarchy_root: nil) }
+ let!(:custom_field) { create(:custom_field, field_format: "hierarchy", hierarchy_root: nil) }
+ let!(:invalid_custom_field) { create(:custom_field, field_format: "text", hierarchy_root: nil) }
let!(:root) { service.generate_root(custom_field).value! }
let!(:luke) { service.insert_item(parent: root, label: "luke", short: "LS").value! }
@@ -89,6 +89,14 @@ RSpec.describe CustomFields::Hierarchy::HierarchicalItemService do
bob = service.insert_item(parent: root, label: "Bob", sort_order: 1).value!
expect(root.reload.children).to contain_exactly(luke, bob, leia)
end
+
+ it "updates the position_cache" do
+ leia = service.insert_item(parent: root, label: "leia").value!
+ expect(root.reload.position_cache).to eq(64)
+
+ service.insert_item(parent: root, label: "Bob", sort_order: 1).value!
+ expect(leia.reload.position_cache).to eq(200)
+ end
end
context "with invalid item" do
@@ -133,6 +141,13 @@ RSpec.describe CustomFields::Hierarchy::HierarchicalItemService do
expect(CustomField::Hierarchy::Item.count).to eq(1)
expect(root.reload.children).to be_empty
end
+
+ it "updates the position_cache" do
+ result = service.delete_branch(item: luke)
+
+ expect(result).to be_success
+ expect(root.reload.position_cache).to eq(27)
+ end
end
context "with root item" do
@@ -214,6 +229,13 @@ RSpec.describe CustomFields::Hierarchy::HierarchicalItemService do
expect(luke.reload.ancestors).to contain_exactly(root, lando)
expect(mara.reload.ancestors).to contain_exactly(root, lando, luke)
end
+
+ it "updates the position_cache" do
+ service.move_item(item: luke, new_parent: lando)
+
+ preordered_descendants = root.reload.self_and_descendants_preordered.pluck(:label)
+ expect(root.self_and_descendants.reorder(:position_cache).pluck(:label)).to eq(preordered_descendants)
+ end
end
describe "#reorder_item" do
@@ -275,6 +297,13 @@ RSpec.describe CustomFields::Hierarchy::HierarchicalItemService do
expect(lando.reload.sort_order).to eq(1)
expect(chewbacca.reload.sort_order).to eq(2)
end
+
+ it "updates the position_cache" do
+ service.reorder_item(item: chewbacca, new_sort_order: 0)
+
+ preordered_descendants = root.reload.self_and_descendants_preordered.pluck(:label)
+ expect(root.self_and_descendants.reorder(:position_cache).pluck(:label)).to eq(preordered_descendants)
+ end
end
describe "#hashed_subtree" do