From 8fd9776e43accabbed5fd71cc03e892d27722846 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Tue, 10 Dec 2013 17:26:46 -0500 Subject: [PATCH] Use COALESCE in case there are no posts in a topic --- db/migrate/20131210181901_migrate_word_counts.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/migrate/20131210181901_migrate_word_counts.rb b/db/migrate/20131210181901_migrate_word_counts.rb index 35a2c6c398..bc5d7c9c65 100644 --- a/db/migrate/20131210181901_migrate_word_counts.rb +++ b/db/migrate/20131210181901_migrate_word_counts.rb @@ -5,13 +5,13 @@ class MigrateWordCounts < ActiveRecord::Migration post_ids = execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i } while post_ids.length > 0 - execute "UPDATE posts SET word_count = array_length(regexp_split_to_array(raw, ' '),1) WHERE id IN (#{post_ids.join(',')})" + execute "UPDATE posts SET word_count = COALESCE(array_length(regexp_split_to_array(raw, ' '),1), 0) WHERE id IN (#{post_ids.join(',')})" post_ids = execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i } end topic_ids = execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i } while topic_ids.length > 0 - execute "UPDATE topics SET word_count = (SELECT SUM(COALESCE(posts.word_count, 0)) FROM posts WHERE posts.topic_id = topics.id) WHERE topics.id IN (#{topic_ids.join(',')})" + 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(',')})" topic_ids = execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i } end