From d3882df4376dde5ecff2c9ddb1478369702ceb7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Mon, 19 Nov 2018 18:42:38 +0100 Subject: [PATCH] Fix milestones migration not updating ID sequence When we insert a record in PostgreSQL and we specify the ID, the internal ID sequence for that table isn't updated. In order to keep the original IDs so we didn't break any foreign keys, we specified the IDs when copying the table, resulting in a table having its ID sequence with a value of an existing record. When trying to insert a new record, we got a `PG::UniqueViolation` exception. Updating the sequence after the data migration might not be the most elegant solution, but it's easy to do and it's already been tested on a production environment. --- lib/tasks/migrate_milestones_and_statuses.rake | 4 ++++ spec/lib/tasks/milestones_spec.rb | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/lib/tasks/migrate_milestones_and_statuses.rake b/lib/tasks/migrate_milestones_and_statuses.rake index 789e3d57e..d01418e6b 100644 --- a/lib/tasks/migrate_milestones_and_statuses.rake +++ b/lib/tasks/migrate_milestones_and_statuses.rake @@ -91,6 +91,10 @@ namespace :milestones do "budget_investment_statuses" => "milestone_statuses", "budget_investment_milestone_translations" => "milestone_translations" }.each do |original_table, migrated_table| + ActiveRecord::Base.connection.execute( + "select setval('#{migrated_table}_id_seq', (select max(id) from #{migrated_table}));" + ) + unless count_rows(original_table) == count_rows(migrated_table) raise "Number of rows of old and new tables do not match! Rolling back transaction..." end diff --git a/spec/lib/tasks/milestones_spec.rb b/spec/lib/tasks/milestones_spec.rb index b1693ccf5..56507d02b 100644 --- a/spec/lib/tasks/milestones_spec.rb +++ b/spec/lib/tasks/milestones_spec.rb @@ -66,6 +66,11 @@ describe "Milestones tasks" do expect(milestone.updated_at.to_date).to eq Date.today end + it "Updates the primary key sequence correctly" do + run_rake_task + expect { create(:milestone) }.not_to raise_exception + end + context "Milestone has images and documents" do let(:milestone_id) do ActiveRecord::Base.connection.execute(