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
add validity_period to journal
ulferts7c8432c9e68d
diff --git a/app/services/journals/create_service.rb b/app/services/journals/create_service.rbindex 88d5a13eda4..a49492ff464 100644--- a/app/services/journals/create_service.rb+++ b/app/services/journals/create_service.rb@@ -149,6 +149,9 @@ module Journals## If a journal is created, all entries in the custom_values table associated to the journable are recreated as entries# in the customizable_journals table. Again, newlines are normalized.+ #+ # In case of no aggregation, the preceding journal will have its validity_range updated to be the created_at time of the newly+ # inserted journal. Such a journal can then be considered closed.def create_journal_sql(predecessor, notes, cause)<<~SQLWITH cleanup_predecessor_data AS (@@ -168,6 +171,8 @@ module Journals#{insert_data_sql(predecessor, notes, cause)}), inserted_journal AS (#{update_or_insert_journal_sql(predecessor, notes, cause)}+ ), update_predecessor AS (+ #{update_predecessor_sql(predecessor, notes, cause)}), insert_attachable AS (#{insert_attachable_sql}), insert_customizable AS (@@ -263,7 +268,8 @@ module Journalsupdated_at,data_id,data_type,- cause+ cause,+ validity_period)SELECT:journable_id,@@ -275,7 +281,8 @@ module Journals#{journal_timestamp_sql(notes, ':updated_at')},insert_data.id,:data_type,- :cause+ :cause,+ tstzrange(#{journal_timestamp_sql(notes, ':created_at')}, NULL)FROM max_journals, insert_dataRETURNING *SQL@@ -292,12 +299,6 @@ module Journalsenddef insert_data_sql(predecessor, notes, cause)- condition = if notes.blank? && cause.blank? && predecessor.nil?- "AND EXISTS (SELECT * FROM changes)"- else- ""- end-data_sql = <<~SQLINSERT INTO#{data_table_name} (@@ -309,7 +310,7 @@ module Journals#{journable_data_sql_addition}WHERE#{journable_table_name}.id = :journable_id- #{condition}+ #{only_on_changed_or_forced_condition_sql(predecessor, notes, cause)}RETURNING *SQL@@ -371,6 +372,25 @@ module Journalsjournable_class_name:)end+ # Sets the validity_period's upper boundary of the preceding journal to the created_at timestamp of the inserted journal.+ # If there is a predecessor (meaning we are aggregating/updating an existing journal), nothing is done.+ def update_predecessor_sql(predecessor, notes, cause)+ return "SELECT 1" if predecessor.present?++ update_sql = <<~SQL+ UPDATE+ journals+ SET+ validity_period = tstzrange(journals.created_at, :created_at)+ WHERE+ id = (SELECT id from max_journals)+ #{only_on_changed_or_forced_condition_sql(predecessor, notes, cause)}+ SQL++ sanitize(update_sql,+ created_at: journable_timestamp)+ end+def select_max_journal_sql(predecessor)sql = <<~SQLSELECT@@ -384,9 +404,9 @@ module JournalsRIGHT OUTER JOIN(SELECT 0 AS version) fallbackON- journals.journable_id = :journable_id- AND journals.journable_type = :journable_type- AND journals.version IN (#{max_journal_sql(predecessor)})+ journals.journable_id = :journable_id+ AND journals.journable_type = :journable_type+ AND journals.version IN (#{max_journal_sql(predecessor)})SQLsanitize(sql,@@ -537,6 +557,14 @@ module Journalsdata_changes.join(' OR ')end+ def only_on_changed_or_forced_condition_sql(predecessor, notes, cause)+ if notes.blank? && cause.blank? && predecessor.nil?+ "AND EXISTS (SELECT * FROM changes)"+ else+ ""+ end+ end+def data_sink_columnstext_columns = text_column_names(journable.journaled_columns_names - text_columns + text_columns).join(', ')diff --git a/config/application.rb b/config/application.rbindex 1d9f183ed37..2d21ad9204e 100644--- a/config/application.rb+++ b/config/application.rb@@ -143,6 +143,9 @@ module OpenProject# Enable serialization of types [Symbol, Date, Time]config.active_record.yaml_column_permitted_classes = [Symbol, Date, Time, ActiveSupport::HashWithIndifferentAccess]+ # Include tstzrange columns in the list of time zone aware types+ ActiveRecord::Base.time_zone_aware_types += [:tstzrange]+# Activate being able to specify the format in which full_message works.# Doing this, it is e.g. possible to avoid having the format of '%{attribute} %{message}' which# will always prepend the attribute name to the error message.diff --git a/db/migrate/20230608151123_add_validity_period_to_journals.rb b/db/migrate/20230608151123_add_validity_period_to_journals.rbnew file mode 100644index 00000000000..cef0e7f3754--- /dev/null+++ b/db/migrate/20230608151123_add_validity_period_to_journals.rb@@ -0,0 +1,100 @@+class AddValidityPeriodToJournals < ActiveRecord::Migration[7.0]+ def change+ add_column :journals, :validity_period, :tstzrange++ reversible do |direction|+ direction.up do+ fix_all_journal_timestamps+ write_validity_period++ add_validity_period_constraint+ end+ end++ change_column_null :journals, :validity_period, false+ end++ def fix_all_journal_timestamps+ max_attempts = attempts = ENV['MAX_JOURNAL_TIMESTAMPS_ATTEMPTS'].presence.to_i || Journal.all.maximum(:version)++ loop do+ break if fix_journal_timestamps == 0++ if attempts == 0+ raise <<~MSG.squish+ There are still journals with timestamps after their successors timestamp.+ Aborting after #{max_attempts}.+ Run the migration again with the env variable MAX_JOURNAL_TIMESTAMPS_ATTEMPTS set to a higher value.+ MSG+ else+ say "Journals with timestamps after their successors timestamp remain in the database. Retrying..."+ end++ attempts -= 1+ end++ say "All journals' timestamps in the database are correct."+ end++ def fix_journal_timestamps+ update <<~SQL.squish+ UPDATE journals+ SET+ created_at = LEAST(journals.created_at, values.created_at),+ updated_at = LEAST(journals.updated_at, values.created_at)+ FROM (+ SELECT+ predecessors.id,+ successors.created_at+ FROM+ journals predecessors+ LEFT JOIN LATERAL (SELECT DISTINCT ON (journable_type, journable_id) *+ FROM "journals"+ WHERE "journals"."version" > predecessors.version+ AND "journals"."journable_id" = predecessors.journable_id+ ORDER BY "journals"."journable_type" ASC,+ "journals"."journable_id" ASC,+ "journals"."version" ASC) successors+ ON successors.journable_id = predecessors.journable_id+ AND successors.journable_type = predecessors.journable_type+ ) values+ WHERE values.id = journals.id+ AND (values.created_at < journals.created_at OR values.created_at < journals.updated_at)+ SQL+ end++ def write_validity_period+ execute <<~SQL.squish+ UPDATE journals+ SET validity_period = values.validity_period+ FROM (+ SELECT+ predecessors.id,+ tstzrange(predecessors.created_at, successors.created_at) validity_period+ FROM+ journals predecessors+ LEFT JOIN LATERAL (SELECT DISTINCT ON (journable_type, journable_id) *+ FROM "journals"+ WHERE "journals"."version" > predecessors.version+ AND "journals"."journable_id" = predecessors.journable_id+ ORDER BY "journals"."journable_type" ASC,+ "journals"."journable_id" ASC,+ "journals"."version" ASC) successors+ ON successors.journable_id = predecessors.journable_id+ AND successors.journable_type = predecessors.journable_type+ ) values+ WHERE values.id = journals.id+ SQL+ end++ def add_validity_period_constraint+ execute <<~SQL.squish+ CREATE EXTENSION IF NOT EXISTS btree_gist;++ ALTER TABLE journals+ ADD CONSTRAINT non_overlapping_journals_validity_periods+ EXCLUDE USING gist (journable_id WITH =, journable_type WITH =, validity_period WITH &&)+ DEFERRABLE+ SQL+ end+enddiff --git a/spec/controllers/activities_controller_spec.rb b/spec/controllers/activities_controller_spec.rbindex 6d70f3932b2..939fb69109d 100644--- a/spec/controllers/activities_controller_spec.rb+++ b/spec/controllers/activities_controller_spec.rb@@ -46,18 +46,7 @@ RSpec.describe ActivitiesController doenddescribe 'global' do- let(:work_package) { create(:work_package) }- let!(:journal) do- create(:work_package_journal,- journable_id: work_package.id,- created_at: 3.days.ago.to_date.to_fs(:db),- version: Journal.maximum(:version) + 1,- data: build(:journal_work_package_journal,- subject: work_package.subject,- status_id: work_package.status_id,- type_id: work_package.type_id,- project_id: work_package.project_id))- end+ let!(:work_package) { create(:work_package, :created_in_past, created_at: 3.days.ago) }before { get 'index' }diff --git a/spec/factories/journal_factory.rb b/spec/factories/journal_factory.rbindex d42de09ccff..ccfd9d4eb91 100644--- a/spec/factories/journal_factory.rb+++ b/spec/factories/journal_factory.rb@@ -30,8 +30,20 @@ FactoryBot.define dofactory :journal douser factory: :usercreated_at { Time.zone.now }+ validity_period { created_at..Float::INFINITY }sequence(:version, 1)+ callback(:before_create) do |journal|+ # If there is a predecessor to the newly created journal, update the validity period of the predecessor+ # to end at the creation time of the new journal.+ Journal+ .where(journable_id: journal.journable_id,+ journable_type: journal.journable_type,+ version: journal.version - 1)+ .where('upper(validity_period) IS NULL')+ .update_all(['validity_period = tstzrange(journals.created_at, ?)', journal.created_at])+ end+factory :work_package_journal, class: 'Journal' dojournable_type { 'WorkPackage' }data { build(:journal_work_package_journal) }diff --git a/spec/factories/work_package_factory.rb b/spec/factories/work_package_factory.rbindex 3461241c913..614211c31bd 100644--- a/spec/factories/work_package_factory.rb+++ b/spec/factories/work_package_factory.rb@@ -59,6 +59,18 @@ FactoryBot.define dotype factory: :type_milestoneend+ # Using this trait, the work package and its journal will appear to have been created+ # in the past (at the time of the created_at attribute).+ trait :created_in_past do+ updated_at { created_at }++ callback(:after_create) do |work_package|+ work_package.journals.first.update_columns(created_at: work_package.created_at,+ updated_at: work_package.created_at,+ validity_period: work_package.created_at..Float::INFINITY)+ end+ end+callback(:after_build) do |work_package, evaluator|work_package.type = work_package.project.types.first unless work_package.typediff --git a/spec/lib/journal_formatter/diff_spec.rb b/spec/lib/journal_formatter/diff_spec.rbindex 5b29c313a1c..4b318683bda 100644--- a/spec/lib/journal_formatter/diff_spec.rb+++ b/spec/lib/journal_formatter/diff_spec.rb@@ -50,7 +50,7 @@ RSpec.describe OpenProject::JournalFormatter::Diff dolet(:journal) dobuild_stubbed(:work_package_journal,journable: work_package,- created_at: 3.days.ago.to_date.to_fs(:db),+ created_at: 3.days.ago.to_date,version: 1,data: build(:journal_work_package_journal,subject: work_package.subject,diff --git a/spec/models/work_package/work_package_acts_as_journalized_spec.rb b/spec/models/work_package/work_package_acts_as_journalized_spec.rbindex f94a5a41cf9..aa1c126d6d0 100644--- a/spec/models/work_package/work_package_acts_as_journalized_spec.rb+++ b/spec/models/work_package/work_package_acts_as_journalized_spec.rb@@ -79,12 +79,14 @@ RSpec.describe WorkPackage doendit 'has the timestamp of the work package update time for created_at' do- # This seemingly unnecessary reload leads to the updated_at having the same- # precision as the created_at of the Journal. It is database dependent, so it would work without- # reload on PG 12 but does not work on PG 9.expect(work_package.last_journal.created_at).to eql(work_package.reload.updated_at)end++ it 'has the updated_at of the work package as the lower bound for validity_period and no upper bound' do+ expect(work_package.last_journal.validity_period)+ .to eql(work_package.reload.updated_at...Float::INFINITY)+ endendcontext 'when nothing is changed' do@@ -148,7 +150,7 @@ RSpec.describe WorkPackage doendend- describe 'on work package change', with_settings: { journal_aggregation_time_minutes: 0 } do+ describe 'on work package change without aggregation', with_settings: { journal_aggregation_time_minutes: 0 } dolet(:parent_work_package) docreate(:work_package,project_id: project.id,@@ -274,12 +276,20 @@ RSpec.describe WorkPackage doendit 'has the timestamp of the work package update time for created_at' do- # This seemingly unnecessary reload leads to the updated_at having the same- # precision as the created_at of the Journal. It is database dependent, so it would work without- # reload on PG 12 but does not work on PG 9.expect(work_package.last_journal.created_at).to eql(work_package.reload.updated_at)end++ it 'has the updated_at of the work package as the lower bound for validity_period and no upper bound' do+ expect(work_package.last_journal.validity_period)+ .to eql(work_package.reload.updated_at...Float::INFINITY)+ end++ it 'sets the upper bound of the preceeding journal to be the created_at time of the newly created journal' do+ former_last_journal = work_package.journals[-2]+ expect(former_last_journal.validity_period)+ .to eql(former_last_journal.created_at...work_package.last_journal.created_at)+ endenddescribe 'attachments', with_settings: { journal_aggregation_time_minutes: 0 } do@@ -369,6 +379,13 @@ RSpec.describe WorkPackage doendit { expect { work_package.save! }.not_to change(Journal, :count) }++ it 'does not set an upper bound to the already existing journal' do+ work_package.save++ expect(work_package.last_journal.validity_period.last)+ .to eql(Float::INFINITY)+ endendcontext 'when custom value removed' do@@ -549,7 +566,7 @@ RSpec.describe WorkPackage docontext 'when updated within aggregation time' dosubject(:journals) { work_package.journals }- let(:current_user) { user1 }+ current_user { user1 }let(:notes) { nil }let(:user1) { create(:user) }@@ -676,6 +693,11 @@ RSpec.describe WorkPackage doendendend++ it 'has the journal\'s creation time as the lower and no upper bound for validity_period' do+ expect(work_package.last_journal.validity_period)+ .to eql(work_package.last_journal.created_at...Float::INFINITY)+ endendcontext 'with a different author' do@@ -683,15 +705,33 @@ RSpec.describe WorkPackage doit 'leads to two journals' doexpect(subject.count).to be 2+ end++ it 'has the initial user as the author of the first journal' doexpect(subject.first.user).to eql current_user+ end+ it 'has the second user as he author of the second journal' doexpect(subject.second.user).to eql new_author+ end+ it 'has the changes (compared to the initial state) in the second journal' doexpect(subject.second.get_changes).to eql("status_id" => [status.id, new_status.id])end++ it 'has the first journal\'s creation time as the lower and the second journal\'s creation time ' \+ 'as the upper bound for validity_period of the first journal' do+ expect(subject.first.validity_period)+ .to eql(subject.first.created_at...subject.second.created_at)+ end++ it 'has the second journal\'s creation time as the lower and no upper bound for validity_period of the second journal' do+ expect(subject.second.validity_period)+ .to eql(subject.second.created_at...Float::INFINITY)+ endendend@@ -709,6 +749,17 @@ RSpec.describe WorkPackage doit 'creates a new journal' doexpect(journals.count).to be 2end++ it 'has the first journal\'s creation time as the lower and the second journal\'s creation time ' \+ 'as the upper bound for validity_period of the first journal' do+ expect(subject.first.validity_period)+ .to eql(subject.first.created_at...subject.second.created_at)+ end++ it 'has the second journal\'s creation time as the lower and no upper bound for validity_period of the second journal' do+ expect(subject.second.validity_period)+ .to eql(subject.second.created_at...Float::INFINITY)+ endendcontext 'when updating with aggregation disabled', with_settings: { journal_aggregation_time_minutes: 0 } dodiff --git a/spec/requests/api/v3/work_packages/index_resource_spec.rb b/spec/requests/api/v3/work_packages/index_resource_spec.rbindex ba1ae3717ad..1120f928544 100644--- a/spec/requests/api/v3/work_packages/index_resource_spec.rb+++ b/spec/requests/api/v3/work_packages/index_resource_spec.rb@@ -251,12 +251,12 @@ RSpec.describe 'API v3 Work package resource',let(:created_at) { baseline_time - 1.day }let(:work_package) do- new_work_package = create(:work_package,- subject: "The current work package",- assigned_to: current_user,- project:)- new_work_package.update_columns(created_at:)- new_work_package+ create(:work_package,+ :created_in_past,+ created_at:,+ subject: "The current work package",+ assigned_to: current_user,+ project:)endlet(:original_journal) docreate_journal(journable: work_package, timestamp: created_at,@@ -900,10 +900,7 @@ RSpec.describe 'API v3 Work package resource',describe "for multiple work packages" dolet!(:work_package2) do- new_work_package = create(:work_package, subject: "Other work package", project:)- new_work_package.update_columns(created_at:)- new_work_package.journals.update_all(created_at:)- new_work_package+ create(:work_package, :created_in_past, created_at:, subject: "Other work package", project:)endit "succeeds" do@@ -1073,7 +1070,7 @@ RSpec.describe 'API v3 Work package resource',context "with caching" docontext "with relative timestamps" dolet(:timestamps) { [Timestamp.parse("P-2D"), Timestamp.now] }- let(:created_at) { '2015-01-01' }+ let(:created_at) { Date.parse('2015-01-01') }describe "when the filter becomes outdated" do# The work package has been updated 1 day ago, which is after the baseline@@ -1124,7 +1121,7 @@ RSpec.describe 'API v3 Work package resource',context "with relative date keyword timestamps" dolet(:timestamps) { [Timestamp.parse('oneWeekAgo@12:00+00:00'), Timestamp.now] }- let(:created_at) { '2015-01-01' }+ let(:created_at) { Date.parse('2015-01-01') }describe "when the filter becomes outdated" do# The work package has been updated 1 day ago, which is after the baselinediff --git a/spec/requests/api/v3/work_packages/show_resource_spec.rb b/spec/requests/api/v3/work_packages/show_resource_spec.rbindex 36b14dab7ed..f5fc2ceda80 100644--- a/spec/requests/api/v3/work_packages/show_resource_spec.rb+++ b/spec/requests/api/v3/work_packages/show_resource_spec.rb@@ -229,12 +229,14 @@ RSpec.describe 'API v3 Work package resource',new_work_packageendlet(:original_journal) do- create_journal(journable: work_package, timestamp: created_at,+ create_journal(journable: work_package,+ timestamp: created_at,version: 1,attributes: { subject: "The original work package" })endlet(:current_journal) do- create_journal(journable: work_package, timestamp: 1.day.ago,+ create_journal(journable: work_package,+ timestamp: 1.day.ago,version: 2,attributes: { subject: "The current work package" })end@@ -371,7 +373,7 @@ RSpec.describe 'API v3 Work package resource',context "with relative timestamps" dolet(:timestamps) { [Timestamp.parse("P-2D"), Timestamp.now] }- let(:created_at) { '2015-01-01' }+ let(:created_at) { Date.parse('2015-01-01') }describe "attributesByTimestamp" doit "does not cache the self link" do@@ -457,7 +459,7 @@ RSpec.describe 'API v3 Work package resource',context "with relative timestamps" dolet(:timestamps) { [Timestamp.parse("oneDayAgo@00:00+00:00"), Timestamp.now] }- let(:created_at) { '2015-01-01' }+ let(:created_at) { Date.parse('2015-01-01') }describe "attributesByTimestamp" doit "does not cache the self link" dodiff --git a/spec/support/queries/shared_get_individual_query_examples.rb b/spec/support/queries/shared_get_individual_query_examples.rbindex defba5bf4ee..1896e504333 100644--- a/spec/support/queries/shared_get_individual_query_examples.rb+++ b/spec/support/queries/shared_get_individual_query_examples.rb@@ -27,7 +27,7 @@#++RSpec.shared_examples_for 'GET individual query' do- let(:work_package) { create(:work_package, project:) }+ let(:work_package) { create(:work_package, :created_in_past, project:, created_at: 1.minute.ago) }let(:filter) { [] }let(:path) doif filter.any?