2019-05-02 18:17:27 -04:00
# frozen_string_literal: true
2017-08-31 00:06:56 -04:00
class MigrateWordCounts < ActiveRecord :: Migration [ 4 . 2 ]
2013-12-10 19:52:55 -05:00
disable_ddl_transaction!
2013-12-31 14:37:43 -05:00
2013-12-10 13:47:07 -05:00
def up
2017-07-27 21:20:09 -04:00
post_ids = execute ( " SELECT id FROM posts WHERE word_count IS NULL LIMIT 500 " ) . map { | r | r [ 'id' ] . to_i }
2013-12-10 13:47:07 -05:00
while post_ids . length > 0
2013-12-10 18:10:52 -05:00
3 . times do
begin
execute " UPDATE posts SET word_count = COALESCE(array_length(regexp_split_to_array(raw, ' '),1), 0) WHERE id IN ( #{ post_ids . join ( ',' ) } ) "
break
rescue PG :: Error
# Deadlock. Try again, up to 3 times.
end
end
2017-07-27 21:20:09 -04:00
post_ids = execute ( " SELECT id FROM posts WHERE word_count IS NULL LIMIT 500 " ) . map { | r | r [ 'id' ] . to_i }
2013-12-10 13:47:07 -05:00
end
2017-07-27 21:20:09 -04:00
topic_ids = execute ( " SELECT id FROM topics WHERE word_count IS NULL LIMIT 500 " ) . map { | r | r [ 'id' ] . to_i }
2013-12-10 13:47:07 -05:00
while topic_ids . length > 0
2013-12-10 18:10:52 -05:00
3 . times do
begin
execute " UPDATE topics SET word_count = COALESCE((SELECT SUM(COALESCE(posts.word_count, 0)) FROM posts WHERE posts.topic_id = topics.id), 0) WHERE topics.id IN ( #{ topic_ids . join ( ',' ) } ) "
break
rescue PG :: Error
# Deadlock. Try again, up to 3 times.
end
end
2017-07-27 21:20:09 -04:00
topic_ids = execute ( " SELECT id FROM topics WHERE word_count IS NULL LIMIT 500 " ) . map { | r | r [ 'id' ] . to_i }
2013-12-10 13:47:07 -05:00
end
end
2015-04-24 13:10:43 -04:00
end