diff options
Diffstat (limited to 'activerecord')
49 files changed, 717 insertions, 429 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index bba6447bf9..f7de341fbe 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,5 +1,37 @@ ## Rails 4.0.0 (unreleased) ## +* In previous releases, the following would generate a single query with + an `OUTER JOIN comments`, rather than two separate queries: + + Post.includes(:comments) + .where("comments.name = 'foo'") + + This behaviour relies on matching SQL string, which is an inherently + flawed idea unless we write an SQL parser, which we do not wish to + do. + + Therefore, it is now deprecated. + + To avoid deprecation warnings and for future compatibility, you must + explicitly state which tables you reference, when using SQL snippets: + + Post.includes(:comments) + .where("comments.name = 'foo'") + .references(:comments) + + Note that you do not need to explicitly specify references in the + following cases, as they can be automatically inferred: + + Post.where(comments: { name: 'foo' }) + Post.where('comments.name' => 'foo') + Post.order('comments.name') + + You also do not need to worry about this unless you are doing eager + loading. Basically, don't worry unless you see a deprecation warning + or (in future releases) an SQL error due to a missing JOIN. + + [Jon Leighton] + * Support for the `schema_info` table has been dropped. Please switch to `schema_migrations`. diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb index 8a17f0ced4..0209ce36df 100644 --- a/activerecord/lib/active_record/associations/association_scope.rb +++ b/activerecord/lib/active_record/associations/association_scope.rb @@ -20,7 +20,7 @@ module ActiveRecord # It's okay to just apply all these like this. The options will only be present if the # association supports that option; this is enforced by the association builder. scope = scope.apply_finder_options(options.slice( - :readonly, :include, :eager_load, :order, :limit, :joins, :group, :having, :offset, :select)) + :readonly, :include, :references, :order, :limit, :joins, :group, :having, :offset, :select)) if options[:through] && !options[:include] scope = scope.includes(source_options[:include]) @@ -90,8 +90,11 @@ module ActiveRecord scope = scope.joins(join(foreign_table, constraint)) - unless conditions.empty? - scope = scope.where(sanitize(conditions, table)) + conditions.each do |condition| + condition = interpolate(condition) + condition = { (table.table_alias || table.name) => condition } unless i == 0 + + scope = scope.where(condition) end end end diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb index 776f0d0469..6e2e5f9de0 100644 --- a/activerecord/lib/active_record/associations/builder/association.rb +++ b/activerecord/lib/active_record/associations/builder/association.rb @@ -1,7 +1,7 @@ module ActiveRecord::Associations::Builder class Association #:nodoc: class_attribute :valid_options - self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :eager_load, :extend, :readonly, :validate] + self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate, :references] # Set by subclasses class_attribute :macro diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb index 03963ab060..0d7d28e458 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb @@ -95,8 +95,11 @@ module ActiveRecord conditions = self.conditions[i].dup conditions << { reflection.type => foreign_klass.base_class.name } if reflection.type - unless conditions.empty? - constraint = constraint.and(sanitize(conditions, table)) + conditions.each do |condition| + condition = active_record.send(:sanitize_sql, interpolate(condition), table.table_alias || table.name) + condition = Arel.sql(condition) unless condition.is_a?(Arel::Node) + + constraint = constraint.and(condition) end relation.from(join(table, constraint)) diff --git a/activerecord/lib/active_record/associations/join_helper.rb b/activerecord/lib/active_record/associations/join_helper.rb index f83138195c..cea6ad6944 100644 --- a/activerecord/lib/active_record/associations/join_helper.rb +++ b/activerecord/lib/active_record/associations/join_helper.rb @@ -40,16 +40,6 @@ module ActiveRecord def join(table, constraint) table.create_join(table, table.create_on(constraint), join_type) end - - def sanitize(conditions, table) - conditions = conditions.map do |condition| - condition = active_record.send(:sanitize_sql, interpolate(condition), table.table_alias || table.name) - condition = Arel.sql(condition) unless condition.is_a?(Arel::Node) - condition - end - - conditions.length == 1 ? conditions.first : Arel::Nodes::And.new(conditions) - end end end end diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 298decb0f1..253998fb23 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -95,12 +95,11 @@ module ActiveRecord def build_scope scope = klass.scoped - scope = scope.where(process_conditions(options[:conditions])) - scope = scope.where(process_conditions(preload_options[:conditions])) + scope = scope.where(interpolate(options[:conditions])) + scope = scope.where(interpolate(preload_options[:conditions])) scope = scope.select(preload_options[:select] || options[:select] || table[Arel.star]) scope = scope.includes(preload_options[:include] || options[:include]) - scope = scope.eager_load(preload_options[:eager_load] || options[:eager_load]) if options[:as] scope = scope.where( @@ -113,13 +112,11 @@ module ActiveRecord scope end - def process_conditions(conditions) + def interpolate(conditions) if conditions.respond_to?(:to_proc) - conditions = klass.send(:instance_eval, &conditions) - end - - if conditions - klass.send(:sanitize_sql, conditions) + klass.send(:instance_eval, &conditions) + else + conditions end end end diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb index 97898c53ae..ad6374d09a 100644 --- a/activerecord/lib/active_record/associations/preloader/through_association.rb +++ b/activerecord/lib/active_record/associations/preloader/through_association.rb @@ -53,7 +53,6 @@ module ActiveRecord else if options[:conditions] through_options[:include] = options[:include] || options[:source] - through_options[:eager_load] = options[:eager_load] || options[:source] through_options[:conditions] = options[:conditions] end diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 8031912669..d468663084 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -295,7 +295,7 @@ module ActiveRecord def association_valid?(reflection, record) return true if record.destroyed? || record.marked_for_destruction? - unless valid = record.valid? + unless valid = record.valid?(validation_context) if reflection.options[:autosave] record.errors.each do |attribute, message| attribute = "#{reflection.name}.#{attribute}" diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb index 031918712a..c9c46b8d4f 100644 --- a/activerecord/lib/active_record/counter_cache.rb +++ b/activerecord/lib/active_record/counter_cache.rb @@ -25,9 +25,10 @@ module ActiveRecord self.name end + foreign_key = has_many_association.foreign_key.to_s child_class = has_many_association.klass belongs_to = child_class.reflect_on_all_associations(:belongs_to) - reflection = belongs_to.find { |e| e.class_name == expected_name } + reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key } counter_name = reflection.counter_cache_column stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({ diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb index 09da9ad1d1..94e34e1bd4 100644 --- a/activerecord/lib/active_record/querying.rb +++ b/activerecord/lib/active_record/querying.rb @@ -8,7 +8,7 @@ module ActiveRecord delegate :find_each, :find_in_batches, :to => :scoped delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, - :having, :create_with, :uniq, :to => :scoped + :having, :create_with, :uniq, :references, :to => :scoped delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :to => :scoped # Executes a custom SQL query against your database and returns all the results. The results will diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index bf1de4ba9d..01019db2cc 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -7,7 +7,7 @@ module ActiveRecord class Relation JoinOperation = Struct.new(:relation, :join_class, :on) ASSOCIATION_METHODS = [:includes, :eager_load, :preload] - MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind] + MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind, :references] SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering, :reverse_order, :uniq] include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation @@ -521,14 +521,25 @@ module ActiveRecord # always convert table names to downcase as in Oracle quoted table names are in uppercase joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq + string_tables = tables_in_string(to_sql) - referenced_tables = (tables_in_string(to_sql) - joined_tables) - if referenced_tables.any? + if (references_values - joined_tables).any? + true + elsif (string_tables - joined_tables).any? ActiveSupport::Deprecation.warn( - "Your query appears to reference tables (#{referenced_tables.join(', ')}) that are not " \ - "explicitly joined. This implicit joining is deprecated, so you must explicitly " \ - "reference the tables. For example, instead of Author.includes(:posts).where(\"posts.name = 'foo'\"), " \ - "you should write Author.eager_load(:posts).where(\"posts.name = 'foo'\")." + "It looks like you are eager loading table(s) (one of: #{string_tables.join(', ')}) " \ + "that are referenced in a string SQL snippet. For example: \n" \ + "\n" \ + " Post.includes(:comments).where(\"comments.title = 'foo'\")\n" \ + "\n" \ + "Currently, Active Record recognises the table in the string, and knows to JOIN the " \ + "comments table to the query, rather than loading comments in a separate query. " \ + "However, doing this without writing a full-blown SQL parser is inherently flawed. " \ + "Since we don't want to write an SQL parser, we are removing this functionality. " \ + "From now on, you must explicitly tell Active Record when you are referencing a table " \ + "from a string:\n" \ + "\n" \ + " Post.includes(:comments).where(\"comments.title = 'foo'\").references(:comments)\n\n" ) true else diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 88081edae2..1d04e763f6 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -21,6 +21,18 @@ module ActiveRecord predicates.flatten end + def self.references(attributes) + references = attributes.map do |key, value| + if value.is_a?(Hash) + key + else + key = key.to_s + key.split('.').first.to_sym if key.include?('.') + end + end + references.compact + end + private def self.build(attribute, value) case value diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 44ff8f7b22..b5f202ef6a 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -10,7 +10,7 @@ module ActiveRecord :where_values, :having_values, :bind_values, :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, :from_value, :reordering_value, :reverse_order_value, - :uniq_value + :uniq_value, :references_values def includes(*args) args.reject! {|a| a.blank? } @@ -38,6 +38,24 @@ module ActiveRecord relation end + # Used to indicate that an association is referenced by an SQL string, and should + # therefore be JOINed in any query rather than loaded separately. + # + # For example: + # + # User.includes(:posts).where("posts.name = 'foo'") + # # => Doesn't JOIN the posts table, resulting in an error. + # + # User.includes(:posts).where("posts.name = 'foo'").references(:posts) + # # => Query now knows the string references posts, so adds a JOIN + def references(*args) + return self if args.blank? + + relation = clone + relation.references_values = (references_values + args.flatten.map(&:to_s)).uniq + relation + end + # Works in two unique ways. # # First: takes a block so it can be used just like Array#select. @@ -88,8 +106,14 @@ module ActiveRecord def order(*args) return self if args.blank? + args = args.flatten + references = args.reject { |arg| Arel::Node === arg } + .map { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 } + .compact + relation = clone - relation.order_values += args.flatten + relation = relation.references(references) if references.any? + relation.order_values += args relation end @@ -133,6 +157,7 @@ module ActiveRecord return self if opts.blank? relation = clone + relation = relation.references(PredicateBuilder.references(opts)) if Hash === opts relation.where_values += build_where(opts, rest) relation end @@ -141,6 +166,7 @@ module ActiveRecord return self if opts.blank? relation = clone + relation = relation.references(PredicateBuilder.references(opts)) if Hash === opts relation.having_values += build_where(opts, rest) relation end diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb index de639a48f2..7131aa29b6 100644 --- a/activerecord/lib/active_record/relation/spawn_methods.rb +++ b/activerecord/lib/active_record/relation/spawn_methods.rb @@ -122,7 +122,7 @@ module ActiveRecord result end - VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend, :eager_load, + VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend, :references, :order, :select, :readonly, :group, :having, :from, :lock ] def apply_finder_options(options) @@ -133,7 +133,7 @@ module ActiveRecord finders = options.dup finders.delete_if { |key, value| value.nil? && key != :limit } - ([:joins, :select, :group, :order, :having, :limit, :offset, :from, :lock, :readonly, :eager_load] & finders.keys).each do |finder| + ((VALID_FIND_OPTIONS - [:conditions, :include, :extend]) & finders.keys).each do |finder| relation = relation.send(finder, finders[finder]) end diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb index 9f072c4c39..afce149da9 100644 --- a/activerecord/lib/active_record/validations/associated.rb +++ b/activerecord/lib/active_record/validations/associated.rb @@ -2,7 +2,7 @@ module ActiveRecord module Validations class AssociatedValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) - if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any? + if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?(record.validation_context) }.any? record.errors.add(attribute, :invalid, options.merge(:value => value)) end end diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb index 90e5609782..6733f3e889 100644 --- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb +++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb @@ -61,31 +61,15 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_cascaded_eager_association_loading_with_duplicated_includes - categories = Category.includes(:categorizations).includes(:categorizations => :author) - assert_nothing_raised do - assert_equal Category.count, categories.count - assert_equal Category.count, categories.all.size - end - end - - def test_cascaded_eager_association_loading_with_twice_includes_edge_cases - categories = Category.includes(:categorizations => :author).includes(:categorizations => :post) - assert_nothing_raised do - assert_equal Category.count, categories.count - assert_equal Category.count, categories.all.size - end - end - - def test_cascaded_eager_association_loading_with_duplicated_eager_load - categories = Category.eager_load(:categorizations).eager_load(:categorizations => :author).where("categorizations.id is not null") + categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null").references(:categorizations) assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.all.size end end - def test_cascaded_eager_association_loading_with_twice_eager_load_edge_cases - categories = Category.eager_load(:categorizations => :author).eager_load(:categorizations => :post).where("posts.id is not null") + def test_cascaded_eager_association_loading_with_twice_includes_edge_cases + categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null").references(:posts) assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.all.size @@ -143,7 +127,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase silly.parent_id = 1 assert silly.save - topics = Topic.eager_load(:replies).order('topics.id, replies_topics.id').to_a + topics = Topic.find(:all, :include => :replies, :order => ['topics.id', 'replies_topics.id']) assert_no_queries do assert_equal 2, topics[0].replies.size assert_equal 0, topics[1].replies.size @@ -158,9 +142,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_eager_association_loading_with_multiple_stis_and_order - author = Author.eager_load(:posts => [ :special_comments , :very_special_comment ]). - order('authors.name', 'comments.body', 'very_special_comments_posts.body'). - where('posts.id = 4').first + author = Author.find(:first, :include => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :conditions => 'posts.id = 4') assert_equal authors(:david), author assert_no_queries do author.posts.first.special_comments @@ -169,9 +151,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_eager_association_loading_of_stis_with_multiple_references - authors = Author.eager_load(:posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } }). - order('comments.body, very_special_comments_posts.body'). - where('posts.id = 4') + authors = Author.find(:all, :include => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :conditions => 'posts.id = 4') assert_equal [authors(:david)], authors assert_no_queries do authors.first.posts.first.special_comments.first.post.special_comments diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 0964124a81..1e1958410c 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -123,7 +123,7 @@ class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase assert_nothing_raised do # @davey_mcdave doesn't have any author_favorites includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author } - Author.all :eager_load => includes, :conditions => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name' + Author.all :include => includes, :conditions => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name' end end end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index ac9e3f29f9..b79c69bbb5 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -55,13 +55,16 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_loading_with_one_association_with_non_preload - posts = Post.find(:all, :eager_load => :last_comment, :order => 'comments.id DESC') + posts = Post.find(:all, :include => :last_comment, :order => 'comments.id DESC') post = posts.find { |p| p.id == 1 } assert_equal Post.find(1).last_comment, post.last_comment end def test_loading_conditions_with_or - posts = authors(:david).posts.find(:all, :eager_load => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'") + posts = authors(:david).posts.find( + :all, :include => :comments, :references => :comments, + :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'" + ) assert_nil posts.detect { |p| p.author_id != authors(:david).id }, "expected to find only david's posts" end @@ -164,8 +167,8 @@ class EagerAssociationTest < ActiveRecord::TestCase car_post.categories << categories(:technology) comment = car_post.comments.create!(:body => "hmm") - categories = Category.find(:all, :conditions => ["posts.id=?", car_post.id], - :eager_load => {:posts => :comments}) + categories = Category.find(:all, :conditions => { 'posts.id' => car_post.id }, + :include => {:posts => :comments}) categories.each do |category| assert_equal [comment], category.posts[0].comments end @@ -263,27 +266,36 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_nested_loading_through_has_one_association_with_order_on_association - aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :order => 'authors.id') + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :order => 'authors.id') assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_order_on_nested_association - aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :order => 'posts.id') + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :order => 'posts.id') assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_conditions - aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :conditions => "author_addresses.id > 0") + aa = AuthorAddress.find( + author_addresses(:david_address).id, :include => {:author => :posts}, + :conditions => "author_addresses.id > 0", :references => :author_addresses + ) assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_conditions_on_association - aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :conditions => "authors.id > 0") + aa = AuthorAddress.find( + author_addresses(:david_address).id, :include => {:author => :posts}, + :conditions => "authors.id > 0", :references => :authors + ) assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_conditions_on_nested_association - aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :conditions => "posts.id > 0") + aa = AuthorAddress.find( + author_addresses(:david_address).id, :include => {:author => :posts}, + :conditions => "posts.id > 0", :references => :posts + ) assert_equal aa.author.posts.count, aa.author.posts.length end @@ -332,14 +344,16 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name assert_nothing_raised do - Comment.eager_load(:post).where('posts.id = ?',4).to_a + ActiveSupport::Deprecation.silence do + Comment.find(:all, :include => :post, :conditions => ['posts.id = ?',4]) + end end end def test_eager_association_loading_with_belongs_to_and_conditions_hash comments = [] assert_nothing_raised do - comments = Comment.eager_load(:post).where(:posts => {:id => 4}).limit(3).order('comments.id').to_a + comments = Comment.find(:all, :include => :post, :conditions => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id') end assert_equal 3, comments.length assert_equal [5,6,7], comments.collect { |c| c.id } @@ -351,20 +365,24 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_conditions_string_with_quoted_table_name quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id') assert_nothing_raised do - Comment.eager_load(:post).where("#{quoted_posts_id} = ?",4).to_a + ActiveSupport::Deprecation.silence do + Comment.find(:all, :include => :post, :conditions => ["#{quoted_posts_id} = ?",4]) + end end end def test_eager_association_loading_with_belongs_to_and_order_string_with_unquoted_table_name assert_nothing_raised do - Comment.eager_load(:post).order('posts.id').to_a + Comment.find(:all, :include => :post, :order => 'posts.id') end end def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_table_name quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id') assert_nothing_raised do - Comment.eager_load(:post).order(quoted_posts_id).to_a + ActiveSupport::Deprecation.silence do + Comment.find(:all, :include => :post, :order => quoted_posts_id) + end end end @@ -528,36 +546,41 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers - posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + posts = ActiveSupport::Deprecation.silence do + Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + end assert_equal 2, posts.size - count = Post.count(:eager_load => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + count = ActiveSupport::Deprecation.silence do + Post.count(:include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + end assert_equal count, posts.size end def test_eager_with_has_many_and_limit_and_high_offset - posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ]) + posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => { 'authors.name' => 'David' }) assert_equal 0, posts.size end def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions assert_queries(1) do - posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :offset => 10, - :conditions => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]) + posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, + :conditions => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ], + :references => [:authors, :comments]) assert_equal 0, posts.size end end def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditions assert_queries(1) do - posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :offset => 10, + posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => { 'authors.name' => 'David', 'comments.body' => 'go crazy' }) assert_equal 0, posts.size end end def test_count_eager_with_has_many_and_limit_and_high_offset - posts = Post.eager_load(:author, :comments).limit(2).offset(10).where("authors.name = ?", 'David').count + posts = Post.count(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => { 'authors.name' => 'David' }) assert_equal 0, posts end @@ -569,7 +592,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_count_performed_on_a_has_many_association_with_multi_table_conditional author = authors(:david) author_posts_without_comments = author.posts.select { |post| post.comments.blank? } - assert_equal author_posts_without_comments.size, author.posts.eager_load(:comments).where('comments.id is null').count + assert_equal author_posts_without_comments.size, author.posts.count(:all, :include => :comments, :conditions => 'comments.id is null', :references => :comments) end def test_eager_count_performed_on_a_has_many_through_association_with_multi_table_conditional @@ -606,15 +629,17 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_conditions_on_the_eagers posts = authors(:david).posts.find(:all, - :eager_load => :comments, + :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", + :references => :comments, :limit => 2 ) assert_equal 2, posts.size count = Post.count( - :eager_load => [ :comments, :author ], + :include => [ :comments, :author ], :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", + :references => [:authors, :comments], :limit => 2 ) assert_equal count, posts.size @@ -623,16 +648,18 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_scoped_conditions_on_the_eagers posts = nil Post.send(:with_scope, :find => { - :eager_load => :comments, - :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'" + :include => :comments, + :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", + :references => :comments }) do posts = authors(:david).posts.find(:all, :limit => 2) assert_equal 2, posts.size end Post.send(:with_scope, :find => { - :eager_load => [ :comments, :author ], - :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')" + :include => [ :comments, :author ], + :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", + :references => [:authors, :comments] }) do count = Post.count(:limit => 2) assert_equal count, posts.size @@ -642,15 +669,17 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_scoped_and_explicit_conditions_on_the_eagers Post.send(:with_scope, :find => { :conditions => "1=1" }) do posts = authors(:david).posts.find(:all, - :eager_load => :comments, + :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", + :references => :comments, :limit => 2 ) assert_equal 2, posts.size count = Post.count( - :eager_load => [ :comments, :author ], + :include => [ :comments, :author ], :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", + :references => [:authors, :comments], :limit => 2 ) assert_equal count, posts.size @@ -658,9 +687,15 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_with_scoped_order_using_association_limiting_without_explicit_scope - posts_with_explicit_order = Post.find(:all, :conditions => 'comments.id is not null', :eager_load => :comments, :order => 'posts.id DESC', :limit => 2) + posts_with_explicit_order = Post.find( + :all, :conditions => 'comments.id is not null', :references => :comments, + :include => :comments, :order => 'posts.id DESC', :limit => 2 + ) posts_with_scoped_order = Post.send(:with_scope, :find => {:order => 'posts.id DESC'}) do - Post.find(:all, :conditions => 'comments.id is not null', :eager_load => :comments, :limit => 2) + Post.find( + :all, :conditions => 'comments.id is not null', + :references => :comments, :include => :comments, :limit => 2 + ) end assert_equal posts_with_explicit_order, posts_with_scoped_order end @@ -773,17 +808,49 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_limited_eager_with_order - assert_equal posts(:thinking, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title)', :limit => 2, :offset => 1) - assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1) + assert_equal( + posts(:thinking, :sti_comments), + Post.find( + :all, :include => [:author, :comments], :conditions => { 'authors.name' => 'David' }, + :order => 'UPPER(posts.title)', :limit => 2, :offset => 1 + ) + ) + assert_equal( + posts(:sti_post_and_comments, :sti_comments), + Post.find( + :all, :include => [:author, :comments], :conditions => { 'authors.name' => 'David' }, + :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1 + ) + ) end def test_limited_eager_with_multiple_order_columns - assert_equal posts(:thinking, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1) - assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1) + assert_equal( + posts(:thinking, :sti_comments), + Post.find( + :all, :include => [:author, :comments], :conditions => { 'authors.name' => 'David' }, + :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1 + ) + ) + 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 + ) + ) end def test_limited_eager_with_numeric_in_association - assert_equal people(:david, :susan), Person.find(:all, :eager_load => [:readers, :primary_contact, :number1_fan], :conditions => "number1_fans_people.first_name like 'M%'", :order => 'people.id', :limit => 2, :offset => 0) + assert_equal( + people(:david, :susan), + Person.find( + :all, :include => [:readers, :primary_contact, :number1_fan], + :conditions => "number1_fans_people.first_name like 'M%'", + :references => :number1_fans_people, + :order => 'people.id', :limit => 2, :offset => 0 + ) + ) end def test_preload_with_interpolation @@ -898,11 +965,11 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_count_with_include if current_adapter?(:SybaseAdapter) - assert_equal 3, assert_deprecated { authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15") } + assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15", :references => :comments) elsif current_adapter?(:OpenBaseAdapter) - assert_equal 3, assert_deprecated { authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15") } + assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15", :references => :comments) else - assert_equal 3, assert_deprecated { authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15") } + assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15", :references => :comments) end end @@ -913,11 +980,11 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_conditions_on_join_table_with_include_and_limit - assert_equal 3, assert_deprecated { Developer.find(:all, :include => 'projects', :conditions => 'developers_projects.access_level = 1', :limit => 5).size } + assert_equal 3, Developer.find(:all, :include => 'projects', :conditions => { 'developers_projects.access_level' => 1 }, :limit => 5).size end def test_order_on_join_table_with_include_and_limit - assert_equal 5, assert_deprecated { Developer.find(:all, :include => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).size } + assert_equal 5, Developer.find(:all, :include => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).size end def test_eager_loading_with_order_on_joined_table_preloads @@ -1014,9 +1081,9 @@ class EagerAssociationTest < ActiveRecord::TestCase expected = Firm.find(1).clients_using_primary_key.sort_by(&:name) # Oracle adapter truncates alias to 30 characters if current_adapter?(:OracleAdapter) - firm = Firm.find 1, :eager_load => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name' + firm = Firm.find 1, :include => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name' else - firm = Firm.find 1, :eager_load => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name' + firm = Firm.find 1, :include => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name' end assert_no_queries do assert_equal expected, firm.clients_using_primary_key @@ -1033,7 +1100,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_include_has_one_using_primary_key expected = accounts(:signals37) - firm = Firm.find(:all, :eager_load => :account_using_primary_key, :order => 'accounts.id').detect {|f| f.id == 1} + firm = Firm.find(:all, :include => :account_using_primary_key, :order => 'accounts.id').detect {|f| f.id == 1} assert_no_queries do assert_equal expected, firm.account_using_primary_key end @@ -1086,13 +1153,13 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_join_eager_with_empty_order_should_generate_valid_sql assert_nothing_raised(ActiveRecord::StatementInvalid) do - Post.eager_load(:comments).order("").where(:comments => {:body => "Thank you for the welcome"}).first + Post.includes(:comments).order("").where(:comments => {:body => "Thank you for the welcome"}).first end end def test_join_eager_with_nil_order_should_generate_valid_sql assert_nothing_raised(ActiveRecord::StatementInvalid) do - Post.eager_load(:comments).order(nil).where(:comments => {:body => "Thank you for the welcome"}).first + Post.includes(:comments).order(nil).where(:comments => {:body => "Thank you for the welcome"}).first end end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index b91d9b5659..f457dfb9b3 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -679,7 +679,13 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase end def test_join_table_alias - assert_equal 3, Developer.find(:all, :eager_load => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size + assert_equal( + 3, + Developer.find( + :all, :include => {:projects => :developers}, :references => :developers_projects_join, + :conditions => 'developers_projects_join.joined_on IS NOT NULL' + ).size + ) end def test_join_with_group @@ -689,7 +695,13 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase end Project.columns.each { |c| group << "projects.#{c.name}" } - assert_equal 3, Developer.find(:all, :eager_load => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', :group => group.join(",")).size + assert_equal( + 3, + Developer.find( + :all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', + :references => :developers_projects_join, :group => group.join(",") + ).size + ) end def test_find_grouped diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index efe92c54c6..4612bc2618 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -847,7 +847,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_preloading_empty_through_association_via_joins person = Person.create!(:first_name => "Gaga") - person = Person.where(:id => person.id).where('readers.id = 1 or 1=1').eager_load(:posts).to_a.first + person = Person.where(:id => person.id).where('readers.id = 1 or 1=1').references(:readers).includes(:posts).to_a.first assert person.posts.loaded?, 'person.posts should be loaded' assert_equal [], person.posts diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index b04c5c7b54..2503349c08 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -111,7 +111,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase def test_has_one_through_nonpreload_eagerloading members = assert_queries(1) do - Member.find(:all, :eager_load => :club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback + Member.find(:all, :include => :club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].club} @@ -119,7 +119,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase def test_has_one_through_nonpreload_eager_loading_through_polymorphic members = assert_queries(1) do - Member.find(:all, :eager_load => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback + Member.find(:all, :include => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].sponsor_club} @@ -128,7 +128,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save! members = assert_queries(1) do - Member.find(:all, :eager_load => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC') #force fallback + Member.find(:all, :include => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC') #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries { members[0].sponsor_club } diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index 4202d28061..68a1e62328 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -42,7 +42,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase end def test_join_conditions_allow_nil_associations - authors = Author.eager_load(:essays).where(:essays => {:id => nil}) + authors = Author.includes(:essays).where(:essays => {:id => nil}) assert_equal 2, authors.count end diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index 61b341eaa4..76282213d8 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -104,7 +104,7 @@ class InverseHasOneTests < ActiveRecord::TestCase f.man.name = 'Mungo' assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance" - m = Man.find(:first, :conditions => {:name => 'Gordon'}, :eager_load => :face, :order => 'faces.id') + m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :face, :order => 'faces.id') f = m.face assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' @@ -189,7 +189,7 @@ class InverseHasManyTests < ActiveRecord::TestCase assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance" end - m = Man.find(:first, :conditions => {:name => 'Gordon'}, :eager_load => :interests, :order => 'interests.id') + m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :interests, :order => 'interests.id') is = m.interests is.each do |i| assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" @@ -286,7 +286,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase m.face.description = 'pleasing' assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance" - f = Face.find(:first, :eager_load => :man, :order => 'men.id', :conditions => {:description => 'trusting'}) + f = Face.find(:first, :include => :man, :order => 'men.id', :conditions => {:description => 'trusting'}) m = f.man assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" f.description = 'gormless' @@ -369,7 +369,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase m.polymorphic_face.description = 'pleasing' assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance" - f = Face.find(:first, :conditions => {:description => 'confused'}, :eager_load => :man, :order => 'men.id') + f = Face.find(:first, :conditions => {:description => 'confused'}, :include => :man, :order => 'men.id') m = f.polymorphic_man assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance" f.description = 'gormless' diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 244d01da7d..301755249c 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -362,7 +362,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end assert_raise ActiveRecord::EagerLoadPolymorphicError do - tags(:general).taggings.eager_load(:taggable).where('bogus_table.column = 1').to_a + tags(:general).taggings.find(:all, :include => :taggable, :references => :bogus_table, :conditions => 'bogus_table.column = 1') end end @@ -419,7 +419,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end def test_eager_load_has_many_through_has_many - author = Author.where('name = ?', 'David').eager_load(:comments).order('comments.id').first + author = Author.find :first, :conditions => ['name = ?', 'David'], :include => :comments, :order => 'comments.id' SpecialComment.new; VerySpecialComment.new assert_no_queries do assert_equal [1,2,3,5,6,7,8,9,10,12], author.comments.collect(&:id) diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb index b879ac9fb8..03d99d19f6 100644 --- a/activerecord/test/cases/associations/nested_through_associations_test.rb +++ b/activerecord/test/cases/associations/nested_through_associations_test.rb @@ -505,7 +505,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase def test_nested_has_many_through_with_conditions_on_through_associations_preload_via_joins # Pointless condition to force single-query loading assert_includes_and_joins_equal( - Author.where('tags.id = tags.id'), + Author.where('tags.id = tags.id').references(:tags), [authors(:bob)], :misc_post_first_blue_tags ) end @@ -515,7 +515,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase end def test_nested_has_many_through_with_conditions_on_source_associations_preload - authors = assert_queries(2) { Author.includes(:misc_post_first_blue_tags_2).to_a.sort_by(&:id) } + authors = assert_queries(4) { Author.includes(:misc_post_first_blue_tags_2).to_a.sort_by(&:id) } blue = tags(:blue) assert_no_queries do @@ -526,7 +526,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase def test_nested_has_many_through_with_conditions_on_source_associations_preload_via_joins # Pointless condition to force single-query loading assert_includes_and_joins_equal( - Author.where('tags.id = tags.id'), + Author.where('tags.id = tags.id').references(:tags), [authors(:bob)], :misc_post_first_blue_tags_2 ) end @@ -560,7 +560,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase actual = assert_queries(1) { query.joins(association).to_a.uniq } assert_equal expected, actual - actual = assert_queries(1) { query.eager_load(association).to_a.uniq } + actual = assert_queries(1) { query.includes(association).to_a.uniq } assert_equal expected, actual end end diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index df657c1eb4..017905e0ac 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -29,7 +29,7 @@ class AssociationsTest < ActiveRecord::TestCase molecule.electrons.create(:name => 'electron_1') molecule.electrons.create(:name => 'electron_2') - liquids = Liquid.eager_load(:molecules => :electrons).where('molecules.id is not null') + liquids = Liquid.includes(:molecules => :electrons).references(:molecules).where('molecules.id is not null') assert_equal 1, liquids[0].molecules.length end @@ -129,6 +129,11 @@ class AssociationsTest < ActiveRecord::TestCase end end + def test_association_with_references + firm = companies(:first_firm) + assert_equal ['foo'], firm.association_with_references.scoped.references_values + end + end class AssociationProxyTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 3f026e310f..7c9ebf528e 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -49,11 +49,11 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_get_maximum_of_field_with_include - assert_equal 55, Account.eager_load(:firm).where("companies.name != 'Summit'").maximum(:credit_limit) + assert_equal 55, Account.maximum(:credit_limit, :include => :firm, :references => :companies, :conditions => "companies.name != 'Summit'") end def test_should_get_maximum_of_field_with_scoped_include - Account.eager_load(:firm).where("companies.name != 'Summit'").scoping do + Account.send :with_scope, :find => { :include => :firm, :references => :companies, :conditions => "companies.name != 'Summit'" } do assert_equal 55, Account.maximum(:credit_limit) end end @@ -270,7 +270,7 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_not_modify_options_when_using_includes - options = {:include => :firm} + options = {:conditions => 'companies.id > 1', :include => :firm, :references => :companies} options_copy = options.dup Account.count(:all, options) @@ -334,9 +334,7 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_perform_joined_include_when_referencing_included_tables - joined_count = assert_deprecated do - Account.includes(:firm).where(:companies => {:name => '37signals'}).count - end + joined_count = Account.includes(:firm).where(:companies => {:name => '37signals'}).count assert_equal 1, joined_count end diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb index 3ed96a3ec8..cd3d19e783 100644 --- a/activerecord/test/cases/counter_cache_test.rb +++ b/activerecord/test/cases/counter_cache_test.rb @@ -6,9 +6,11 @@ require 'models/engine' require 'models/reply' require 'models/category' require 'models/categorization' +require 'models/dog' +require 'models/dog_lover' class CounterCacheTest < ActiveRecord::TestCase - fixtures :topics, :categories, :categorizations, :cars + fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers class ::SpecialTopic < ::Topic has_many :special_replies, :foreign_key => 'parent_id' @@ -61,7 +63,7 @@ class CounterCacheTest < ActiveRecord::TestCase end end - test "reset counter should with belongs_to which has class_name" do + test "reset counter with belongs_to which has class_name" do car = cars(:honda) assert_nothing_raised do Car.reset_counters(car.id, :engines) @@ -71,6 +73,20 @@ class CounterCacheTest < ActiveRecord::TestCase end end + test "reset the right counter if two have the same class_name" do + david = dog_lovers(:david) + + DogLover.increment_counter(:bred_dogs_count, david.id) + DogLover.increment_counter(:trained_dogs_count, david.id) + + assert_difference 'david.reload.bred_dogs_count', -1 do + DogLover.reset_counters(david.id, :bred_dogs) + end + assert_difference 'david.reload.trained_dogs_count', -1 do + DogLover.reset_counters(david.id, :trained_dogs) + end + end + test "update counter with initial null value" do category = categories(:general) assert_equal 2, category.categorizations.count diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 5b882f966b..7d80a56858 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -1119,10 +1119,10 @@ class FinderTest < ActiveRecord::TestCase end def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct - assert_equal 2, Post.find(:all, :eager_load => { :authors => :author_address }, :order => ' author_addresses.id DESC ', :limit => 2).size + assert_equal 2, Post.find(:all, :include => { :authors => :author_address }, :order => 'author_addresses.id DESC ', :limit => 2).size - assert_equal 3, Post.find(:all, :eager_load => { :author => :author_address, :authors => :author_address}, - :order => ' author_addresses_authors.id DESC ', :limit => 3).size + assert_equal 3, Post.find(:all, :include => { :author => :author_address, :authors => :author_address}, + :order => 'author_addresses_authors.id DESC ', :limit => 3).size end def test_find_with_nil_inside_set_passed_for_one_attribute @@ -1149,7 +1149,10 @@ class FinderTest < ActiveRecord::TestCase end def test_with_limiting_with_custom_select - posts = Post.find(:all, :eager_load => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id') + posts = Post.find( + :all, :include => :author, :select => ' posts.*, authors.id as "author_id"', + :references => :authors, :limit => 3, :order => 'posts.id' + ) assert_equal 3, posts.size assert_equal [0, 1, 1], posts.map(&:author_id).sort end diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index 0f0621f2e0..ebf6e26385 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -103,8 +103,8 @@ class MethodScopingTest < ActiveRecord::TestCase def test_scoped_find_include # with the include, will retrieve only developers for the given project - scoped_developers = Developer.send(:with_scope, :find => { :eager_load => :projects }) do - Developer.find(:all, :conditions => 'projects.id = 2') + scoped_developers = Developer.send(:with_scope, :find => { :include => :projects }) do + Developer.find(:all, :conditions => { 'projects.id' => 2 }) end assert scoped_developers.include?(developers(:david)) assert !scoped_developers.include?(developers(:jamis)) @@ -203,8 +203,8 @@ class MethodScopingTest < ActiveRecord::TestCase def test_scoped_count_include # with the include, will retrieve only developers for the given project - Developer.send(:with_scope, :find => { :eager_load => :projects }) do - assert_equal 1, Developer.count(:conditions => 'projects.id = 2') + Developer.send(:with_scope, :find => { :include => :projects }) do + assert_equal 1, Developer.count(:conditions => { 'projects.id' => 2 }) end end @@ -268,7 +268,7 @@ class MethodScopingTest < ActiveRecord::TestCase end class NestedScopingTest < ActiveRecord::TestCase - fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects + fixtures :authors, :developers, :projects, :comments, :posts def test_merge_options Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do @@ -338,8 +338,8 @@ class NestedScopingTest < ActiveRecord::TestCase end def test_nested_scoped_find_include - Developer.send(:with_scope, :find => { :eager_load => :projects }) do - Developer.send(:with_scope, :find => { :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :include => :projects }) do + Developer.send(:with_scope, :find => { :conditions => { 'projects.id' => 2 } }) do assert_nothing_raised { Developer.find(1) } assert_equal('David', Developer.find(:first).name) end @@ -348,49 +348,25 @@ class NestedScopingTest < ActiveRecord::TestCase def test_nested_scoped_find_merged_include # :include's remain unique and don't "double up" when merging - Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :include => :projects, :conditions => { 'projects.id' => 2 } }) do Developer.send(:with_scope, :find => { :include => :projects }) do - assert_deprecated do - assert_equal 1, Developer.scoped.includes_values.uniq.length - assert_equal 'David', Developer.find(:first).name - end + assert_equal 1, Developer.scoped.includes_values.uniq.length + assert_equal 'David', Developer.find(:first).name end end # the nested scope doesn't remove the first :include - Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :include => :projects, :conditions => { 'projects.id' => 2 } }) do Developer.send(:with_scope, :find => { :include => [] }) do - assert_deprecated do - assert_equal 1, Developer.scoped.includes_values.uniq.length - assert_equal('David', Developer.find(:first).name) - end + assert_equal 1, Developer.scoped.includes_values.uniq.length + assert_equal('David', Developer.find(:first).name) end end # mixing array and symbol include's will merge correctly - Developer.send(:with_scope, :find => { :include => [:projects], :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :include => [:projects], :conditions => { 'projects.id' => 2 } }) do Developer.send(:with_scope, :find => { :include => :projects }) do - assert_deprecated do - assert_equal 1, Developer.scoped.includes_values.uniq.length - assert_equal('David', Developer.find(:first).name) - end - end - end - end - - def test_nested_scoped_find_merged_eager_load - # :include's remain unique and don't "double up" when merging - Developer.send(:with_scope, :find => { :eager_load => :projects, :conditions => "projects.id = 2" }) do - Developer.send(:with_scope, :find => { :eager_load => :projects }) do - assert_equal 1, Developer.scoped.eager_load_values.uniq.length - assert_equal 'David', Developer.find(:first).name - end - end - - # mixing array and symbol include's will merge correctly - Developer.send(:with_scope, :find => { :eager_load => [:projects], :conditions => "projects.id = 2" }) do - Developer.send(:with_scope, :find => { :eager_load => :projects }) do - assert_equal 1, Developer.scoped.eager_load_values.uniq.length + assert_equal 1, Developer.scoped.includes_values.uniq.length assert_equal('David', Developer.find(:first).name) end end diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb index 1a5ac1333e..fe53510ba2 100644 --- a/activerecord/test/cases/migration/helper.rb +++ b/activerecord/test/cases/migration/helper.rb @@ -2,6 +2,15 @@ require "cases/helper" module ActiveRecord class Migration + class << self + attr_accessor :message_count + end + + def puts(text="") + ActiveRecord::Migration.message_count ||= 0 + ActiveRecord::Migration.message_count += 1 + end + module TestHelper attr_reader :connection, :table_name diff --git a/activerecord/test/cases/migration/logger_test.rb b/activerecord/test/cases/migration/logger_test.rb index 8466562daf..ee0c20747e 100644 --- a/activerecord/test/cases/migration/logger_test.rb +++ b/activerecord/test/cases/migration/logger_test.rb @@ -3,13 +3,16 @@ require "cases/helper" module ActiveRecord class Migration class LoggerTest < ActiveRecord::TestCase + # mysql can't roll back ddl changes + self.use_transactional_fixtures = false + Migration = Struct.new(:name, :version) do def migrate direction # do nothing end end - def initialize(*args) + def setup super ActiveRecord::SchemaMigration.create_table ActiveRecord::SchemaMigration.delete_all diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 0ca3ab9807..575df2f84b 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require "cases/migration/helper" require 'bigdecimal/util' require 'models/person' @@ -16,28 +17,6 @@ class Reminder < ActiveRecord::Base; end class Thing < ActiveRecord::Base; end -class ActiveRecord::Migration - class << self - attr_accessor :message_count - end - - def puts(text="") - ActiveRecord::Migration.message_count ||= 0 - ActiveRecord::Migration.message_count += 1 - end -end - -module ActiveRecord - class MigrationTest < ActiveRecord::TestCase - attr_reader :connection - - def setup - super - @connection = Base.connection - end - end -end - class MigrationTest < ActiveRecord::TestCase self.use_transactional_fixtures = false @@ -45,6 +24,10 @@ class MigrationTest < ActiveRecord::TestCase def setup super + %w(reminders people_reminders prefix_reminders_suffix).each do |table| + Reminder.connection.drop_table(table) rescue nil + end + Reminder.reset_column_information ActiveRecord::Migration.verbose = true ActiveRecord::Migration.message_count = 0 end @@ -81,9 +64,9 @@ class MigrationTest < ActiveRecord::TestCase # using a copy as we need the drop_table method to # continue to work for the ensure block of the test temp_conn = Person.connection.dup - temp_conn.extend(Module.new { - def drop_table; raise "no"; end - }) + + assert_not_equal temp_conn, Person.connection + temp_conn.create_table :testings2, :force => true do |t| t.column :foo, :string end @@ -91,16 +74,25 @@ class MigrationTest < ActiveRecord::TestCase Person.connection.drop_table :testings2 rescue nil end - def test_add_table - assert !Reminder.table_exists? + def connection + ActiveRecord::Base.connection + end - WeNeedReminders.up + def test_migration_instance_has_connection + migration = Class.new(ActiveRecord::Migration).new + assert_equal connection, migration.connection + end - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content + def test_method_missing_delegates_to_connection + migration = Class.new(ActiveRecord::Migration) { + def connection + Class.new { + def create_table; "hi mom!"; end + }.new + end + }.new - WeNeedReminders.down - assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } + assert_equal "hi mom!", migration.method_missing(:create_table) end def test_add_table_with_decimals @@ -164,26 +156,6 @@ class MigrationTest < ActiveRecord::TestCase assert_raise(ActiveRecord::StatementInvalid) { BigNumber.find(:first) } end - def test_migrator - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid") - - assert_equal 3, ActiveRecord::Migrator.current_version - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content - - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid") - - assert_equal 0, ActiveRecord::Migrator.current_version - Person.reset_column_information - assert !Person.column_methods_hash.include?(:last_name) - assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } - end - def test_filtering_migrations assert !Person.column_methods_hash.include?(:last_name) assert !Reminder.table_exists? @@ -240,55 +212,6 @@ class MigrationTest < ActiveRecord::TestCase assert migration.went_down, 'have not gone down' end - def test_migrator_one_up - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 2) - - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content - end - - def test_migrator_one_down - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid") - - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 1) - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - end - - def test_migrator_one_up_one_down - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) - - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - end - - def test_migrator_double_up - assert_equal(0, ActiveRecord::Migrator.current_version) - ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) - assert_nothing_raised { ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) } - assert_equal(1, ActiveRecord::Migrator.current_version) - end - - def test_migrator_double_down - assert_equal(0, ActiveRecord::Migrator.current_version) - ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) - ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) - assert_nothing_raised { ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) } - assert_equal(0, ActiveRecord::Migrator.current_version) - end - def test_migrator_one_up_with_exception_and_rollback unless ActiveRecord::Base.connection.supports_ddl_transactions? skip "not supported on #{ActiveRecord::Base.connection.class}" @@ -310,117 +233,6 @@ class MigrationTest < ActiveRecord::TestCase refute Person.column_methods_hash.include?(:last_name) end - def test_only_loads_pending_migrations - # migrate up to 1 - ActiveRecord::SchemaMigration.create!(:version => '1') - - proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", nil) - - names = proxies.map(&:name) - assert !names.include?('ValidPeopleHaveLastNames') - assert names.include?('WeNeedReminders') - assert names.include?('InnocentJointable') - end - - def test_target_version_zero_should_run_only_once - # migrate up to 1 - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) - - # migrate down to 0 - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) - - # migrate down to 0 again - proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) - assert_equal [], proxies - end - - def test_migrator_db_has_no_schema_migrations_table - # Oracle adapter raises error if semicolon is present as last character - if current_adapter?(:OracleAdapter) - ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations") - else - ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations;") - end - assert_nothing_raised do - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) - end - end - - def test_migrator_verbosity - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - assert_not_equal 0, ActiveRecord::Migration.message_count - ActiveRecord::Migration.message_count = 0 - - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) - assert_not_equal 0, ActiveRecord::Migration.message_count - ActiveRecord::Migration.message_count = 0 - end - - def test_migrator_verbosity_off - ActiveRecord::Migration.verbose = false - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - assert_equal 0, ActiveRecord::Migration.message_count - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) - assert_equal 0, ActiveRecord::Migration.message_count - end - - def test_migrator_going_down_due_to_version_target - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) - - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content - end - - def test_migrator_rollback - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") - assert_equal(3, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(2, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(1, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(0, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(0, ActiveRecord::Migrator.current_version) - end - - def test_migrator_forward - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) - assert_equal(1, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid", 2) - assert_equal(3, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid") - assert_equal(3, ActiveRecord::Migrator.current_version) - end - - def test_get_all_versions - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") - assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal([1,2], ActiveRecord::Migrator.get_all_versions) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal([1], ActiveRecord::Migrator.get_all_versions) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal([], ActiveRecord::Migrator.get_all_versions) - end - def test_schema_migrations_table_name ActiveRecord::Base.table_name_prefix = "prefix_" ActiveRecord::Base.table_name_suffix = "_suffix" diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index 143aadd833..1e16addcf3 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -1,13 +1,16 @@ require "cases/helper" +require "cases/migration/helper" module ActiveRecord class MigratorTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + # Use this class to sense if migrations have gone # up or down. class Sensor < ActiveRecord::Migration attr_reader :went_up, :went_down - def initialize name, version + def initialize name = self.class.name, version = nil super @went_up = false @went_down = false @@ -129,5 +132,246 @@ module ActiveRecord refute pass_three[1].went_down assert pass_three[2].went_down end + + def test_up_calls_up + migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] + ActiveRecord::Migrator.new(:up, migrations).migrate + assert migrations.all? { |m| m.went_up } + assert migrations.all? { |m| !m.went_down } + assert_equal 2, ActiveRecord::Migrator.current_version + end + + def test_down_calls_down + test_up_calls_up + + migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] + ActiveRecord::Migrator.new(:down, migrations).migrate + assert migrations.all? { |m| !m.went_up } + assert migrations.all? { |m| m.went_down } + assert_equal 0, ActiveRecord::Migrator.current_version + end + + def test_current_version + ActiveRecord::SchemaMigration.create!(:version => '1000') + assert_equal 1000, ActiveRecord::Migrator.current_version + end + + def test_migrator_one_up + calls, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:up, migrations, 2).migrate + assert_equal [[:up, 2]], calls + end + + def test_migrator_one_down + calls, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations).migrate + assert_equal [[:up, 1], [:up, 2], [:up, 3]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 1).migrate + + assert_equal [[:down, 3], [:down, 2]], calls + end + + def test_migrator_one_up_one_down + calls, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal [[:down, 1]], calls + end + + def test_migrator_double_up + calls, migrations = sensors(3) + assert_equal(0, ActiveRecord::Migrator.current_version) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [], calls + end + + def test_migrator_double_down + calls, migrations = sensors(3) + + assert_equal(0, ActiveRecord::Migrator.current_version) + + ActiveRecord::Migrator.new(:up, migrations, 1).run + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 1).run + assert_equal [[:down, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 1).run + assert_equal [], calls + + assert_equal(0, ActiveRecord::Migrator.current_version) + end + + def test_migrator_verbosity + _, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_not_equal 0, ActiveRecord::Migration.message_count + + ActiveRecord::Migration.message_count = 0 + + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_not_equal 0, ActiveRecord::Migration.message_count + ActiveRecord::Migration.message_count = 0 + end + + def test_migrator_verbosity_off + _, migrations = sensors(3) + + ActiveRecord::Migration.message_count = 0 + ActiveRecord::Migration.verbose = false + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal 0, ActiveRecord::Migration.message_count + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal 0, ActiveRecord::Migration.message_count + end + + def test_target_version_zero_should_run_only_once + calls, migrations = sensors(3) + + # migrate up to 1 + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + # migrate down to 0 + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal [[:down, 1]], calls + calls.clear + + # migrate down to 0 again + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal [], calls + end + + def test_migrator_going_down_due_to_version_target + calls, migrator = migrator_class(3) + + migrator.up("valid", 1) + assert_equal [[:up, 1]], calls + calls.clear + + migrator.migrate("valid", 0) + assert_equal [[:down, 1]], calls + calls.clear + + migrator.migrate("valid") + assert_equal [[:up, 1], [:up, 2], [:up, 3]], calls + end + + def test_migrator_rollback + _, migrator = migrator_class(3) + + migrator.migrate("valid") + assert_equal(3, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(2, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(1, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(0, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(0, ActiveRecord::Migrator.current_version) + end + + def test_migrator_db_has_no_schema_migrations_table + _, migrator = migrator_class(3) + + ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations") + refute ActiveRecord::Base.connection.table_exists?('schema_migrations') + migrator.migrate("valid", 1) + assert ActiveRecord::Base.connection.table_exists?('schema_migrations') + end + + def test_migrator_forward + _, migrator = migrator_class(3) + migrator.migrate("/valid", 1) + assert_equal(1, ActiveRecord::Migrator.current_version) + + migrator.forward("/valid", 2) + assert_equal(3, ActiveRecord::Migrator.current_version) + + migrator.forward("/valid") + assert_equal(3, ActiveRecord::Migrator.current_version) + end + + def test_only_loads_pending_migrations + # migrate up to 1 + ActiveRecord::SchemaMigration.create!(:version => '1') + + calls, migrator = migrator_class(3) + migrator.migrate("valid", nil) + + assert_equal [[:up, 2], [:up, 3]], calls + end + + def test_get_all_versions + _, migrator = migrator_class(3) + + migrator.migrate("valid") + assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions) + + migrator.rollback("valid") + assert_equal([1,2], ActiveRecord::Migrator.get_all_versions) + + migrator.rollback("valid") + assert_equal([1], ActiveRecord::Migrator.get_all_versions) + + migrator.rollback("valid") + assert_equal([], ActiveRecord::Migrator.get_all_versions) + end + + private + def m(name, version, &block) + x = Sensor.new name, version + x.extend(Module.new { + define_method(:up) { block.call(:up, x); super() } + define_method(:down) { block.call(:down, x); super() } + }) if block_given? + end + + def sensors(count) + calls = [] + migrations = count.times.map { |i| + m(nil, i + 1) { |c,migration| + calls << [c, migration.version] + } + } + [calls, migrations] + end + + def migrator_class(count) + calls, migrations = sensors(count) + + migrator = Class.new(Migrator).extend(Module.new { + define_method(:migrations) { |paths| + migrations + } + }) + [calls, migrator] + end end end diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index 72d96f2bab..f7a5d05582 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -72,7 +72,7 @@ class ModulesTest < ActiveRecord::TestCase clients = [] assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do - clients << MyApplication::Business::Client.find(3, :eager_load => {:firm => :account}, :conditions => 'accounts.id IS NOT NULL') + clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}, :conditions => 'accounts.id IS NOT NULL', :references => :accounts) clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}) end diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 7fd15027eb..297fb56570 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -189,8 +189,8 @@ class ReflectionTest < ActiveRecord::TestCase def test_reflection_of_all_associations # FIXME these assertions bust a lot - assert_equal 37, Firm.reflect_on_all_associations.size - assert_equal 27, Firm.reflect_on_all_associations(:has_many).size + assert_equal 38, Firm.reflect_on_all_associations.size + assert_equal 28, Firm.reflect_on_all_associations(:has_many).size assert_equal 10, Firm.reflect_on_all_associations(:has_one).size assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size end diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 52dfea8fac..edf38cb7a3 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -105,8 +105,8 @@ class RelationScopingTest < ActiveRecord::TestCase def test_scoped_find_include # with the include, will retrieve only developers for the given project - scoped_developers = Developer.eager_load(:projects).scoping do - Developer.where('projects.id = 2').all + scoped_developers = Developer.includes(:projects).scoping do + Developer.where('projects.id' => 2).all end assert scoped_developers.include?(developers(:david)) assert !scoped_developers.include?(developers(:jamis)) @@ -528,7 +528,7 @@ class DefaultScopingTest < ActiveRecord::TestCase d = DeveloperWithIncludes.create! d.audit_logs.create! :message => 'foo' - assert_equal 1, DeveloperWithIncludes.eager_load(:audit_logs).where(:audit_logs => { :message => 'foo' }).count + assert_equal 1, DeveloperWithIncludes.where(:audit_logs => { :message => 'foo' }).count end def test_default_scope_is_threadsafe diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index e9a3b0419c..ac6dee3c6a 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -44,7 +44,7 @@ module ActiveRecord end def test_multi_value_methods - assert_equal [:select, :group, :order, :joins, :where, :having, :bind].map(&:to_s).sort, + assert_equal [:select, :group, :order, :joins, :where, :having, :bind, :references].map(&:to_s).sort, Relation::MULTI_VALUE_METHODS.map(&:to_s).sort end @@ -136,10 +136,23 @@ module ActiveRecord assert relation.eager_loading? end - def test_apply_finder_options_supports_eager_load + def test_references_values relation = Relation.new :a, :b - relation = relation.apply_finder_options(:eager_load => :b) - assert_equal [:b], relation.eager_load_values + assert_equal [], relation.references_values + relation = relation.references(:foo).references(:omg, :lol) + assert_equal ['foo', 'omg', 'lol'], relation.references_values + end + + def test_references_values_dont_duplicate + relation = Relation.new :a, :b + relation = relation.references(:foo).references(:foo) + assert_equal ['foo'], relation.references_values + end + + def test_apply_finder_options_takes_references + relation = Relation.new :a, :b + relation = relation.apply_finder_options(:references => :foo) + assert_equal ['foo'], relation.references_values end end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index f1a9f3e0a1..5e19465253 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -16,6 +16,7 @@ require 'models/engine' require 'models/tyre' require 'models/minivan' + class RelationTest < ActiveRecord::TestCase fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments, :tags, :taggings, :cars, :minivans @@ -176,19 +177,19 @@ class RelationTest < ActiveRecord::TestCase end def test_finding_with_cross_table_order_and_limit - tags = Tag.eager_load(:taggings). + tags = Tag.includes(:taggings). order("tags.name asc", "taggings.taggable_id asc", "REPLACE('abc', taggings.taggable_type, taggings.taggable_type)"). limit(1).to_a assert_equal 1, tags.length end def test_finding_with_complex_order_and_limit - tags = Tag.eager_load(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a + tags = Tag.includes(:taggings).references(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a assert_equal 1, tags.length end def test_finding_with_complex_order - tags = Tag.eager_load(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").to_a + tags = Tag.includes(:taggings).references(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").to_a assert_equal 3, tags.length end @@ -1166,18 +1167,48 @@ class RelationTest < ActiveRecord::TestCase assert_equal ['Foo', 'Foo'], query.uniq(true).uniq(false).map(&:name) end - def test_deprecated_references_eager_loaded_tables - expected = tags(:general) - tagging = taggings(:welcome_general) - tag = assert_queries 1 do - assert_deprecated do - Tag.includes(:taggings).where(:taggings => { :id => tagging.id }).to_a.first - end - end + def test_references_triggers_eager_loading + scope = Post.includes(:comments) + assert !scope.eager_loading? + assert scope.references(:comments).eager_loading? + end - assert_equal expected, tag - assert_no_queries do - tag.taggings.to_a - end + def test_references_doesnt_trigger_eager_loading_if_reference_not_included + scope = Post.references(:comments) + assert !scope.eager_loading? + end + + def test_automatically_added_where_references + scope = Post.where(:comments => { :body => "Bla" }) + assert_equal ['comments'], scope.references_values + + scope = Post.where('comments.body' => 'Bla') + assert_equal ['comments'], scope.references_values + end + + def test_automatically_added_having_references + scope = Post.having(:comments => { :body => "Bla" }) + assert_equal ['comments'], scope.references_values + + scope = Post.having('comments.body' => 'Bla') + assert_equal ['comments'], scope.references_values + end + + def test_automatically_added_order_references + scope = Post.order('comments.body') + assert_equal ['comments'], scope.references_values + + scope = Post.order('comments.body', 'yaks.body') + assert_equal ['comments', 'yaks'], scope.references_values + + # Don't infer yaks, let's not go down that road again... + scope = Post.order('comments.body, yaks.body') + assert_equal ['comments'], scope.references_values + + scope = Post.order('comments.body asc') + assert_equal ['comments'], scope.references_values + + scope = Post.order('foo(comments.body)') + assert_equal [], scope.references_values end end diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb index f155b9bc40..c72b7b35cd 100644 --- a/activerecord/test/cases/validations/association_validation_test.rb +++ b/activerecord/test/cases/validations/association_validation_test.rb @@ -118,4 +118,21 @@ class AssociationValidationTest < ActiveRecord::TestCase end end + def test_validates_associated_models_in_the_same_context + Topic.validates_presence_of :title, :on => :custom_context + Topic.validates_associated :replies + Reply.validates_presence_of :title, :on => :custom_context + + t = Topic.new('title' => '') + r = t.replies.new('title' => '') + + assert t.valid? + assert !t.valid?(:custom_context) + + t.title = "Longer" + assert !t.valid?(:custom_context), "Should NOT be valid if the associated object is not valid in the same context." + + r.title = "Longer" + assert t.valid?(:custom_context), "Should be valid if the associated object is not valid in the same context." + end end diff --git a/activerecord/test/fixtures/dog_lovers.yml b/activerecord/test/fixtures/dog_lovers.yml new file mode 100644 index 0000000000..d3e5e4a1aa --- /dev/null +++ b/activerecord/test/fixtures/dog_lovers.yml @@ -0,0 +1,4 @@ +david: + id: 1 + bred_dogs_count: 0 + trained_dogs_count: 1 diff --git a/activerecord/test/fixtures/dogs.yml b/activerecord/test/fixtures/dogs.yml new file mode 100644 index 0000000000..16d19be2c5 --- /dev/null +++ b/activerecord/test/fixtures/dogs.yml @@ -0,0 +1,3 @@ +sophie: + id: 1 + trainer_id: 1 diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index 881e387c8f..d50e11d6c9 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -3,7 +3,7 @@ class Author < ActiveRecord::Base has_many :very_special_comments, :through => :posts has_many :posts_with_comments, :include => :comments, :class_name => "Post" has_many :popular_grouped_posts, :include => :comments, :class_name => "Post", :group => "type", :having => "SUM(comments_count) > 1", :select => "type" - has_many :posts_with_comments_sorted_by_comment_id, :eager_load => :comments, :class_name => "Post", :order => 'comments.id' + has_many :posts_with_comments_sorted_by_comment_id, :include => :comments, :class_name => "Post", :order => 'comments.id' has_many :posts_sorted_by_id_limited, :class_name => "Post", :order => 'posts.id', :limit => 1 has_many :posts_with_categories, :include => :categories, :class_name => "Post" has_many :posts_with_comments_and_categories, :include => [ :comments, :categories ], :order => "posts.id", :class_name => "Post" @@ -49,12 +49,12 @@ class Author < ActiveRecord::Base has_many :sti_post_comments, :through => :sti_posts, :source => :comments has_many :special_nonexistant_posts, :class_name => "SpecialPost", :conditions => "posts.body = 'nonexistant'" - has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => "comments.post_id = 0" + has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => { 'comments.post_id' => 0 } has_many :nonexistant_comments, :through => :posts has_many :hello_posts, :class_name => "Post", :conditions => "posts.body = 'hello'" has_many :hello_post_comments, :through => :hello_posts, :source => :comments - has_many :posts_with_no_comments, :class_name => 'Post', :conditions => 'comments.id is null', :eager_load => :comments + has_many :posts_with_no_comments, :class_name => 'Post', :conditions => { 'comments.id' => nil }, :include => :comments has_many :hello_posts_with_hash_conditions, :class_name => "Post", :conditions => {:body => 'hello'} diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb index 3cd63f0660..02b85fd38a 100644 --- a/activerecord/test/models/category.rb +++ b/activerecord/test/models/category.rb @@ -2,7 +2,7 @@ class Category < ActiveRecord::Base has_and_belongs_to_many :posts has_and_belongs_to_many :special_posts, :class_name => "Post" has_and_belongs_to_many :other_posts, :class_name => "Post" - has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, :class_name => "Post", :eager_load => :authors, :order => "authors.id" + has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, :class_name => "Post", :include => :authors, :order => "authors.id" has_and_belongs_to_many(:select_testing_posts, :class_name => 'Post', diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index fe9c465c81..d1a8a82786 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -88,6 +88,8 @@ class Firm < Company has_many :accounts has_many :unautosaved_accounts, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false + has_many :association_with_references, :class_name => 'Client', :references => :foo + def log @log ||= [] end diff --git a/activerecord/test/models/dog.rb b/activerecord/test/models/dog.rb new file mode 100644 index 0000000000..72b7d33a86 --- /dev/null +++ b/activerecord/test/models/dog.rb @@ -0,0 +1,4 @@ +class Dog < ActiveRecord::Base + belongs_to :breeder, :class_name => "DogLover", :counter_cache => :bred_dogs_count + belongs_to :trainer, :class_name => "DogLover", :counter_cache => :trained_dogs_count +end diff --git a/activerecord/test/models/dog_lover.rb b/activerecord/test/models/dog_lover.rb new file mode 100644 index 0000000000..a33dc575c5 --- /dev/null +++ b/activerecord/test/models/dog_lover.rb @@ -0,0 +1,4 @@ +class DogLover < ActiveRecord::Base + has_many :trained_dogs, :class_name => "Dog", :foreign_key => :trainer_id + has_many :bred_dogs, :class_name => "Dog", :foreign_key => :breeder_id +end diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index 5792b4705b..d2a0c6b40c 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -3,13 +3,14 @@ class Person < ActiveRecord::Base has_one :reader has_many :posts, :through => :readers - has_many :posts_with_no_comments, :through => :readers, :source => :post, :eager_load => :comments, :conditions => 'comments.id is null' + has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments, + :conditions => 'comments.id is null', :references => :comments has_many :references has_many :bad_references has_many :fixed_bad_references, :conditions => { :favourite => true }, :class_name => 'BadReference' has_one :favourite_reference, :class_name => 'Reference', :conditions => ['favourite=?', true] - has_many :posts_with_comments_sorted_by_comment_id, :through => :readers, :source => :post, :eager_load => :comments, :order => 'comments.id' + has_many :posts_with_comments_sorted_by_comment_id, :through => :readers, :source => :post, :include => :comments, :order => 'comments.id' has_many :jobs, :through => :references has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 11378c12e5..e2cd7ce9e4 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -213,6 +213,16 @@ ActiveRecord::Schema.define do t.integer :access_level, :default => 1 end + create_table :dog_lovers, :force => true do |t| + t.integer :trained_dogs_count, :default => 0 + t.integer :bred_dogs_count, :default => 0 + end + + create_table :dogs, :force => true do |t| + t.integer :trainer_id + t.integer :breeder_id + end + create_table :edges, :force => true, :id => false do |t| t.column :source_id, :integer, :null => false t.column :sink_id, :integer, :null => false |