Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #9640: preloading.patch

File preloading.patch, 17.1 kB (added by lifofifo, 7 months ago)

Refactored Fred's patch

  • activerecord/test/associations/join_model_test.rb

    old new  
    315315      assert_equal posts(:welcome, :thinking), tags(:general).taggables 
    316316    end 
    317317    assert_raises ActiveRecord::EagerLoadPolymorphicError do 
    318       assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable
    319     end 
     318      assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1'
     319    end     
    320320  end 
    321321   
    322322  def test_has_many_polymorphic_with_source_type 
     
    329329    assert_no_queries do 
    330330      assert_equal desired, tag_with_include.tagged_posts 
    331331    end 
     332    assert_equal 4, tag_with_include.taggings.length 
    332333  end 
    333334 
    334335  def test_has_many_through_has_many_find_all 
     
    518519    assert_equal [comments(:does_it_hurt)], authors(:david).special_post_comments 
    519520  end 
    520521 
     522  def test_polymorphic_has_many 
     523    expected = taggings(:welcome_general) 
     524    p = Post.find(posts(:welcome).id, :include => :taggings) 
     525    assert_no_queries {assert p.taggings.include?(expected)} 
     526    assert posts(:welcome).taggings.include?(taggings(:welcome_general)) 
     527  end 
     528 
     529  def test_polymorphic_has_one 
     530    expected = posts(:welcome) 
     531     
     532    tagging  = Tagging.find(taggings(:welcome_general).id, :include => :taggable) 
     533    assert_no_queries { assert_equal expected, tagging.taggable} 
     534  end 
     535 
     536  def test_polymorphic_belongs_to 
     537    p = Post.find(posts(:welcome).id, :include => {:taggings => :taggable}) 
     538    assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable} 
     539  end 
     540 
     541  def test_preload_polymorphic_has_many_through 
     542    posts           = Post.find(:all, :order => 'posts.id') 
     543    posts_with_tags = Post.find(:all, :include => :tags, :order => 'posts.id') 
     544    assert_equal posts.length, posts_with_tags.length 
     545    posts.length.times do |i| 
     546      assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length } 
     547    end 
     548  end 
     549    
     550  def test_preload_polymorph_many_types 
     551    taggings = Tagging.find :all, :include => :taggable, :conditions => ['taggable_type != ?', 'FakeModel'] 
     552    assert_no_queries do 
     553      taggings.first.taggable.id 
     554      taggings[1].taggable.id 
     555    end 
     556    assert_equal items(:dvd), taggings.last.taggable 
     557    assert_equal posts(:welcome), taggings.first.taggable 
     558  end 
     559 
     560  def test_preload_polymorphic_has_many 
     561    posts               = Post.find(:all, :order => 'posts.id') 
     562    posts_with_taggings = Post.find(:all, :include => :taggings, :order => 'posts.id') 
     563    assert_equal posts.length, posts_with_taggings.length 
     564    posts.length.times do |i| 
     565      assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length } 
     566    end 
     567  end 
     568   
     569  def test_belongs_to_shared_parent 
     570    comments = Comment.find(:all, :include => :post, :conditions => 'post_id = 1') 
     571    assert_no_queries do 
     572      assert_equal comments.first.post, comments[1].post 
     573    end 
     574  end 
     575   
    521576  private 
    522577    # create dynamic Post models to allow different dependency options 
    523578    def find_post_with_dependency(post_id, association, association_name, dependency) 
  • activerecord/test/associations/eager_test.rb

    old new  
    4444    assert posts.first.comments.include?(comments(:greetings)) 
    4545  end 
    4646 
     47  def test_duplicate_middle_objects 
     48    comments = Comment.find :all, :conditions => 'post_id = 1', :include => [:post => :author] 
     49    assert_no_queries do 
     50      comments.each {|comment| comment.post.author.name} 
     51    end 
     52  end 
     53 
    4754  def test_loading_from_an_association 
    4855    posts = authors(:david).posts.find(:all, :include => :comments, :order => "posts.id") 
    4956    assert_equal 2, posts.first.comments.size 
  • activerecord/lib/active_record/association_preload.rb

    old new  
     1module ActiveRecord 
     2  module AssociationPreload #:nodoc: 
     3    def self.included(base) 
     4      base.extend(ClassMethods) 
     5    end 
     6     
     7    module ClassMethods                                                                                                 
     8       
     9      # Loads the named associations for the activerecord record (or records) given 
     10      # preload_options is passed only one level deep: don't pass to the child associations when associations is a Hash 
     11      protected 
     12      def preload_associations(records, associations, preload_options={}) 
     13        records = [records].flatten.compact 
     14        return if records.empty? 
     15        case associations 
     16        when Array then associations.each {|association| preload_associations(records, association, preload_options)} 
     17        when Symbol, String then preload_one_association(records, associations.to_sym, preload_options) 
     18        when Hash then 
     19          associations.each do |parent, child| 
     20            raise "parent must be an association name" unless parent.is_a?(String) || parent.is_a?(Symbol) 
     21            preload_associations(records, parent, preload_options) 
     22            reflection = reflections[parent] 
     23            parents = records.map {|record| record.send(reflection.name)}.flatten 
     24            unless parents.empty? 
     25              parents.first.class.preload_associations(parents, child) 
     26            end 
     27          end 
     28        end   
     29      end     
     30     
     31      private 
     32     
     33      def preload_one_association(records, association, preload_options={})  
     34        reflection = reflections[association] 
     35        raise ConfigurationError, "Association named '#{ association }' was not found; perhaps you misspelled it?" unless reflection 
     36         
     37        send(:"preload_#{reflection.macro}_association", records, reflection, preload_options) 
     38      end 
     39     
     40      def add_preloaded_records_to_collection(parent_records, reflection_name, associated_record) 
     41        parent_records.each do |parent_record| 
     42          association_proxy = parent_record.send(reflection_name) 
     43          association_proxy.loaded 
     44          association_proxy.target.push(*[associated_record].flatten) 
     45        end 
     46      end 
     47       
     48      def set_association_collection_records(id_to_record_map, reflection_name, associated_records, key) 
     49        associated_records.each do |associated_record| 
     50          mapped_records = id_to_record_map[associated_record[key].to_i] 
     51          add_preloaded_records_to_collection(mapped_records, reflection_name, associated_record) 
     52        end 
     53      end 
     54       
     55      def set_association_single_records(id_to_record_map, reflection_name, associated_records, key) 
     56        associated_records.each do |associated_record| 
     57          mapped_records = id_to_record_map[associated_record[key].to_i] 
     58          mapped_records.each do |mapped_record| 
     59            mapped_record.send("set_#{reflection_name}_target", associated_record) 
     60          end 
     61        end 
     62      end 
     63 
     64      def construct_id_map(records) 
     65        id_to_record_map = {} 
     66        ids = [] 
     67        records.each do |record| 
     68          ids << record.id 
     69          mapped_records = (id_to_record_map[record.id] ||= []) 
     70          mapped_records << record 
     71        end 
     72        ids.uniq! 
     73        return id_to_record_map, ids 
     74      end 
     75               
     76      def preload_has_and_belongs_to_many_association(records, reflection, preload_options={}) 
     77        table_name = reflection.klass.table_name 
     78        id_to_record_map, ids = construct_id_map(records) 
     79        records.each {|record| record.send(reflection.name).loaded} 
     80        options = reflection.options 
     81 
     82        conditions = "t0.#{reflection.primary_key_name}  IN (?)" 
     83        conditions << " AND (#{options[:conditions]})" if options[:conditions] 
     84        conditions << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions] 
     85 
     86        associated_records = reflection.klass.find(:all, :conditions => [conditions, ids], 
     87        :include => options[:include], 
     88        :joins => "INNER JOIN #{options[:join_table]} as t0 ON #{reflection.klass.table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}", 
     89        :select => "#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as _parent_record_id", 
     90        :order => options[:order]) 
     91 
     92        set_association_collection_records(id_to_record_map, reflection.name, associated_records, '_parent_record_id') 
     93      end 
     94 
     95      def foreign_key_for_preload reflection 
     96        options = reflection.options 
     97        if options[:as] 
     98          foreign_key = "#{options[:as]}_id" 
     99        else 
     100          foreign_key = options[:foreign_key] || reflection.active_record.to_s.foreign_key   
     101        end           
     102      end 
     103 
     104      def preload_has_one_association(records, reflection, preload_options={}) 
     105        id_to_record_map, ids = construct_id_map(records) 
     106        records.each {|record| record.send("set_#{reflection.name}_target", nil)} 
     107         
     108        set_association_single_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options), 
     109                                       foreign_key_for_preload(reflection)) 
     110      end 
     111 
     112      def preload_has_many_association(records, reflection, preload_options={}) 
     113        id_to_record_map, ids = construct_id_map(records) 
     114        records.each {|record| record.send(reflection.name).loaded} 
     115        options = reflection.options 
     116 
     117        if options[:through] 
     118          through_records = preload_through_records(records, reflection, options[:through]) 
     119          through_reflection = reflections[options[:through]]               
     120          through_primary_key = through_reflection.primary_key_name 
     121          unless through_records.empty? 
     122            source = reflection.source_reflection.name 
     123            through_records.first.class.preload_associations(through_records, source) 
     124            through_records.compact.each do |through_record| 
     125              add_preloaded_records_to_collection(id_to_record_map[through_record[through_primary_key].to_i],  
     126                                                 reflection.name, through_record.send(source)) 
     127            end 
     128          end 
     129        else 
     130          set_association_collection_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options), 
     131                                             foreign_key_for_preload(reflection)) 
     132        end 
     133      end 
     134 
     135      def preload_through_records(records, reflection, through_association) 
     136        through_reflection = reflections[through_association]               
     137        through_primary_key = through_reflection.primary_key_name 
     138         
     139        if reflection.options[:source_type] 
     140          interface = reflection.source_reflection.options[:foreign_type] 
     141          preload_options = {:conditions => ["#{interface} = ?", reflection.options[:source_type]]} 
     142 
     143          records.first.class.preload_associations(records, through_association, preload_options) 
     144                             
     145          # Dont cache the association - we would only be caching a subset 
     146          through_records = [] 
     147          records.compact.each do |record| 
     148            proxy = record.send(through_association) 
     149            through_records << proxy.target 
     150            proxy.reset 
     151          end 
     152          through_records = through_records.flatten 
     153        else 
     154          records.first.class.preload_associations(records, through_association) 
     155          through_records = records.compact.map {|record| record.send(through_association)}.flatten 
     156        end 
     157      end 
     158 
     159      def preload_belongs_to_association(records, reflection, preload_options={}) 
     160        options = reflection.options 
     161        primary_key_name = reflection.primary_key_name 
     162 
     163        if options[:polymorphic] 
     164          polymorph_type = options[:foreign_type] 
     165          klasses_and_ids = {} 
     166 
     167          # Construct a mapping from klass to a list of ids to load and a mapping of those ids back to their parent_records 
     168          records.each do |record| 
     169            klass = record.send(polymorph_type) 
     170            klass_id = record.send(primary_key_name) 
     171     
     172            id_map = klasses_and_ids[klass] ||= {} 
     173            id_list_for_klass_id = (id_map[klass_id] ||= []) 
     174            id_list_for_klass_id << record 
     175          end 
     176          klasses_and_ids = klasses_and_ids.to_a 
     177        else 
     178          id_map = {} 
     179          records.each do |record| 
     180            mapped_records = (id_map[record.send(primary_key_name)] ||= []) 
     181            mapped_records << record 
     182          end 
     183          klasses_and_ids = [[reflection.klass.name, id_map]] 
     184        end 
     185 
     186        klasses_and_ids.each do |klass_and_id| 
     187          klass_name, id_map = *klass_and_id 
     188          klass = klass_name.constantize 
     189   
     190          table_name = klass.table_name 
     191          conditions = "#{table_name}.#{primary_key} IN (?)" 
     192          conditions << " AND (#{sanitize_sql options[:conditions]})" if options[:conditions] 
     193          conditions << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions] 
     194          associated_records = klass.find(:all, :conditions => [conditions, id_map.keys.uniq], 
     195                                          :include => options[:include], 
     196                                          :order => options[:order]) 
     197          set_association_single_records(id_map, reflection.name, associated_records, 'id') 
     198        end 
     199      end  
     200       
     201      def find_associated_records(ids, reflection, preload_options) 
     202        options = reflection.options         
     203        table_name = reflection.klass.table_name 
     204                 
     205        if interface = reflection.options[:as] 
     206          conditions = "#{reflection.klass.table_name}.#{interface}_id IN (?) and #{reflection.klass.table_name}.#{interface}_type = '#{self.name}'" 
     207        else 
     208          foreign_key = options[:foreign_key] || reflection.active_record.to_s.foreign_key 
     209          conditions = "#{reflection.klass.table_name}.#{foreign_key} IN (?)" 
     210        end 
     211         
     212        conditions << " AND (#{sanitize_sql options[:conditions]})" if options[:conditions] 
     213        conditions << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions] 
     214         
     215        reflection.klass.find(:all,  
     216                              :conditions => [conditions, ids], 
     217                              :select => (options[:select] || "#{table_name}.*"), 
     218                              :include => options[:include], 
     219                              :order => options[:order]) 
     220      end 
     221    end 
     222  end 
     223end 
  • activerecord/lib/active_record/associations.rb

    old new  
    13301330            order_table_name != table_name 
    13311331          end 
    13321332        end 
     1333         
     1334        def references_eager_loaded_tables?(options) 
     1335          include_eager_order?(options) || include_eager_conditions?(options) 
     1336        end 
    13331337 
    13341338        def using_limitable_reflections?(reflections) 
    13351339          reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero? 
  • activerecord/lib/active_record/base.rb

    old new  
    10051005        end 
    10061006 
    10071007        def find_every(options) 
    1008           records = scoped?(:find, :include) || options[:include] ? 
    1009             find_with_associations(options) :  
    1010             find_by_sql(construct_finder_sql(options)) 
     1008          include_associations = merge_includes(scope(:find, :include), options[:include]) 
     1009          if include_associations.any? && references_eager_loaded_tables?(options) 
     1010            records = find_with_associations(options) 
     1011          else   
     1012            records = find_by_sql(construct_finder_sql(options)) 
     1013            preload_associations(records, include_associations) if include_associations.any? 
     1014          end 
    10111015 
    10121016          records.each { |record| record.readonly! } if options[:readonly] 
    10131017 
  • activerecord/lib/active_record.rb

    old new  
    4343require 'active_record/callbacks' 
    4444require 'active_record/reflection' 
    4545require 'active_record/associations' 
     46require 'active_record/association_preload' 
    4647require 'active_record/aggregations' 
    4748require 'active_record/transactions' 
    4849require 'active_record/timestamp' 
     
    6364  include ActiveRecord::Observing 
    6465  include ActiveRecord::Timestamp 
    6566  include ActiveRecord::Associations 
     67  include ActiveRecord::AssociationPreload 
    6668  include ActiveRecord::Aggregations 
    6769  include ActiveRecord::Transactions 
    6870  include ActiveRecord::Reflection