<commit_before>class CategoryFeaturedTopic < ActiveRecord::Base
  belongs_to :category
  belongs_to :topic

  # Populates the category featured topics
  def self.feature_topics
    transaction do
      current = {}
      CategoryFeaturedTopic.select(:topic_id, :category_id).order(:rank).each do |f|
        (current[f.category_id] ||= []) << f.topic_id
      end
      Category.select(:id, :topic_id).find_each do |c|
        CategoryFeaturedTopic.feature_topics_for(c, current[c.id] || [])
      end
    end
  end

  def self.feature_topics_for(c, existing=nil)
    return if c.blank?

    query_opts = {
      per_page: SiteSetting.category_featured_topics,
      except_topic_ids: [c.topic_id],
      visible: true,
      no_definitions: true
    }

    # Add topics, even if they're in secured categories:
    query = TopicQuery.new(CategoryFeaturedTopic.fake_admin, query_opts)
    results = query.list_category_topic_ids(c).uniq

    # Add some topics that are visible to everyone:
    anon_query = TopicQuery.new(nil, query_opts.merge({except_topic_ids: [c.topic_id] + results}))
    results += anon_query.list_category_topic_ids(c).uniq

    return if results == existing
<commit_msg>PERF: no need to nest a transaction when featuring topics<commit_after>class CategoryFeaturedTopic < ActiveRecord::Base
  belongs_to :category
  belongs_to :topic

  # Populates the category featured topics
  def self.feature_topics
    current = {}
    CategoryFeaturedTopic.select(:topic_id, :category_id).order(:rank).each do |f|
      (current[f.category_id] ||= []) << f.topic_id
    end
    Category.select(:id, :topic_id).find_each do |c|
      CategoryFeaturedTopic.feature_topics_for(c, current[c.id] || [])
    end
  end

  def self.feature_topics_for(c, existing=nil)
    return if c.blank?

    query_opts = {
      per_page: SiteSetting.category_featured_topics,
      except_topic_ids: [c.topic_id],
      visible: true,
      no_definitions: true
    }

    # Add topics, even if they're in secured categories:
    query = TopicQuery.new(CategoryFeaturedTopic.fake_admin, query_opts)
    results = query.list_category_topic_ids(c).uniq

    # Add some topics that are visible to everyone:
    anon_query = TopicQuery.new(nil, query_opts.merge({except_topic_ids: [c.topic_id] + results}))
    results += anon_query.list_category_topic_ids(c).uniq

    return if results == existing

{'fraction_non_alphanumeric': 0.10087902888237757, 'fraction_numerical': 0.0, 'mean_word_length': 3.7514910536779325, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1993524', 'n_tokens_mistral': 777, 'n_tokens_neox': 764, 'n_words': 166}