DEV: Move data migration of `PostSearchData#private_message` into post_migration.

Follow-up to 92b7fe4c62
This commit is contained in:
Guo Xiang Tan 2020-08-18 16:44:54 +08:00
parent 562180dd9a
commit 2161abfabd
No known key found for this signature in database
GPG Key ID: FBD110179AAC1F20
2 changed files with 48 additions and 41 deletions

View File

@ -3,49 +3,9 @@
class AddPrivateMessageToPostSearchData < ActiveRecord::Migration[6.0] class AddPrivateMessageToPostSearchData < ActiveRecord::Migration[6.0]
def up def up
add_column :post_search_data, :private_message, :boolean add_column :post_search_data, :private_message, :boolean
# Delete post_search_data of orphaned posts
execute <<~SQL
DELETE FROM post_search_data
WHERE post_id IN (
SELECT posts.id
FROM posts
LEFT JOIN topics ON topics.id = posts.topic_id
WHERE topics.id IS NULL
)
SQL
# Delete orphaned post_search_data
execute <<~SQL
DELETE FROM post_search_data
WHERE post_id IN (
SELECT post_search_data.post_id
FROM post_search_data
LEFT JOIN posts ON posts.id = post_search_data.post_id
WHERE posts.id IS NULL
)
SQL
execute <<~SQL
UPDATE post_search_data
SET private_message = true
FROM posts
INNER JOIN topics ON topics.id = posts.topic_id AND topics.archetype = 'private_message'
WHERE posts.id = post_search_data.post_id
SQL
execute <<~SQL
UPDATE post_search_data
SET private_message = false
FROM posts
INNER JOIN topics ON topics.id = posts.topic_id AND topics.archetype <> 'private_message'
WHERE posts.id = post_search_data.post_id
SQL
change_column_null(:post_search_data, :private_message, false)
end end
def down def down
raise ActiveRecord::IrreversibleMigration remove_column :post_search_data, :private_message
end end
end end

View File

@ -0,0 +1,47 @@
class UpdatePrivateMessageOnPostSearchData < ActiveRecord::Migration[6.0]
def up
# Delete post_search_data of orphaned posts
execute <<~SQL
DELETE FROM post_search_data
WHERE post_id IN (
SELECT posts.id
FROM posts
LEFT JOIN topics ON topics.id = posts.topic_id
WHERE topics.id IS NULL
)
SQL
# Delete orphaned post_search_data
execute <<~SQL
DELETE FROM post_search_data
WHERE post_id IN (
SELECT post_search_data.post_id
FROM post_search_data
LEFT JOIN posts ON posts.id = post_search_data.post_id
WHERE posts.id IS NULL
)
SQL
execute <<~SQL
UPDATE post_search_data
SET private_message = true
FROM posts
INNER JOIN topics ON topics.id = posts.topic_id AND topics.archetype = 'private_message'
WHERE posts.id = post_search_data.post_id
SQL
execute <<~SQL
UPDATE post_search_data
SET private_message = false
FROM posts
INNER JOIN topics ON topics.id = posts.topic_id AND topics.archetype <> 'private_message'
WHERE posts.id = post_search_data.post_id
SQL
change_column_null(:post_search_data, :private_message, false)
end
def down
raise ActiveRecord::IrreversibleMigration
end
end