FIX: old migration was loading up invalid model schema

cherry-pick-2-2
approved

#1

FIX: old migration was loading up invalid model schema

Generally we should never be touching AR objects in migrations, this is super risky as we may end up with invalid schema cache.

This code from 2013 did it unconditionally. This change amends it so:

  1. We only load up schema if we have no choice
  2. We flush the cache before and after

This makes this migration far less risky.

diff --git a/db/migrate/20130221215017_add_description_to_categories.rb b/db/migrate/20130221215017_add_description_to_categories.rb
index aa22568..24514a4 100644
--- a/db/migrate/20130221215017_add_description_to_categories.rb
+++ b/db/migrate/20130221215017_add_description_to_categories.rb
@@ -8,10 +8,20 @@ class AddDescriptionToCategories < ActiveRecord::Migration[4.2]
     remove_column :categories, :top1_user_id
     remove_column :categories, :top2_user_id
 
-    # Migrate excerpts over
-    Category.order('id').each do |c|
-      post = c.topic.posts.order(:post_number).first
-      PostRevisor.new(post).send(:update_category_description)
+    # some ancient installs may have bad category descriptions
+    # attempt to fix
+    if !DB.query_single("SELECT 1 FROM categories limit 1").empty?
+
+      # Reaching into post revisor is not ideal here, but this code
+      # should almost never run, so bypass it
+      Discourse.reset_active_record_cache
+
+      Category.order('id').each do |c|
+        post = c.topic.ordered_posts.first
+        PostRevisor.new(post).update_category_description
+      end
+
+      Discourse.reset_active_record_cache
     end
 
   end

GitHub sha: 19386ec2


Approved #2