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

  def up
    safety_assured do
      Status.where.not(id: StatusStat.select('status_id')).select('id').find_in_batches do |statuses|
        execute <<-SQL.squish
          INSERT INTO status_stats (status_id, reblogs_count, favourites_count, created_at, updated_at)
          SELECT id, reblogs_count, favourites_count, created_at, updated_at
          FROM statuses
          WHERE id IN (#{statuses.map(&:id).join(', ')})
          ON CONFLICT (status_id) DO UPDATE
          SET reblogs_count = EXCLUDED.reblogs_count, favourites_count = EXCLUDED.favourites_count
        SQL
      end
    end
  end

  def down
    # Nothing
  end
end