about summary refs log tree commit diff
path: root/db/migrate/20200717015413_backfill_status_nest_level.rb
blob: 1f37ef84710e7289267f7a6f9ea24fe9c7224d28 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class BackfillStatusNestLevel < ActiveRecord::Migration[5.2]
  disable_ddl_transaction!

  def up
    Rails.logger.info("Populating nest levels for orphaned replies...")
    Status.select(:id, :account_id).where(reply: true, in_reply_to_id: nil).reorder(nil).in_batches.update_all(nest_level: 1)

    count = 1.0
    total = Conversation.count

    Conversation.reorder('conversations.id DESC').find_each do |conversation|
      Rails.logger.info("(#{(count/total*100).to_i}%) Populating nest levels for threads...")
      conversation.statuses.where(reply: true).reorder('statuses.id ASC').find_each do |status|
        level = [status.thread&.account_id == status.account_id ? status.thread&.nest_level.to_i : status.thread&.nest_level.to_i + 1, 127].min
        status.update(nest_level: level) if level != status.nest_level
      end
      count += 1
    end
  end

  def down
    true
  end
end