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

Ticket #9640: preloading.7.patch

File preloading.7.patch, 20.0 kB (added by fcheung, 4 months ago)

rebased on latest edge

  • activerecord/test/associations/join_model_test.rb

    old new  
    317317      assert_equal posts(:welcome, :thinking), tags(:general).taggables 
    318318    end 
    319319    assert_raise ActiveRecord::EagerLoadPolymorphicError do 
    320       assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable
     320      assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1'
    321321    end 
    322322  end 
    323323   
     
    331331    assert_no_queries do 
    332332      assert_equal desired, tag_with_include.tagged_posts 
    333333    end 
     334    assert_equal 4, tag_with_include.taggings.length 
    334335  end 
    335336 
    336337  def test_has_many_through_has_many_find_all 
     
    546547    assert_equal comment_ids.sort.reverse, authors(:david).ordered_uniq_comments_desc.map(&:id) 
    547548  end 
    548549 
     550  def test_polymorphic_has_many 
     551    expected = taggings(:welcome_general) 
     552    p = Post.find(posts(:welcome).id, :include => :taggings) 
     553    assert_no_queries {assert p.taggings.include?(expected)} 
     554    assert posts(:welcome).taggings.include?(taggings(:welcome_general)) 
     555  end 
     556 
     557  def test_polymorphic_has_one 
     558    expected = posts(:welcome) 
     559     
     560    tagging  = Tagging.find(taggings(:welcome_general).id, :include => :taggable) 
     561    assert_no_queries { assert_equal expected, tagging.taggable} 
     562  end 
     563 
     564  def test_polymorphic_belongs_to 
     565    p = Post.find(posts(:welcome).id, :include => {:taggings => :taggable}) 
     566    assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable} 
     567  end 
     568 
     569  def test_preload_polymorphic_has_many_through 
     570    posts           = Post.find(:all, :order => 'posts.id') 
     571    posts_with_tags = Post.find(:all, :include => :tags, :order => 'posts.id') 
     572    assert_equal posts.length, posts_with_tags.length 
     573    posts.length.times do |i| 
     574      assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length } 
     575    end 
     576  end 
     577    
     578  def test_preload_polymorph_many_types 
     579    taggings = Tagging.find :all, :include => :taggable, :conditions => ['taggable_type != ?', 'FakeModel'] 
     580    assert_no_queries do 
     581      taggings.first.taggable.id 
     582      taggings[1].taggable.id 
     583    end 
     584    assert_equal items(:dvd), taggings.last.taggable 
     585    assert_equal posts(:welcome), taggings.first.taggable 
     586  end 
     587 
     588  def test_preload_polymorphic_has_many 
     589    posts               = Post.find(:all, :order => 'posts.id') 
     590    posts_with_taggings = Post.find(:all, :include => :taggings, :order => 'posts.id') 
     591    assert_equal posts.length, posts_with_taggings.length 
     592    posts.length.times do |i| 
     593      assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length } 
     594    end 
     595  end 
     596   
     597  def test_belongs_to_shared_parent 
     598    comments = Comment.find(:all, :include => :post, :conditions => 'post_id = 1') 
     599    assert_no_queries do 
     600      assert_equal comments.first.post, comments[1].post 
     601    end 
     602  end 
     603   
    549604  private 
    550605    # create dynamic Post models to allow different dependency options 
    551606    def find_post_with_dependency(post_id, association, association_name, dependency) 
  • activerecord/test/associations/eager_test.rb

    old new  
    5656    assert posts.first.comments.include?(comments(:greetings)) 
    5757  end 
    5858 
     59  def test_duplicate_middle_objects 
     60    comments = Comment.find :all, :conditions => 'post_id = 1', :include => [:post => :author] 
     61    assert_no_queries do 
     62      comments.each {|comment| comment.post.author.name} 
     63    end 
     64  end 
     65 
    5966  def test_loading_from_an_association 
    6067    posts = authors(:david).posts.find(:all, :include => :comments, :order => "posts.id") 
    6168    assert_equal 2, posts.first.comments.size 
     
    353360    assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC, posts.id', :limit => 2, :offset => 1) 
    354361  end 
    355362 
     363  def test_preload_with_interpolation 
     364    assert_equal [comments(:greetings)], Post.find(posts(:welcome).id, :include => :comments_with_interpolated_conditions).comments_with_interpolated_conditions 
     365  end 
     366   
    356367  def test_eager_with_multiple_associations_with_same_table_has_many_and_habtm 
    357368    # Eager includes of has many and habtm associations aren't necessarily sorted in the same way 
    358369    def assert_equal_after_sort(item1, item2, item3 = nil) 
     
    405416 
    406417  def test_preconfigured_includes_with_belongs_to 
    407418    author = posts(:welcome).author_with_posts 
    408     assert_equal 5, author.posts.size 
     419    assert_no_queries {assert_equal 5, author.posts.size} 
    409420  end 
    410421 
    411422  def test_preconfigured_includes_with_has_one 
    412423    comment = posts(:sti_comments).very_special_comment_with_post 
    413     assert_equal posts(:sti_comments), comment.post 
     424    assert_no_queries {assert_equal posts(:sti_comments), comment.post} 
    414425  end 
    415426 
    416427  def test_preconfigured_includes_with_has_many 
    417428    posts = authors(:david).posts_with_comments 
    418429    one = posts.detect { |p| p.id == 1 } 
    419     assert_equal 5, posts.size 
    420     assert_equal 2, one.comments.size 
     430    assert_no_queries do 
     431      assert_equal 5, posts.size 
     432      assert_equal 2, one.comments.size 
     433    end 
    421434  end 
    422435 
    423436  def test_preconfigured_includes_with_habtm 
    424437    posts = authors(:david).posts_with_categories 
    425438    one = posts.detect { |p| p.id == 1 } 
    426     assert_equal 5, posts.size 
    427     assert_equal 2, one.categories.size 
     439    assert_no_queries do 
     440      assert_equal 5, posts.size 
     441      assert_equal 2, one.categories.size 
     442    end 
    428443  end 
    429444 
    430445  def test_preconfigured_includes_with_has_many_and_habtm 
    431446    posts = authors(:david).posts_with_comments_and_categories 
    432447    one = posts.detect { |p| p.id == 1 } 
    433     assert_equal 5, posts.size 
    434     assert_equal 2, one.comments.size 
    435     assert_equal 2, one.categories.size 
     448    assert_no_queries do 
     449      assert_equal 5, posts.size 
     450      assert_equal 2, one.comments.size 
     451      assert_equal 2, one.categories.size 
     452    end 
    436453  end 
    437454   
    438455  def test_count_with_include 
  • activerecord/test/fixtures/post.rb

    old new  
    1212      find(:first, :order => "id DESC") 
    1313    end 
    1414  end 
     15   
     16  has_many :comments_with_interpolated_conditions, :class_name => 'Comment', 
     17      :conditions => ['#{"#{aliased_table_name}." rescue ""}body = ?', 'Thank you for the welcome'] 
    1518 
    1619  has_one  :very_special_comment 
    1720  has_one  :very_special_comment_with_post, :class_name => "VerySpecialComment", :include => :post 
  • 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 << append_conditions(options, preload_options) 
     84         
     85        associated_records = reflection.klass.find(:all, :conditions => [conditions, ids], 
     86        :include => options[:include], 
     87        :joins => "INNER JOIN #{options[:join_table]} as t0 ON #{reflection.klass.table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}", 
     88        :select => "#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as _parent_record_id", 
     89        :order => options[:order]) 
     90 
     91        set_association_collection_records(id_to_record_map, reflection.name, associated_records, '_parent_record_id') 
     92      end 
     93 
     94      def preload_has_one_association(records, reflection, preload_options={}) 
     95        id_to_record_map, ids = construct_id_map(records) 
     96        records.each {|record| record.send("set_#{reflection.name}_target", nil)} 
     97         
     98        set_association_single_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options), 
     99                                       reflection.primary_key_name) 
     100      end 
     101 
     102      def preload_has_many_association(records, reflection, preload_options={}) 
     103        id_to_record_map, ids = construct_id_map(records) 
     104        records.each {|record| record.send(reflection.name).loaded} 
     105        options = reflection.options 
     106 
     107        if options[:through] 
     108          through_records = preload_through_records(records, reflection, options[:through]) 
     109          through_reflection = reflections[options[:through]]               
     110          through_primary_key = through_reflection.primary_key_name 
     111          unless through_records.empty? 
     112            source = reflection.source_reflection.name 
     113            through_records.first.class.preload_associations(through_records, source) 
     114            through_records.compact.each do |through_record| 
     115              add_preloaded_records_to_collection(id_to_record_map[through_record[through_primary_key].to_i],  
     116                                                 reflection.name, through_record.send(source)) 
     117            end 
     118          end 
     119        else 
     120          set_association_collection_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options), 
     121                                             reflection.primary_key_name) 
     122        end 
     123      end 
     124 
     125      def preload_through_records(records, reflection, through_association) 
     126        through_reflection = reflections[through_association]               
     127        through_primary_key = through_reflection.primary_key_name 
     128         
     129        if reflection.options[:source_type] 
     130          interface = reflection.source_reflection.options[:foreign_type] 
     131          preload_options = {:conditions => ["#{interface} = ?", reflection.options[:source_type]]} 
     132 
     133          records.first.class.preload_associations(records, through_association, preload_options) 
     134                             
     135          # Dont cache the association - we would only be caching a subset 
     136          through_records = [] 
     137          records.compact.each do |record| 
     138            proxy = record.send(through_association) 
     139            through_records << proxy.target 
     140            proxy.reset 
     141          end 
     142          through_records = through_records.flatten 
     143        else 
     144          records.first.class.preload_associations(records, through_association) 
     145          through_records = records.compact.map {|record| record.send(through_association)}.flatten 
     146        end 
     147      end 
     148 
     149      def preload_belongs_to_association(records, reflection, preload_options={}) 
     150        options = reflection.options 
     151        primary_key_name = reflection.primary_key_name 
     152 
     153        if options[:polymorphic] 
     154          polymorph_type = options[:foreign_type] 
     155          klasses_and_ids = {} 
     156 
     157          # Construct a mapping from klass to a list of ids to load and a mapping of those ids back to their parent_records 
     158          records.each do |record| 
     159            klass = record.send(polymorph_type) 
     160            klass_id = record.send(primary_key_name) 
     161     
     162            id_map = klasses_and_ids[klass] ||= {} 
     163            id_list_for_klass_id = (id_map[klass_id] ||= []) 
     164            id_list_for_klass_id << record 
     165          end 
     166          klasses_and_ids = klasses_and_ids.to_a 
     167        else 
     168          id_map = {} 
     169          records.each do |record| 
     170            mapped_records = (id_map[record.send(primary_key_name)] ||= []) 
     171            mapped_records << record 
     172          end 
     173          klasses_and_ids = [[reflection.klass.name, id_map]] 
     174        end 
     175 
     176        klasses_and_ids.each do |klass_and_id| 
     177          klass_name, id_map = *klass_and_id 
     178          klass = klass_name.constantize 
     179   
     180          table_name = klass.table_name 
     181          conditions = "#{table_name}.#{primary_key} IN (?)" 
     182          conditions << append_conditions(options, preload_options) 
     183          associated_records = klass.find(:all, :conditions => [conditions, id_map.keys.uniq], 
     184                                          :include => options[:include], 
     185                                          :select => options[:select], 
     186                                          :joins => options[:joins], 
     187                                          :order => options[:order]) 
     188          set_association_single_records(id_map, reflection.name, associated_records, 'id') 
     189        end 
     190      end  
     191       
     192      def find_associated_records(ids, reflection, preload_options) 
     193        options = reflection.options         
     194        table_name = reflection.klass.table_name 
     195                 
     196        if interface = reflection.options[:as] 
     197          conditions = "#{reflection.klass.table_name}.#{interface}_id IN (?) and #{reflection.klass.table_name}.#{interface}_type = '#{self.name}'" 
     198        else 
     199          foreign_key = reflection.primary_key_name 
     200          conditions = "#{reflection.klass.table_name}.#{foreign_key} IN (?)" 
     201        end 
     202         
     203        conditions << append_conditions(options, preload_options) 
     204         
     205        reflection.klass.find(:all,  
     206                              :select => (options[:select] || "#{table_name}.*"), 
     207                              :include => options[:include], 
     208                              :conditions => [conditions, ids], 
     209                              :joins => options[:joins], 
     210                              :group => options[:group], 
     211                              :order => options[:order]) 
     212      end 
     213       
     214       
     215      def interpolate_sql_for_preload(sql) 
     216        instance_eval("%@#{sql.gsub('@', '\@')}@")  
     217      end 
     218       
     219      def append_conditions(options, preload_options) 
     220        sql = "" 
     221        sql << " AND (#{interpolate_sql_for_preload(sanitize_sql(options[:conditions]))})" if options[:conditions] 
     222        sql << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions] 
     223        sql 
     224      end 
     225       
     226    end 
     227  end 
     228end 
  • activerecord/lib/active_record/associations.rb

    old new  
    13521352            order_table_name != table_name 
    13531353          end 
    13541354        end 
     1355         
     1356        def references_eager_loaded_tables?(options) 
     1357          include_eager_order?(options) || include_eager_conditions?(options) 
     1358        end 
    13551359 
    13561360        def using_limitable_reflections?(reflections) 
    13571361          reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero? 
  • activerecord/lib/active_record/base.rb

    old new  
    12371237        end 
    12381238 
    12391239        def find_every(options) 
    1240           records = scoped?(:find, :include) || options[:include] ? 
    1241             find_with_associations(options) : 
    1242             find_by_sql(construct_finder_sql(options)) 
    1243  
     1240          include_associations = merge_includes(scope(:find, :include), options[:include]) 
     1241           
     1242          if include_associations.any? && references_eager_loaded_tables?(options) 
     1243            records = find_with_associations(options) 
     1244          else 
     1245            records = find_by_sql(construct_finder_sql(options)) 
     1246            if include_associations.any? 
     1247              preload_associations(records, include_associations)  
     1248            end 
     1249          end 
     1250           
    12441251          records.each { |record| record.readonly! } if options[:readonly] 
    12451252 
    12461253          records 
  • 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