FIX: CF to table migration was incorrect (#171)

The order of values in the `INSERT` query was invalid (`assigned_to_id` and `topic_id` were swapped)

Co-authored-by: David Taylor <david@taylorhq.com>
This commit is contained in:
Jarek Radosz 2021-07-14 20:45:31 +02:00 committed by GitHub
parent 470dd939aa
commit b0a480fd35
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 12 deletions

View File

@ -2,18 +2,7 @@
class MoveAssignmentsFromCustomFieldsToATable < ActiveRecord::Migration[6.1]
def up
execute <<~SQL
INSERT INTO assignments (topic_id, assigned_by_user_id, assigned_to_id, created_at, updated_at)
SELECT (
SELECT value::integer assigned_to_id
FROM topic_custom_fields tcf1
WHERE tcf1.name = 'assigned_to_id' AND tcf1.topic_id = tcf2.topic_id
), value::integer assgined_by_id, topic_id, created_at, updated_at
FROM topic_custom_fields tcf2
WHERE name = 'assigned_by_id'
ORDER BY created_at DESC
ON CONFLICT DO NOTHING
SQL
# No-op, this migration was invalid
end
def down

View File

@ -0,0 +1,32 @@
# frozen_string_literal: true
class CorrectlyMoveAssignmentsFromCustomFieldsToATable < ActiveRecord::Migration[6.1]
def up
# An old version of 20210709101534 incorrectly imported `assignments` with
# the topic_id and assigned_to_id columns flipped. This query deletes those invalid records.
execute <<~SQL
DELETE FROM assignments USING topic_custom_fields
WHERE
assignments.assigned_to_id = topic_custom_fields.topic_id
AND assignments.topic_id = topic_custom_fields.value::integer
AND topic_custom_fields.name = 'assigned_to_id'
SQL
execute <<~SQL
INSERT INTO assignments (assigned_to_id, assigned_by_user_id, topic_id, created_at, updated_at)
SELECT (
SELECT value::integer assigned_to_id
FROM topic_custom_fields tcf1
WHERE tcf1.name = 'assigned_to_id' AND tcf1.topic_id = tcf2.topic_id
), value::integer assigned_by_id, topic_id, created_at, updated_at
FROM topic_custom_fields tcf2
WHERE name = 'assigned_by_id'
ORDER BY created_at DESC
ON CONFLICT DO NOTHING
SQL
end
def down
raise ActiveRecord::IrreversibleMigration
end
end