2023-07-12 16:47:08 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-08-15 02:19:32 +09:00
|
|
|
class CopyStatusStats < ActiveRecord::Migration[5.2]
|
|
|
|
disable_ddl_transaction!
|
|
|
|
|
|
|
|
def up
|
|
|
|
safety_assured do
|
2018-10-07 11:40:37 +09:00
|
|
|
if supports_upsert?
|
|
|
|
up_fast
|
|
|
|
else
|
|
|
|
up_slow
|
2018-08-18 10:44:50 +09:00
|
|
|
end
|
2018-08-15 02:19:32 +09:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def down
|
|
|
|
# Nothing
|
|
|
|
end
|
2018-10-07 11:40:37 +09:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def supports_upsert?
|
2024-01-19 01:11:50 +09:00
|
|
|
ActiveRecord::Base.connection.database_version >= 90_500
|
2018-10-07 11:40:37 +09:00
|
|
|
end
|
|
|
|
|
|
|
|
def up_fast
|
|
|
|
say 'Upsert is available, importing counters using the fast method'
|
|
|
|
|
|
|
|
Status.unscoped.select('id').find_in_batches(batch_size: 5_000) 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
|
|
|
|
|
|
|
|
def up_slow
|
|
|
|
say 'Upsert is not available in PostgreSQL below 9.5, falling back to slow import of counters'
|
|
|
|
|
|
|
|
# We cannot use bulk INSERT or overarching transactions here because of possible
|
|
|
|
# uniqueness violations that we need to skip over
|
|
|
|
Status.unscoped.select('id, reblogs_count, favourites_count, created_at, updated_at').find_each do |status|
|
2023-08-03 03:54:56 +09:00
|
|
|
params = [status.id, status.reblogs_count, status.favourites_count, status.created_at, status.updated_at]
|
2023-02-19 07:09:40 +09:00
|
|
|
exec_insert('INSERT INTO status_stats (status_id, reblogs_count, favourites_count, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)', nil, params)
|
|
|
|
rescue ActiveRecord::RecordNotUnique
|
|
|
|
next
|
2018-10-07 11:40:37 +09:00
|
|
|
end
|
|
|
|
end
|
2018-08-15 02:19:32 +09:00
|
|
|
end
|