Skip to content
This repository has been archived by the owner on May 27, 2022. It is now read-only.

Commit

Permalink
FIX: Backfill topic_id for EmailLog (discourse#13469)
Browse files Browse the repository at this point in the history
In the previous commit 5222247
we added a topic_id column to EmailLog. This simply backfills it in
batches. The next PR will get rid of the topic method defined on EmailLog in favour
of belongs_to.
  • Loading branch information
martin-brennan authored Jun 27, 2021
1 parent 203d567 commit 69518be
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions db/post_migrate/20210621234939_backfill_email_log_topic_id.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# frozen_string_literal: true

class BackfillEmailLogTopicId < ActiveRecord::Migration[6.1]
disable_ddl_transaction!
BATCH_SIZE = 30_000

def up
offset = 0
email_log_count = DB.query_single("SELECT COUNT(*) FROM email_logs").first

loop do
DB.exec(<<~SQL, offset: offset, batch_size: BATCH_SIZE)
WITH cte AS (
SELECT post_id
FROM email_logs
ORDER BY id
LIMIT :batch_size
OFFSET :offset
)
UPDATE email_logs
SET topic_id = posts.topic_id
FROM cte
INNER JOIN posts ON posts.id = cte.post_id
WHERE email_logs.post_id = cte.post_id
SQL

offset += BATCH_SIZE
break if offset > (email_log_count + BATCH_SIZE * 2)
end
end

def down
raise ActiveRecord::IrreversibleMigration
end
end

0 comments on commit 69518be

Please sign in to comment.