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

Ticket #9640: preloading.3.patch

File preloading.3.patch, 18.8 kB (added by fcheung, 2 years ago)

interpolate sql

  • 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 
     
    534535    assert_equal [comments(:does_it_hurt)], authors(:david).special_post_comments 
    535536  end 
    536537 
     538  def test_polymorphic_has_many 
     539    expected = taggings(:welcome_general) 
     540    p = Post.find(posts(:welcome).id, :include => :taggings) 
     541    assert_no_queries {assert p.taggings.include?(expected)} 
     542    assert posts(:welcome).taggings.include?(taggings(:welcome_general)) 
     543  end 
     544 
     545  def test_polymorphic_has_one 
     546    expected = posts(:welcome) 
     547     
     548    tagging  = Tagging.find(taggings(:welcome_general).id, :include => :taggable) 
     549    assert_no_queries { assert_equal expected, tagging.taggable} 
     550  end 
     551 
     552  def test_polymorphic_belongs_to 
     553    p = Post.find(posts(:welcome).id, :include => {:taggings => :taggable}) 
     554    assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable} 
     555  end 
     556 
     557  def test_preload_polymorphic_has_many_through 
     558    posts           = Post.find(:all, :order => 'posts.id') 
     559    posts_with_tags = Post.find(:all, :include => :tags, :order => 'posts.id') 
     560    assert_equal posts.length, posts_with_tags.length 
     561    posts.length.times do |i| 
     562      assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length } 
     563    end 
     564  end 
     565    
     566  def test_preload_polymorph_many_types 
     567    taggings = Tagging.find :all, :include => :taggable, :conditions => ['taggable_type != ?', 'FakeModel'] 
     568    assert_no_queries do 
     569      taggings.first.taggable.id 
     570      taggings[1].taggable.id 
     571    end 
     572    assert_equal items(:dvd), taggings.last.taggable 
     573    assert_equal posts(:welcome), taggings.first.taggable 
     574  end 
     575 
     576  def test_preload_polymorphic_has_many 
     577    posts               = Post.find(:all, :order => 'posts.id') 
     578    posts_with_taggings = Post.find(:all, :include => :taggings, :order => 'posts.id') 
     579    assert_equal posts.length, posts_with_taggings.length 
     580    posts.length.times do |i| 
     581      assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length } 
     582    end 
     583  end 
     584   
     585  def test_belongs_to_shared_parent 
     586    comments = Comment.find(:all, :include => :post, :conditions => 'post_id = 1') 
     587    assert_no_queries do 
     588      assert_equal comments.first.post, comments[1].post 
     589    end 
     590  end 
     591   
    537592  private 
    538593    # create dynamic Post models to allow different dependency options 
    539594    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 
     
    336343    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) 
    337344  end 
    338345 
     346  def test_preload_with_interpolation 
     347    assert_equal [comments(:greetings)], Post.find(posts(:welcome).id, :include => :comments_with_interpolated_conditions).comments_with_interpolated_conditions 
     348  end 
     349   
    339350  def test_eager_with_multiple_associations_with_same_table_has_many_and_habtm 
    340351    # Eager includes of has many and habtm associations aren't necessarily sorted in the same way 
    341352    def assert_equal_after_sort(item1, item2, item3 = nil) 
  • 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 
     
    4144  has_many :readers 
    4245  has_many :people, :through => :readers 
    4346 
     47 
     48   
    4449  def self.what_are_you 
    4550    'a post...' 
    4651  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                                          :order => options[:order]) 
     195          set_association_single_records(id_map, reflection.name, associated_records, 'id') 
     196        end 
     197      end  
     198       
     199      def find_associated_records(ids, reflection, preload_options) 
     200        options = reflection.options         
     201        table_name = reflection.klass.table_name 
     202                 
     203        if interface = reflection.options[:as] 
     204          conditions = "#{reflection.klass.table_name}.#{interface}_id IN (?) and #{reflection.klass.table_name}.#{interface}_type = '#{self.name}'" 
     205        else 
     206          foreign_key = options[:foreign_key] || reflection.active_record.to_s.foreign_key 
     207          conditions = "#{reflection.klass.table_name}.#{foreign_key} IN (?)" 
     208        end 
     209         
     210        conditions << append_conditions(options, preload_options) 
     211         
     212        reflection.klass.find(:all,  
     213                              :conditions => [conditions, ids], 
     214                              :select => (options[:select] || "#{table_name}.*"), 
     215                              :include => options[:include], 
     216                              :order => options[:order]) 
     217      end 
     218       
     219       
     220      def interpolate_sql_for_preload(sql) 
     221        instance_eval("%@#{sql.gsub('@', '\@')}@")  
     222      end 
     223       
     224      def append_conditions(options, preload_options) 
     225        sql = "" 
     226        sql << " AND (#{interpolate_sql_for_preload(sanitize_sql(options[:conditions]))})" if options[:conditions] 
     227        sql << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions] 
     228        sql 
     229      end 
     230       
     231    end 
     232  end 
     233end 
  • activerecord/lib/active_record/associations.rb

    old new  
    13961396            order_table_name != table_name 
    13971397          end 
    13981398        end 
     1399         
     1400        def references_eager_loaded_tables?(options) 
     1401          include_eager_order?(options) || include_eager_conditions?(options) 
     1402        end 
    13991403 
    14001404        def using_limitable_reflections?(reflections) 
    14011405          reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero? 
  • activerecord/lib/active_record/base.rb

    old new  
    10411041        end 
    10421042 
    10431043        def find_every(options) 
    1044           records = scoped?(:find, :include) || options[:include] || scoped?(:find, :ar_joins) || (options[:ar_joins]) ? 
    1045             find_with_associations(options) :  
    1046             find_by_sql(construct_finder_sql(options)) 
    1047  
     1044          include_associations = merge_includes(scope(:find, :include), options[:include]) 
     1045          ar_joins = scoped?(:find, :ar_joins) || (options[:ar_joins]) 
     1046           
     1047          if (include_associations.any?  && references_eager_loaded_tables?(options)) || ar_joins 
     1048            records = find_with_associations(options) 
     1049          else 
     1050            records = find_by_sql(construct_finder_sql(options)) 
     1051            preload_associations(records, include_associations) if include_associations.any? 
     1052          end 
     1053           
    10481054          records.each { |record| record.readonly! } if options[:readonly] 
    10491055 
    10501056          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