20181116173541_copy_account_stats.rb 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # frozen_string_literal: true
  2. class CopyAccountStats < ActiveRecord::Migration[5.2]
  3. disable_ddl_transaction!
  4. class MigrationAccount < ApplicationRecord
  5. self.table_name = :accounts
  6. end
  7. def up
  8. safety_assured do
  9. if supports_upsert?
  10. up_fast
  11. else
  12. up_slow
  13. end
  14. end
  15. end
  16. def down
  17. # Nothing
  18. end
  19. private
  20. def supports_upsert?
  21. ActiveRecord::Base.connection.database_version >= 90_500
  22. end
  23. def up_fast
  24. say 'Upsert is available, importing counters using the fast method'
  25. MigrationAccount.unscoped.select('id').find_in_batches(batch_size: 5_000) do |accounts|
  26. execute <<-SQL.squish
  27. INSERT INTO account_stats (account_id, statuses_count, following_count, followers_count, created_at, updated_at)
  28. SELECT id, statuses_count, following_count, followers_count, created_at, updated_at
  29. FROM accounts
  30. WHERE id IN (#{accounts.map(&:id).join(', ')})
  31. ON CONFLICT (account_id) DO UPDATE
  32. SET statuses_count = EXCLUDED.statuses_count, following_count = EXCLUDED.following_count, followers_count = EXCLUDED.followers_count
  33. SQL
  34. end
  35. end
  36. def up_slow
  37. say 'Upsert is not available in PostgreSQL below 9.5, falling back to slow import of counters'
  38. # We cannot use bulk INSERT or overarching transactions here because of possible
  39. # uniqueness violations that we need to skip over
  40. MigrationAccount.unscoped.select('id, statuses_count, following_count, followers_count, created_at, updated_at').find_each do |account|
  41. params = [account.id, account[:statuses_count], account[:following_count], account[:followers_count], account.created_at, account.updated_at]
  42. exec_insert('INSERT INTO account_stats (account_id, statuses_count, following_count, followers_count, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6)', nil, params)
  43. rescue ActiveRecord::RecordNotUnique
  44. next
  45. end
  46. end
  47. end