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

Ticket #9640: preloading.6.patch

File preloading.6.patch, 20.5 kB (added by fcheung, 5 months ago)

beef up some tests & pass more association options through

  • activerecord/test/associations/join_model_test.rb

    old new  
    317317      assert_equal posts(:welcome, :thinking), tags(:general).taggables 
    318318    end 
    319319    assert_raises ActiveRecord::EagerLoadPolymorphicError do 
    320       assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable
    321     end 
     320      assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1'
     321    end     
    322322  end 
    323323   
    324324  def test_has_many_polymorphic_with_source_type 
     
    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 
     
    540541    assert_equal [comments(:does_it_hurt)], authors(:david).special_post_comments 
    541542  end 
    542543 
     544  def test_polymorphic_has_many 
     545    expected = taggings(:welcome_general) 
     546    p = Post.find(posts(:welcome).id, :include => :taggings) 
     547    assert_no_queries {assert p.taggings.include?(expected)} 
     548    assert posts(:welcome).taggings.include?(taggings(:welcome_general)) 
     549  end 
     550 
     551  def test_polymorphic_has_one 
     552    expected = posts(:welcome) 
     553     
     554    tagging  = Tagging.find(taggings(:welcome_general).id, :include => :taggable) 
     555    assert_no_queries { assert_equal expected, tagging.taggable} 
     556  end 
     557 
     558  def test_polymorphic_belongs_to 
     559    p = Post.find(posts(:welcome).id, :include => {:taggings => :taggable}) 
     560    assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable} 
     561  end 
     562 
     563  def test_preload_polymorphic_has_many_through 
     564    posts           = Post.find(:all, :order => 'posts.id') 
     565    posts_with_tags = Post.find(:all, :include => :tags, :order => 'posts.id') 
     566    assert_equal posts.length, posts_with_tags.length 
     567    posts.length.times do |i| 
     568      assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length } 
     569    end 
     570  end 
     571    
     572  def test_preload_polymorph_many_types 
     573    taggings = Tagging.find :all, :include => :taggable, :conditions => ['taggable_type != ?', 'FakeModel'] 
     574    assert_no_queries do 
     575      taggings.first.taggable.id 
     576      taggings[1].taggable.id 
     577    end 
     578    assert_equal items(:dvd), taggings.last.taggable 
     579    assert_equal posts(:welcome), taggings.first.taggable 
     580  end 
     581 
     582  def test_preload_polymorphic_has_many 
     583    posts               = Post.find(:all, :order => 'posts.id') 
     584    posts_with_taggings = Post.find(:all, :include => :taggings, :order => 'posts.id') 
     585    assert_equal posts.length, posts_with_taggings.length 
     586    posts.length.times do |i| 
     587      assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length } 
     588    end 
     589  end 
     590   
     591  def test_belongs_to_shared_parent 
     592    comments = Comment.find(:all, :include => :post, :conditions => 'post_id = 1') 
     593    assert_no_queries do 
     594      assert_equal comments.first.post, comments[1].post 
     595    end 
     596  end 
     597   
    543598  private 
    544599    # create dynamic Post models to allow different dependency options 
    545600    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 
     
    348355    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) 
    349356  end 
    350357 
     358  def test_preload_with_interpolation 
     359    assert_equal [comments(:greetings)], Post.find(posts(:welcome).id, :include => :comments_with_interpolated_conditions).comments_with_interpolated_conditions 
     360  end 
     361   
    351362  def test_eager_with_multiple_associations_with_same_table_has_many_and_habtm 
    352363    # Eager includes of has many and habtm associations aren't necessarily sorted in the same way 
    353364    def assert_equal_after_sort(item1, item2, item3 = nil) 
     
    400411 
    401412  def test_preconfigured_includes_with_belongs_to 
    402413    author = posts(:welcome).author_with_posts 
    403     assert_equal 5, author.posts.size 
     414    assert_no_queries {assert_equal 5, author.posts.size} 
    404415  end 
    405416 
    406417  def test_preconfigured_includes_with_has_one 
    407418    comment = posts(:sti_comments).very_special_comment_with_post 
    408     assert_equal posts(:sti_comments), comment.post 
     419    assert_no_queries {assert_equal posts(:sti_comments), comment.post} 
    409420  end 
    410421 
    411422  def test_preconfigured_includes_with_has_many 
    412423    posts = authors(:david).posts_with_comments 
    413424    one = posts.detect { |p| p.id == 1 } 
    414     assert_equal 5, posts.size 
    415     assert_equal 2, one.comments.size 
     425    assert_no_queries do 
     426      assert_equal 5, posts.size 
     427      assert_equal 2, one.comments.size 
     428    end 
    416429  end 
    417430 
    418431  def test_preconfigured_includes_with_habtm 
    419432    posts = authors(:david).posts_with_categories 
    420433    one = posts.detect { |p| p.id == 1 } 
    421     assert_equal 5, posts.size 
    422     assert_equal 2, one.categories.size 
     434    assert_no_queries do 
     435      assert_equal 5, posts.size 
     436      assert_equal 2, one.categories.size 
     437    end 
    423438  end 
    424439 
    425440  def test_preconfigured_includes_with_has_many_and_habtm 
    426441    posts = authors(:david).posts_with_comments_and_categories 
    427442    one = posts.detect { |p| p.id == 1 } 
    428     assert_equal 5, posts.size 
    429     assert_equal 2, one.comments.size 
    430     assert_equal 2, one.categories.size 
     443    assert_no_queries do 
     444      assert_equal 5, posts.size 
     445      assert_equal 2, one.comments.size 
     446      assert_equal 2, one.categories.size 
     447    end 
    431448  end 
    432449   
    433450  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 
     
    4245  has_many :readers 
    4346  has_many :people, :through => :readers 
    4447 
     48 
     49   
    4550  def self.what_are_you 
    4651    'a post...' 
    4752  end 
  • 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 foreign_key_for_preload reflection 
     95        options = reflection.options 
     96        if options[:as] 
     97          foreign_key = "#{options[:as]}_id" 
     98        else 
     99          foreign_key = options[:foreign_key] || reflection.active_record.to_s.foreign_key   
     100        end           
     101      end 
     102 
     103      def preload_has_one_association(records, reflection, preload_options={}) 
     104        id_to_record_map, ids = construct_id_map(records) 
     105        records.each {|record| record.send("set_#{reflection.name}_target", nil)} 
     106         
     107        set_association_single_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options), 
     108                                       foreign_key_for_preload(reflection)) 
     109      end 
     110 
     111      def preload_has_many_association(records, reflection, preload_options={}) 
     112        id_to_record_map, ids = construct_id_map(records) 
     113        records.each {|record| record.send(reflection.name).loaded} 
     114        options = reflection.options 
     115 
     116        if options[:through] 
     117          through_records = preload_through_records(records, reflection, options[:through]) 
     118          through_reflection = reflections[options[:through]]               
     119          through_primary_key = through_reflection.primary_key_name 
     120          unless through_records.empty? 
     121            source = reflection.source_reflection.name 
     122            through_records.first.class.preload_associations(through_records, source) 
     123            through_records.compact.each do |through_record| 
     124              add_preloaded_records_to_collection(id_to_record_map[through_record[through_primary_key].to_i],  
     125                                                 reflection.name, through_record.send(source)) 
     126            end 
     127          end 
     128        else 
     129          set_association_collection_records(id_to_record_map, reflection.name, find_associated_records(ids, reflection, preload_options), 
     130                                             foreign_key_for_preload(reflection)) 
     131        end 
     132      end 
     133 
     134      def preload_through_records(records, reflection, through_association) 
     135        through_reflection = reflections[through_association]               
     136        through_primary_key = through_reflection.primary_key_name 
     137         
     138        if reflection.options[:source_type] 
     139          interface = reflection.source_reflection.options[:foreign_type] 
     140          preload_options = {:conditions => ["#{interface} = ?", reflection.options[:source_type]]} 
     141 
     142          records.first.class.preload_associations(records, through_association, preload_options) 
     143                             
     144          # Dont cache the association - we would only be caching a subset 
     145          through_records = [] 
     146          records.compact.each do |record| 
     147            proxy = record.send(through_association) 
     148            through_records << proxy.target 
     149            proxy.reset 
     150          end 
     151          through_records = through_records.flatten 
     152        else 
     153          records.first.class.preload_associations(records, through_association) 
     154          through_records = records.compact.map {|record| record.send(through_association)}.flatten 
     155        end 
     156      end 
     157 
     158      def preload_belongs_to_association(records, reflection, preload_options={}) 
     159        options = reflection.options 
     160        primary_key_name = reflection.primary_key_name 
     161 
     162        if options[:polymorphic] 
     163          polymorph_type = options[:foreign_type] 
     164          klasses_and_ids = {} 
     165 
     166          # Construct a mapping from klass to a list of ids to load and a mapping of those ids back to their parent_records 
     167          records.each do |record| 
     168            klass = record.send(polymorph_type) 
     169            klass_id = record.send(primary_key_name) 
     170     
     171            id_map = klasses_and_ids[klass] ||= {} 
     172            id_list_for_klass_id = (id_map[klass_id] ||= []) 
     173            id_list_for_klass_id << record 
     174          end 
     175          klasses_and_ids = klasses_and_ids.to_a 
     176        else 
     177          id_map = {} 
     178          records.each do |record| 
     179            mapped_records = (id_map[record.send(primary_key_name)] ||= []) 
     180            mapped_records << record 
     181          end 
     182          klasses_and_ids = [[reflection.klass.name, id_map]] 
     183        end 
     184 
     185        klasses_and_ids.each do |klass_and_id| 
     186          klass_name, id_map = *klass_and_id 
     187          klass = klass_name.constantize 
     188   
     189          table_name = klass.table_name 
     190          conditions = "#{table_name}.#{primary_key} IN (?)" 
     191          conditions << append_conditions(options, preload_options) 
     192          associated_records = klass.find(:all, :conditions => [conditions, id_map.keys.uniq], 
     193                                          :include => options[:include], 
     194                                          :select => options[:select], 
     195                                          :joins => options[:joins], 
     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 << append_conditions(options, preload_options) 
     213         
     214        reflection.klass.find(:all,  
     215                              :select => (options[:select] || "#{table_name}.*"), 
     216                              :include => options[:include], 
     217                              :conditions => [conditions, ids], 
     218                              :joins => options[:joins], 
     219                              :group => options[:group], 
     220                              :order => options[:order]) 
     221      end 
     222       
     223       
     224      def interpolate_sql_for_preload(sql) 
     225        instance_eval("%@#{sql.gsub('@', '\@')}@")  
     226      end 
     227       
     228      def append_conditions(options, preload_options) 
     229        sql = "" 
     230        sql << " AND (#{interpolate_sql_for_preload(sanitize_sql(options[:conditions]))})" if options[:conditions] 
     231        sql << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions] 
     232        sql 
     233      end 
     234       
     235    end 
     236  end 
     237end 
  • activerecord/lib/active_record/associations.rb

    old new  
    13331333            order_table_name != table_name 
    13341334          end 
    13351335        end 
     1336         
     1337        def references_eager_loaded_tables?(options) 
     1338          include_eager_order?(options) || include_eager_conditions?(options) 
     1339        end 
    13361340 
    13371341        def using_limitable_reflections?(reflections) 
    13381342          reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero? 
  • activerecord/lib/active_record/base.rb

    old new  
    11551155        end 
    11561156 
    11571157        def find_every(options) 
    1158           records = scoped?(:find, :include) || options[:include] ? 
    1159             find_with_associations(options) :  
    1160             find_by_sql(construct_finder_sql(options)) 
    1161  
     1158          include_associations = merge_includes(scope(:find, :include), options[:include]) 
     1159           
     1160          if include_associations.any?  && references_eager_loaded_tables?(options) 
     1161            records = find_with_associations(options) 
     1162          else 
     1163            records = find_by_sql(construct_finder_sql(options)) 
     1164            preload_associations(records, include_associations) if include_associations.any? 
     1165          end 
    11621166          records.each { |record| record.readonly! } if options[:readonly] 
    11631167 
    11641168          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