From 1f2738261f3c3c061540bb20e3a1edec96b76034 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 15 Mar 2010 13:56:19 -0700 Subject: Hack to keep column metadata queries out of test query counts --- activerecord/test/cases/dirty_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord') diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index 4961d12a44..a64ccb2120 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -26,6 +26,11 @@ class NumericData < ActiveRecord::Base end class DirtyTest < ActiveRecord::TestCase + # Dummy to force column loads so query counts are clean. + def setup + Person.create :first_name => 'foo' + end + def test_attribute_changes # New record - no changes. pirate = Pirate.new -- cgit v1.2.3 From 1def14309f32cc1c7d66b8625754ba2827410c96 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 15 Mar 2010 18:09:33 -0700 Subject: cleaning up a bunch of parse time warnings in AR [#4186 state:resolved] Signed-off-by: wycats --- activerecord/test/cases/associations/eager_test.rb | 2 +- .../associations/has_many_through_associations_test.rb | 4 ++-- .../cases/associations/inner_join_association_test.rb | 4 ++-- activerecord/test/cases/base_test.rb | 18 +++++++++--------- activerecord/test/cases/defaults_test.rb | 4 ++-- activerecord/test/cases/log_subscriber_test.rb | 10 +++++----- activerecord/test/cases/method_scoping_test.rb | 2 +- activerecord/test/cases/migration_test.rb | 4 ++-- activerecord/test/cases/named_scope_test.rb | 4 ++-- 9 files changed, 26 insertions(+), 26 deletions(-) (limited to 'activerecord') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index ffa6d45948..42a891bc3b 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -805,7 +805,7 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_include_has_many_using_primary_key - expected = Firm.find(1).clients_using_primary_key.sort_by &:name + 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, :include => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name' 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 d47c8bba7d..ff799191c2 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -291,7 +291,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase ], log.last(2) post.people_with_callbacks = [people(:michael),people(:david), Person.new(:first_name => "Julian"), Person.create!(:first_name => "Roger")] - assert_equal (%w(Ted Bob Sam Lary) * 2).sort, log[-12..-5].collect(&:last).sort + assert_equal((%w(Ted Bob Sam Lary) * 2).sort, log[-12..-5].collect(&:last).sort) assert_equal [ [:added, :before, "Julian"], [:added, :after, "Julian"], @@ -300,7 +300,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase ], log.last(4) post.people_with_callbacks.clear - assert_equal (%w(Michael David Julian Roger) * 2).sort, log.last(8).collect(&:last).sort + assert_equal((%w(Michael David Julian Roger) * 2).sort, log.last(8).collect(&:last).sort) end def test_dynamic_find_should_respect_association_include diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index 43abcae75e..4ba867dc7c 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -15,12 +15,12 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase def test_construct_finder_sql_ignores_empty_joins_hash sql = Author.joins({}).to_sql - assert_no_match /JOIN/i, sql + assert_no_match(/JOIN/i, sql) end def test_construct_finder_sql_ignores_empty_joins_array sql = Author.joins([]).to_sql - assert_no_match /JOIN/i, sql + assert_no_match(/JOIN/i, sql) end def test_find_with_implicit_inner_joins_honors_readonly_without_select diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index e3047fe873..8774ed58aa 100755 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -674,10 +674,10 @@ class BasicsTest < ActiveRecord::TestCase def test_decrement_counter Topic.decrement_counter("replies_count", 2) - assert_equal -1, Topic.find(2).replies_count + assert_equal(-1, Topic.find(2).replies_count) Topic.decrement_counter("replies_count", 2) - assert_equal -2, Topic.find(2).replies_count + assert_equal(-2, Topic.find(2).replies_count) end def test_reset_counters @@ -1533,7 +1533,7 @@ class BasicsTest < ActiveRecord::TestCase def test_auto_id auto = AutoId.new auto.save - assert (auto.id > 0) + assert(auto.id > 0) end def quote_column_name(name) @@ -2181,7 +2181,7 @@ class BasicsTest < ActiveRecord::TestCase end def test_inspect_new_instance - assert_match /Topic id: nil/, Topic.new.inspect + assert_match(/Topic id: nil/, Topic.new.inspect) end def test_inspect_limited_select_instance @@ -2240,9 +2240,9 @@ class BasicsTest < ActiveRecord::TestCase ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count } ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count } ActiveRecord::Base.benchmark("Error Topic Count", :level => :error) { Topic.count } - assert_no_match /Debug Topic Count/, log.string - assert_match /Warn Topic Count/, log.string - assert_match /Error Topic Count/, log.string + assert_no_match(/Debug Topic Count/, log.string) + assert_match(/Warn Topic Count/, log.string) + assert_match(/Error Topic Count/, log.string) ensure ActiveRecord::Base.logger = original_logger end @@ -2253,8 +2253,8 @@ class BasicsTest < ActiveRecord::TestCase ActiveRecord::Base.logger = Logger.new(log) ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => true) { ActiveRecord::Base.logger.debug "Loud" } ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" } - assert_no_match /Loud/, log.string - assert_match /Quiet/, log.string + assert_no_match(/Loud/, log.string) + assert_match(/Quiet/, log.string) ensure ActiveRecord::Base.logger = original_logger end diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index b4032c23e6..bba216ae19 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -24,7 +24,7 @@ class DefaultTest < ActiveRecord::TestCase assert_instance_of Fixnum, default.positive_integer assert_equal 1, default.positive_integer assert_instance_of Fixnum, default.negative_integer - assert_equal -1, default.negative_integer + assert_equal(-1, default.negative_integer) assert_instance_of BigDecimal, default.decimal_number assert_equal BigDecimal.new("2.78"), default.decimal_number end @@ -33,7 +33,7 @@ class DefaultTest < ActiveRecord::TestCase if current_adapter?(:PostgreSQLAdapter) def test_multiline_default_text # older postgres versions represent the default with escapes ("\\012" for a newline) - assert ( "--- []\n\n" == Default.columns_hash['multiline_default'].default || + assert( "--- []\n\n" == Default.columns_hash['multiline_default'].default || "--- []\\012\\012" == Default.columns_hash['multiline_default'].default) end end diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index f3b94eb829..6ba84fa57b 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -26,8 +26,8 @@ class LogSubscriberTest < ActiveSupport::TestCase Developer.all wait assert_equal 1, @logger.logged(:debug).size - assert_match /Developer Load/, @logger.logged(:debug).last - assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last + assert_match(/Developer Load/, @logger.logged(:debug).last) + assert_match(/SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last) end def test_cached_queries @@ -37,7 +37,7 @@ class LogSubscriberTest < ActiveSupport::TestCase end wait assert_equal 2, @logger.logged(:debug).size - assert_match /CACHE/, @logger.logged(:debug).last - assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last + assert_match(/CACHE/, @logger.logged(:debug).last) + assert_match(/SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last) end -end \ No newline at end of file +end diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index 3151457440..a3b496a0e6 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -382,7 +382,7 @@ class NestedScopingTest < ActiveRecord::TestCase Developer.send(:with_scope, :find => { :conditions => "salary < 100000" }) do Developer.send(:with_scope, :find => { :offset => 1, :order => 'id asc' }) do # Oracle adapter does not generated space after asc therefore trailing space removed from regex - assert_sql /ORDER BY id asc/ do + assert_sql(/ORDER BY id asc/) do assert_equal(poor_jamis, Developer.find(:first, :order => 'id asc')) end end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index dd32eeeff2..3181f27bc2 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -477,7 +477,7 @@ if ActiveRecord::Base.connection.supports_migrations? assert_not_equal "Z", bob.moment_of_truth.zone # US/Eastern is -5 hours from GMT assert_equal Rational(-5, 24), bob.moment_of_truth.offset - assert_match /\A-05:?00\Z/, bob.moment_of_truth.zone #ruby 1.8.6 uses HH:MM, prior versions use HHMM + assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM assert_equal DateTime::ITALY, bob.moment_of_truth.start end end @@ -493,7 +493,7 @@ if ActiveRecord::Base.connection.supports_migrations? ActiveRecord::Migration.add_column :people, :intelligence_quotient, :tinyint Person.reset_column_information - assert_match /tinyint/, Person.columns_hash['intelligence_quotient'].sql_type + assert_match(/tinyint/, Person.columns_hash['intelligence_quotient'].sql_type) ensure ActiveRecord::Migration.remove_column :people, :intelligence_quotient rescue nil end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 894d96346e..6c2b4fa3a7 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -83,8 +83,8 @@ class NamedScopeTest < ActiveRecord::TestCase end def test_scopes_are_composable - assert_equal (approved = Topic.find(:all, :conditions => {:approved => true})), Topic.approved - assert_equal (replied = Topic.find(:all, :conditions => 'replies_count > 0')), Topic.replied + assert_equal((approved = Topic.find(:all, :conditions => {:approved => true})), Topic.approved) + assert_equal((replied = Topic.find(:all, :conditions => 'replies_count > 0')), Topic.replied) assert !(approved == replied) assert !(approved & replied).empty? -- cgit v1.2.3 From dcf1441c0f8c405b1d44cce2e0fbf86a2396dcf1 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 15 Mar 2010 18:33:20 -0700 Subject: removing dead code from activerecord tests. [#4187 state:resolved] Signed-off-by: wycats --- .../cases/associations/has_one_associations_test.rb | 9 --------- .../test/cases/associations/join_model_test.rb | 12 ------------ activerecord/test/cases/reflection_test.rb | 6 ------ .../test/cases/validations/i18n_validation_test.rb | 19 ------------------- 4 files changed, 46 deletions(-) (limited to 'activerecord') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index d5dbb88886..7372f2da1b 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -186,15 +186,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal account, firm.account end - def test_failing_build_association - firm = Firm.new("name" => "GlobalMegaCorp") - firm.save - - account = firm.build_account - assert !account.save - assert_equal ["can't be empty"], account.errors["credit_limit"] - end - def test_build_association_twice_without_saving_affects_nothing count_of_account = Account.count firm = Firm.find(:first) diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index e9af5a60d8..8bdf8bcd55 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -52,18 +52,6 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase assert_equal 1, authors(:mary).unique_categorized_posts.find_all_by_title("So I was thinking").size end - def test_polymorphic_has_many - assert posts(:welcome).taggings.include?(taggings(:welcome_general)) - end - - def test_polymorphic_has_one - assert_equal taggings(:welcome_general), posts(:welcome).tagging - end - - def test_polymorphic_belongs_to - assert_equal posts(:welcome), posts(:welcome).taggings.first.taggable - end - def test_polymorphic_has_many_going_through_join_model assert_equal tags(:general), tag = posts(:welcome).tags.first assert_no_queries do diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 2c9158aa7b..67818622d7 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -22,12 +22,6 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal "Subscriber", Subscriber.model_name.human end - def test_column_null_not_null - subscriber = Subscriber.find(:first) - assert subscriber.column_for_attribute("name").null - assert !subscriber.column_for_attribute("nick").null - end - def test_read_attribute_names assert_equal( %w( id title author_name author_email_address bonus_time written_on last_read content approved replies_count parent_id parent_title type ).sort, diff --git a/activerecord/test/cases/validations/i18n_validation_test.rb b/activerecord/test/cases/validations/i18n_validation_test.rb index a0ff35f948..38fa2b821d 100644 --- a/activerecord/test/cases/validations/i18n_validation_test.rb +++ b/activerecord/test/cases/validations/i18n_validation_test.rb @@ -47,25 +47,6 @@ class I18nValidationTest < ActiveRecord::TestCase @topic.valid? end - # validates_uniqueness_of w/o mocha - - def test_validates_associated_finds_custom_model_key_translation - I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:taken => 'custom message'}}}}}} - I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:taken => 'global message'}}} - - Topic.validates_uniqueness_of :title - unique_topic.valid? - assert_equal ['custom message'], unique_topic.errors[:replies] - end - - def test_validates_associated_finds_global_default_translation - I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:taken => 'global message'}}} - - Topic.validates_uniqueness_of :title - unique_topic.valid? - assert_equal ['global message'], unique_topic.errors[:replies] - end - # validates_associated w/ mocha def test_validates_associated_generates_message -- cgit v1.2.3 From 8c3e46c093023f9430c9772e81d58c9ee24de229 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 16 Mar 2010 11:26:19 -0700 Subject: clean up more warnings, remove unnecessary methods, fix eval line numbers. [#4193 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/associations/has_many_association.rb | 4 ++++ activerecord/lib/active_record/attribute_methods/dirty.rb | 2 +- activerecord/lib/active_record/base.rb | 4 ++++ activerecord/lib/active_record/nested_attributes.rb | 4 ++-- 4 files changed, 11 insertions(+), 3 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 146a6ca55f..0464e8ceea 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -5,6 +5,10 @@ module ActiveRecord # If the association has a :through option further specialization # is provided by its child HasManyThroughAssociation. class HasManyAssociation < AssociationCollection #:nodoc: + def initialize(owner, reflection) + @finder_sql = nil + super + end protected def owner_quoted_id if @reflection.options[:primary_key] diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 4a3ab9ea82..64e761e7a4 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -34,7 +34,7 @@ module ActiveRecord # reload the record and clears changed attributes. def reload_with_dirty(*args) #:nodoc: reload_without_dirty(*args).tap do - previously_changed_attributes.clear + @previously_changed.clear changed_attributes.clear end end diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 1488d9f967..3d4172f368 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1045,6 +1045,8 @@ module ActiveRecord #:nodoc: object.instance_variable_set(:@readonly, false) object.instance_variable_set(:@destroyed, false) object.instance_variable_set(:@marked_for_destruction, false) + object.instance_variable_set(:@previously_changed, {}) + object.instance_variable_set(:@changed_attributes, {}) object.send(:_run_find_callbacks) object.send(:_run_initialize_callbacks) @@ -1513,6 +1515,8 @@ module ActiveRecord #:nodoc: @readonly = false @destroyed = false @marked_for_destruction = false + @previously_changed = {} + @changed_attributes = {} ensure_proper_type diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index d8fae495e7..bc491c367f 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -243,11 +243,11 @@ module ActiveRecord # def pirate_attributes=(attributes) # assign_nested_attributes_for_one_to_one_association(:pirate, attributes) # end - class_eval %{ + class_eval <<-eoruby, __FILE__, __LINE__ + 1 def #{association_name}_attributes=(attributes) assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes) end - }, __FILE__, __LINE__ + eoruby else raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?" end -- cgit v1.2.3 From df735cf5b712312a161d703f2606b145ea2d3b85 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 16 Mar 2010 15:08:38 -0700 Subject: fisting uninitialized ivar warnings. [#4198 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/aggregations.rb | 5 +++++ .../lib/active_record/associations/association_proxy.rb | 1 + .../lib/active_record/attribute_methods/dirty.rb | 16 ++++++++-------- 3 files changed, 14 insertions(+), 8 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb index 9ecf231a66..08389907ef 100644 --- a/activerecord/lib/active_record/aggregations.rb +++ b/activerecord/lib/active_record/aggregations.rb @@ -213,6 +213,11 @@ module ActiveRecord module_eval do define_method(name) do |*args| force_reload = args.first || false + + unless instance_variable_defined?("@#{name}") + instance_variable_set("@#{name}", nil) + end + if (instance_variable_get("@#{name}").nil? || force_reload) && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? }) attrs = mapping.collect {|pair| read_attribute(pair.first)} object = case constructor diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb index 0ff89df1e3..4fb1df3ab9 100644 --- a/activerecord/lib/active_record/associations/association_proxy.rb +++ b/activerecord/lib/active_record/associations/association_proxy.rb @@ -53,6 +53,7 @@ module ActiveRecord def initialize(owner, reflection) @owner, @reflection = owner, reflection + @updated = false reflection.check_validity! Array(reflection.options[:extend]).each { |ext| proxy_extend(ext) } reset diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 64e761e7a4..a8698a2f5a 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -18,7 +18,7 @@ module ActiveRecord def save_with_dirty(*args) #:nodoc: if status = save_without_dirty(*args) @previously_changed = changes - changed_attributes.clear + @changed_attributes.clear end status end @@ -26,8 +26,8 @@ module ActiveRecord # Attempts to save! the record and clears changed attributes if successful. def save_with_dirty!(*args) #:nodoc: save_without_dirty!(*args).tap do - @previously_changed = changes - changed_attributes.clear + @previously_changed = changes + @changed_attributes.clear end end @@ -35,7 +35,7 @@ module ActiveRecord def reload_with_dirty(*args) #:nodoc: reload_without_dirty(*args).tap do @previously_changed.clear - changed_attributes.clear + @changed_attributes.clear end end @@ -45,12 +45,12 @@ module ActiveRecord attr = attr.to_s # The attribute already has an unsaved change. - if changed_attributes.include?(attr) - old = changed_attributes[attr] - changed_attributes.delete(attr) unless field_changed?(attr, old, value) + if attribute_changed?(attr) + old = @changed_attributes[attr] + @changed_attributes.delete(attr) unless field_changed?(attr, old, value) else old = clone_attribute_value(:read_attribute, attr) - changed_attributes[attr] = old if field_changed?(attr, old, value) + @changed_attributes[attr] = old if field_changed?(attr, old, value) end # Carry on. -- cgit v1.2.3 From 843255a763c5e68beaa3a1b0bca306c625c30797 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 17 Mar 2010 10:04:49 -0700 Subject: fixing activerecord tests [#4205 state:resolved] Signed-off-by: Jeremy Kemper --- activerecord/lib/active_record/base.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 3d4172f368..6999d4113d 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -13,6 +13,7 @@ require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/string/behavior' require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/module/delegation' +require 'active_support/core_ext/module/remove_method' require 'arel' require 'active_record/errors' -- cgit v1.2.3 From 067b350301279f608a369a39aff9b6f5a22357aa Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 17 Mar 2010 10:11:38 -0700 Subject: Move require closer to home --- activerecord/lib/active_record/base.rb | 1 - 1 file changed, 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 6999d4113d..3d4172f368 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -13,7 +13,6 @@ require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/string/behavior' require 'active_support/core_ext/object/singleton_class' require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/module/remove_method' require 'arel' require 'active_record/errors' -- cgit v1.2.3 From b652aa81216f718f27ba257238d4c27dd54863b2 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 17 Mar 2010 13:30:17 -0700 Subject: cleaning up a bunch of method already defined warnings [#4209 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/nested_attributes.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index bc491c367f..76ec7eb681 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -244,6 +244,9 @@ module ActiveRecord # assign_nested_attributes_for_one_to_one_association(:pirate, attributes) # end class_eval <<-eoruby, __FILE__, __LINE__ + 1 + if method_defined?(:#{association_name}_attributes=) + remove_method(:#{association_name}_attributes=) + end def #{association_name}_attributes=(attributes) assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes) end -- cgit v1.2.3 From 3911a7c197cf40fadab62d17def21db8a3d52f5e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 18 Mar 2010 10:23:14 -0700 Subject: squelching more warnings in the AR tests. [#4218 state:resolved] Signed-off-by: wycats --- .../lib/active_record/railties/log_subscriber.rb | 7 +++- activerecord/test/cases/callbacks_test.rb | 2 +- activerecord/test/cases/fixtures_test.rb | 12 +++---- activerecord/test/cases/transactions_test.rb | 38 ++++++++++++++++++---- 4 files changed, 45 insertions(+), 14 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/railties/log_subscriber.rb b/activerecord/lib/active_record/railties/log_subscriber.rb index 48b25032ce..31b98bb6ed 100644 --- a/activerecord/lib/active_record/railties/log_subscriber.rb +++ b/activerecord/lib/active_record/railties/log_subscriber.rb @@ -1,6 +1,11 @@ module ActiveRecord module Railties class LogSubscriber < Rails::LogSubscriber + def initialize + super + @odd_or_even = false + end + def sql(event) name = '%s (%.1fms)' % [event.payload[:name], event.duration] sql = event.payload[:sql].squeeze(' ') @@ -24,4 +29,4 @@ module ActiveRecord end end end -end \ No newline at end of file +end diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index ff2322ac15..58194993f2 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -139,7 +139,7 @@ class CallbackCancellationDeveloper < ActiveRecord::Base attr_reader :after_save_called, :after_create_called, :after_update_called, :after_destroy_called attr_accessor :cancel_before_save, :cancel_before_create, :cancel_before_update, :cancel_before_destroy - before_save { !@cancel_before_save } + before_save {defined?(@cancel_before_save) ? !@cancel_before_save : false} before_create { !@cancel_before_create } before_update { !@cancel_before_update } before_destroy { !@cancel_before_destroy } diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index f965652a9a..e78b522b65 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -244,14 +244,14 @@ class FixturesWithoutInstantiationTest < ActiveRecord::TestCase fixtures :topics, :developers, :accounts def test_without_complete_instantiation - assert_nil @first - assert_nil @topics - assert_nil @developers - assert_nil @accounts + assert !defined?(@first) + assert !defined?(@topics) + assert !defined?(@developers) + assert !defined?(@accounts) end def test_fixtures_from_root_yml_without_instantiation - assert_nil @unknown + assert !defined?(@unknown), "@unknown is not defined" end def test_accessor_methods @@ -279,7 +279,7 @@ class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase fixtures :topics, :developers, :accounts def test_without_instance_instantiation - assert_nil @first + assert !defined?(@first), "@first is not defined" assert_not_nil @topics assert_not_nil @developers assert_not_nil @accounts diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index aca70b4238..c550030329 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -51,6 +51,7 @@ class TransactionTest < ActiveRecord::TestCase assert !Topic.find(2).approved?, "Second should have been unapproved" ensure class << Topic.connection + remove_method :commit_db_transaction alias :commit_db_transaction :real_commit_db_transaction rescue nil end end @@ -382,28 +383,53 @@ class TransactionTest < ActiveRecord::TestCase private def add_exception_raising_after_save_callback_to_topic - Topic.class_eval "def after_save_for_transaction; raise 'Make the transaction rollback' end" + Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1 + remove_method(:after_save_for_transaction) + def after_save_for_transaction + raise 'Make the transaction rollback' + end + eoruby end def remove_exception_raising_after_save_callback_to_topic - Topic.class_eval "def after_save_for_transaction; end" + Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1 + remove_method :after_save_for_transaction + def after_save_for_transaction; end + eoruby end def add_exception_raising_after_create_callback_to_topic - Topic.class_eval "def after_create_for_transaction; raise 'Make the transaction rollback' end" + Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1 + remove_method(:after_create_for_transaction) + def after_create_for_transaction + raise 'Make the transaction rollback' + end + eoruby end def remove_exception_raising_after_create_callback_to_topic - Topic.class_eval "def after_create_for_transaction; end" + Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1 + remove_method :after_create_for_transaction + def after_create_for_transaction; end + eoruby end %w(validation save destroy).each do |filter| define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do - Topic.class_eval "def before_#{filter}_for_transaction() Book.create; false end" + Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1 + remove_method :before_#{filter}_for_transaction + def before_#{filter}_for_transaction + Book.create + false + end + eoruby end define_method("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic") do - Topic.class_eval "def before_#{filter}_for_transaction; end" + Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1 + remove_method :before_#{filter}_for_transaction + def before_#{filter}_for_transaction; end + eoruby end end end -- cgit v1.2.3 From 587f4682825e0c1fceabc75c83f121578862f3c8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 18 Mar 2010 13:28:22 -0700 Subject: kill where / having method redefine warnings. [#4225 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/relation/query_methods.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index e00d9cdf27..f7cf68665d 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -6,6 +6,7 @@ module ActiveRecord (ActiveRecord::Relation::ASSOCIATION_METHODS + ActiveRecord::Relation::MULTI_VALUE_METHODS).each do |query_method| attr_accessor :"#{query_method}_values" + next if [:where, :having].include?(query_method) class_eval <<-CEVAL def #{query_method}(*args) new_relation = clone -- cgit v1.2.3 From 541194f641c960efe739b16f76999f47742d12ba Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 19 Mar 2010 09:54:44 -0700 Subject: switching migrations to use require cleans up many warnings [#4234 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/migration.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 5825482db7..23e4505f61 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -374,7 +374,7 @@ module ActiveRecord end def load_migration - load(filename) + require(filename) name.constantize end -- cgit v1.2.3 From 34497c0b3638e7fd298da4a1107333fe534f9ca4 Mon Sep 17 00:00:00 2001 From: Evan Phoenix Date: Tue, 16 Mar 2010 13:51:26 -0700 Subject: Remove test ordering bug by using another class --- activerecord/test/cases/callbacks_test.rb | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'activerecord') diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index 58194993f2..dc7f82b001 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -43,6 +43,11 @@ class CallbackDeveloper < ActiveRecord::Base end end +class CallbackDeveloperWithFalseValidation < CallbackDeveloper + before_validation proc { |model| model.history << [:before_validation, :returning_false]; return false } + before_validation proc { |model| model.history << [:before_validation, :should_never_get_here] } +end + class ParentDeveloper < ActiveRecord::Base set_table_name 'developers' attr_accessor :after_save_called @@ -437,10 +442,8 @@ class CallbacksTest < ActiveRecord::TestCase end private :assert_save_callbacks_not_called - def test_zzz_callback_returning_false # must be run last since we modify CallbackDeveloper - david = CallbackDeveloper.find(1) - CallbackDeveloper.before_validation proc { |model| model.history << [:before_validation, :returning_false]; return false } - CallbackDeveloper.before_validation proc { |model| model.history << [:before_validation, :should_never_get_here] } + def test_callback_returning_false + david = CallbackDeveloperWithFalseValidation.find(1) david.save assert_equal [ [ :after_find, :method ], -- cgit v1.2.3 From a307fd6bd37d12d8ad6baa7e7fcfd0207e8b354a Mon Sep 17 00:00:00 2001 From: Evan Phoenix Date: Mon, 22 Mar 2010 09:51:44 -0700 Subject: Don't depend on order of elements in Set --- activerecord/test/cases/finder_test.rb | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) (limited to 'activerecord') diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index d2451f24c1..9e88ec8016 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -502,6 +502,18 @@ class FinderTest < ActiveRecord::TestCase assert_kind_of Time, Topic.find(:first, :conditions => ["id = :id", { :id => 1 }]).written_on end + class SimpleEnumerable + include Enumerable + + def initialize(ary) + @ary = ary + end + + def each(&b) + @ary.each(&b) + end + end + def test_bind_enumerable quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')}) @@ -511,12 +523,11 @@ class FinderTest < ActiveRecord::TestCase assert_equal '1,2,3', bind(':a', :a => [1, 2, 3]) assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # ' - require 'set' - assert_equal '1,2,3', bind('?', Set.new([1, 2, 3])) - assert_equal quoted_abc, bind('?', Set.new(%w(a b c))) + assert_equal '1,2,3', bind('?', SimpleEnumerable.new([1, 2, 3])) + assert_equal quoted_abc, bind('?', SimpleEnumerable.new(%w(a b c))) - assert_equal '1,2,3', bind(':a', :a => Set.new([1, 2, 3])) - assert_equal quoted_abc, bind(':a', :a => Set.new(%w(a b c))) # ' + assert_equal '1,2,3', bind(':a', :a => SimpleEnumerable.new([1, 2, 3])) + assert_equal quoted_abc, bind(':a', :a => SimpleEnumerable.new(%w(a b c))) # ' end def test_bind_empty_enumerable -- cgit v1.2.3 From 79b08616244b31b7e63a46d9a6492bc7e67c2813 Mon Sep 17 00:00:00 2001 From: Evan Phoenix Date: Mon, 22 Mar 2010 09:52:07 -0700 Subject: Remove obsolete use case that was broken in AR::Observers --- activerecord/test/cases/lifecycle_test.rb | 40 ------------------------------- 1 file changed, 40 deletions(-) (limited to 'activerecord') diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb index aa7ce2ecb6..fcad3e90d3 100644 --- a/activerecord/test/cases/lifecycle_test.rb +++ b/activerecord/test/cases/lifecycle_test.rb @@ -6,25 +6,6 @@ require 'models/minimalistic' class SpecialDeveloper < Developer; end -class TopicManualObserver - include Singleton - - attr_reader :action, :object, :callbacks - - def initialize - Topic.add_observer(self) - @callbacks = [] - end - - def update(callback_method, object) - @callbacks << { "callback_method" => callback_method, "object" => object } - end - - def has_been_notified? - !@callbacks.empty? - end -end - class TopicaAuditor < ActiveRecord::Observer observe :topic @@ -85,27 +66,6 @@ class LifecycleTest < ActiveRecord::TestCase assert_equal original_count - (1 + topic_to_be_destroyed.replies.size), Topic.count end - def test_after_save - ActiveRecord::Base.observers = :topic_manual_observer - ActiveRecord::Base.instantiate_observers - - topic = Topic.find(1) - topic.title = "hello" - topic.save - - assert TopicManualObserver.instance.has_been_notified? - assert_equal :after_save, TopicManualObserver.instance.callbacks.last["callback_method"] - end - - def test_observer_update_on_save - ActiveRecord::Base.observers = TopicManualObserver - ActiveRecord::Base.instantiate_observers - - topic = Topic.find(1) - assert TopicManualObserver.instance.has_been_notified? - assert_equal :after_find, TopicManualObserver.instance.callbacks.first["callback_method"] - end - def test_auto_observer topic_observer = TopicaAuditor.instance assert_nil TopicaAuditor.observed_class -- cgit v1.2.3 From 0b608abeb8fea251d4613458e23bf2b6d564ff60 Mon Sep 17 00:00:00 2001 From: Evan Phoenix Date: Mon, 22 Mar 2010 09:53:07 -0700 Subject: Clear the query cache between tests that test the query cache --- activerecord/test/cases/query_cache_test.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'activerecord') diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index 3710f8e40b..91349689bc 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -10,6 +10,10 @@ require 'models/post' class QueryCacheTest < ActiveRecord::TestCase fixtures :tasks, :topics, :categories, :posts, :categories_posts + def setup + Task.connection.clear_query_cache + end + def test_find_queries assert_queries(2) { Task.find(1); Task.find(1) } end -- cgit v1.2.3 From 4f5de7f89a359924abe21949e0f585682c04dd9f Mon Sep 17 00:00:00 2001 From: Evan Phoenix Date: Mon, 22 Mar 2010 09:59:40 -0700 Subject: Reset class attribute after changing it --- activerecord/test/cases/json_serialization_test.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'activerecord') diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb index 54bc8e2343..a3145d2c04 100644 --- a/activerecord/test/cases/json_serialization_test.rb +++ b/activerecord/test/cases/json_serialization_test.rb @@ -27,6 +27,8 @@ class JsonSerializationTest < ActiveRecord::TestCase @contact = NamespacedContact.new :name => 'whatever' json = @contact.to_json assert_match %r{^\{"namespaced_contact":\{}, json + ensure + NamespacedContact.include_root_in_json = false end def test_should_include_root_in_json -- cgit v1.2.3 From d289e15af9b2749ba0ab9534b5469287be6ece05 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Mon, 22 Mar 2010 15:43:14 -0300 Subject: From and lock should be defined to be consistent with other ivars. Limit and offset are always defined, no need to test that. [#4253 state:committed] Signed-off-by: Jeremy Kemper --- activerecord/lib/active_record/relation.rb | 7 ++----- .../lib/active_record/relation/query_methods.rb | 18 ++++-------------- 2 files changed, 6 insertions(+), 19 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 1a84f70a8e..a20c152eeb 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -15,13 +15,10 @@ module ActiveRecord def initialize(klass, table) @klass, @table = klass, table - @readonly_value = nil - @create_with_value = nil @implicit_readonly = nil - @limit_value = nil - @offset_value = nil @loaded = nil + SINGLE_VALUE_METHODS.each {|v| instance_variable_set(:"@#{v}_value", nil)} (ASSOCIATION_METHODS + MULTI_VALUE_METHODS).each {|v| instance_variable_set(:"@#{v}_values", [])} end @@ -62,7 +59,7 @@ module ActiveRecord preload = @preload_values preload += @includes_values unless eager_loading? - preload.each {|associations| @klass.send(:preload_associations, @records, associations) } + preload.each {|associations| @klass.send(:preload_associations, @records, associations) } # @readonly_value is true only if set explicity. @implicit_readonly is true if there are JOINS and no explicit SELECT. readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index f7cf68665d..0250e739b8 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -134,13 +134,8 @@ module ActiveRecord arel = h.is_a?(String) ? arel.having(h) : arel.having(*h) end - if defined?(@limit_value) && @limit_value.present? - arel = arel.take(@limit_value) - end - - if defined?(@offset_value) && @offset_value.present? - arel = arel.skip(@offset_value) - end + arel = arel.take(@limit_value) if @limit_value.present? + arel = arel.skip(@offset_value) if @offset_value.present? @group_values.uniq.each do |g| arel = arel.group(g) if g.present? @@ -163,19 +158,14 @@ module ActiveRecord arel = arel.project(quoted_table_name + '.*') end - arel = - if defined?(@from_value) && @from_value.present? - arel.from(@from_value) - else - arel.from(quoted_table_name) - end + arel = @from_value.present? ? arel.from(@from_value) : arel.from(quoted_table_name) case @lock_value when TrueClass arel = arel.lock when String arel = arel.lock(@lock_value) - end if defined?(@lock_value) + end if @lock_value.present? arel end -- cgit v1.2.3 From b61f6f59805eec4f5bb873a85910c9fe00e839a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 23 Mar 2010 13:40:19 +0100 Subject: Load generators from both lib/rails/generators and lib/generators. Using the former since it's less obstrusive. --- activerecord/lib/generators/active_record.rb | 30 -------------------- .../active_record/migration/migration_generator.rb | 25 ---------------- .../active_record/migration/templates/migration.rb | 11 -------- .../active_record/model/model_generator.rb | 33 ---------------------- .../active_record/model/templates/migration.rb | 16 ----------- .../active_record/model/templates/model.rb | 5 ---- .../active_record/observer/observer_generator.rb | 15 ---------- .../active_record/observer/templates/observer.rb | 2 -- .../session_migration_generator.rb | 24 ---------------- .../session_migration/templates/migration.rb | 16 ----------- activerecord/lib/rails/generators/active_record.rb | 30 ++++++++++++++++++++ .../active_record/migration/migration_generator.rb | 25 ++++++++++++++++ .../active_record/migration/templates/migration.rb | 11 ++++++++ .../active_record/model/model_generator.rb | 33 ++++++++++++++++++++++ .../active_record/model/templates/migration.rb | 16 +++++++++++ .../active_record/model/templates/model.rb | 5 ++++ .../active_record/observer/observer_generator.rb | 15 ++++++++++ .../active_record/observer/templates/observer.rb | 2 ++ .../session_migration_generator.rb | 24 ++++++++++++++++ .../session_migration/templates/migration.rb | 16 +++++++++++ 20 files changed, 177 insertions(+), 177 deletions(-) delete mode 100644 activerecord/lib/generators/active_record.rb delete mode 100644 activerecord/lib/generators/active_record/migration/migration_generator.rb delete mode 100644 activerecord/lib/generators/active_record/migration/templates/migration.rb delete mode 100644 activerecord/lib/generators/active_record/model/model_generator.rb delete mode 100644 activerecord/lib/generators/active_record/model/templates/migration.rb delete mode 100644 activerecord/lib/generators/active_record/model/templates/model.rb delete mode 100644 activerecord/lib/generators/active_record/observer/observer_generator.rb delete mode 100644 activerecord/lib/generators/active_record/observer/templates/observer.rb delete mode 100644 activerecord/lib/generators/active_record/session_migration/session_migration_generator.rb delete mode 100644 activerecord/lib/generators/active_record/session_migration/templates/migration.rb create mode 100644 activerecord/lib/rails/generators/active_record.rb create mode 100644 activerecord/lib/rails/generators/active_record/migration/migration_generator.rb create mode 100644 activerecord/lib/rails/generators/active_record/migration/templates/migration.rb create mode 100644 activerecord/lib/rails/generators/active_record/model/model_generator.rb create mode 100644 activerecord/lib/rails/generators/active_record/model/templates/migration.rb create mode 100644 activerecord/lib/rails/generators/active_record/model/templates/model.rb create mode 100644 activerecord/lib/rails/generators/active_record/observer/observer_generator.rb create mode 100644 activerecord/lib/rails/generators/active_record/observer/templates/observer.rb create mode 100644 activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb create mode 100644 activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb (limited to 'activerecord') diff --git a/activerecord/lib/generators/active_record.rb b/activerecord/lib/generators/active_record.rb deleted file mode 100644 index 1ca838b4f2..0000000000 --- a/activerecord/lib/generators/active_record.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'rails/generators/named_base' -require 'rails/generators/migration' -require 'rails/generators/active_model' -require 'active_record' - -module ActiveRecord - module Generators - class Base < Rails::Generators::NamedBase #:nodoc: - include Rails::Generators::Migration - - def self.source_root - @_ar_source_root ||= begin - if base_name && generator_name - File.expand_path(File.join(base_name, generator_name, 'templates'), File.dirname(__FILE__)) - end - end - end - - # Implement the required interface for Rails::Generators::Migration. - # - def self.next_migration_number(dirname) #:nodoc: - if ActiveRecord::Base.timestamped_migrations - Time.now.utc.strftime("%Y%m%d%H%M%S") - else - "%.3d" % (current_migration_number(dirname) + 1) - end - end - end - end -end diff --git a/activerecord/lib/generators/active_record/migration/migration_generator.rb b/activerecord/lib/generators/active_record/migration/migration_generator.rb deleted file mode 100644 index 7939977f72..0000000000 --- a/activerecord/lib/generators/active_record/migration/migration_generator.rb +++ /dev/null @@ -1,25 +0,0 @@ -require 'generators/active_record' - -module ActiveRecord - module Generators - class MigrationGenerator < Base - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" - - def create_migration_file - set_local_assigns! - migration_template "migration.rb", "db/migrate/#{file_name}.rb" - end - - protected - attr_reader :migration_action - - def set_local_assigns! - if file_name =~ /^(add|remove)_.*_(?:to|from)_(.*)/ - @migration_action = $1 - @table_name = $2.pluralize - end - end - - end - end -end diff --git a/activerecord/lib/generators/active_record/migration/templates/migration.rb b/activerecord/lib/generators/active_record/migration/templates/migration.rb deleted file mode 100644 index bbb7c53d86..0000000000 --- a/activerecord/lib/generators/active_record/migration/templates/migration.rb +++ /dev/null @@ -1,11 +0,0 @@ -class <%= migration_class_name %> < ActiveRecord::Migration - def self.up<% attributes.each do |attribute| %> - <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end -%> - <%- end %> - end - - def self.down<% attributes.reverse.each do |attribute| %> - <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><% end -%> - <%- end %> - end -end diff --git a/activerecord/lib/generators/active_record/model/model_generator.rb b/activerecord/lib/generators/active_record/model/model_generator.rb deleted file mode 100644 index 2641083e0d..0000000000 --- a/activerecord/lib/generators/active_record/model/model_generator.rb +++ /dev/null @@ -1,33 +0,0 @@ -require 'generators/active_record' - -module ActiveRecord - module Generators - class ModelGenerator < Base - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" - - check_class_collision - - class_option :migration, :type => :boolean - class_option :timestamps, :type => :boolean - class_option :parent, :type => :string, :desc => "The parent class for the generated model" - - def create_migration_file - return unless options[:migration] && options[:parent].nil? - migration_template "migration.rb", "db/migrate/create_#{table_name}.rb" - end - - def create_model_file - template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb") - end - - hook_for :test_framework - - protected - - def parent_class_name - options[:parent] || "ActiveRecord::Base" - end - - end - end -end diff --git a/activerecord/lib/generators/active_record/model/templates/migration.rb b/activerecord/lib/generators/active_record/model/templates/migration.rb deleted file mode 100644 index 1f68487304..0000000000 --- a/activerecord/lib/generators/active_record/model/templates/migration.rb +++ /dev/null @@ -1,16 +0,0 @@ -class <%= migration_class_name %> < ActiveRecord::Migration - def self.up - create_table :<%= table_name %> do |t| -<% for attribute in attributes -%> - t.<%= attribute.type %> :<%= attribute.name %> -<% end -%> -<% if options[:timestamps] %> - t.timestamps -<% end -%> - end - end - - def self.down - drop_table :<%= table_name %> - end -end diff --git a/activerecord/lib/generators/active_record/model/templates/model.rb b/activerecord/lib/generators/active_record/model/templates/model.rb deleted file mode 100644 index 21ae29e9f2..0000000000 --- a/activerecord/lib/generators/active_record/model/templates/model.rb +++ /dev/null @@ -1,5 +0,0 @@ -class <%= class_name %> < <%= parent_class_name.classify %> -<% attributes.select {|attr| attr.reference? }.each do |attribute| -%> - belongs_to :<%= attribute.name %> -<% end -%> -end diff --git a/activerecord/lib/generators/active_record/observer/observer_generator.rb b/activerecord/lib/generators/active_record/observer/observer_generator.rb deleted file mode 100644 index a6b57423b8..0000000000 --- a/activerecord/lib/generators/active_record/observer/observer_generator.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'generators/active_record' - -module ActiveRecord - module Generators - class ObserverGenerator < Base - check_class_collision :suffix => "Observer" - - def create_observer_file - template 'observer.rb', File.join('app/models', class_path, "#{file_name}_observer.rb") - end - - hook_for :test_framework - end - end -end diff --git a/activerecord/lib/generators/active_record/observer/templates/observer.rb b/activerecord/lib/generators/active_record/observer/templates/observer.rb deleted file mode 100644 index b9a3004161..0000000000 --- a/activerecord/lib/generators/active_record/observer/templates/observer.rb +++ /dev/null @@ -1,2 +0,0 @@ -class <%= class_name %>Observer < ActiveRecord::Observer -end diff --git a/activerecord/lib/generators/active_record/session_migration/session_migration_generator.rb b/activerecord/lib/generators/active_record/session_migration/session_migration_generator.rb deleted file mode 100644 index 59c4792066..0000000000 --- a/activerecord/lib/generators/active_record/session_migration/session_migration_generator.rb +++ /dev/null @@ -1,24 +0,0 @@ -require 'generators/active_record' - -module ActiveRecord - module Generators - class SessionMigrationGenerator < Base - argument :name, :type => :string, :default => "add_sessions_table" - - def create_migration_file - migration_template "migration.rb", "db/migrate/#{file_name}.rb" - end - - protected - - def session_table_name - current_table_name = ActiveRecord::SessionStore::Session.table_name - if ["sessions", "session"].include?(current_table_name) - current_table_name = (ActiveRecord::Base.pluralize_table_names ? 'session'.pluralize : 'session') - end - current_table_name - end - - end - end -end diff --git a/activerecord/lib/generators/active_record/session_migration/templates/migration.rb b/activerecord/lib/generators/active_record/session_migration/templates/migration.rb deleted file mode 100644 index 919822af7b..0000000000 --- a/activerecord/lib/generators/active_record/session_migration/templates/migration.rb +++ /dev/null @@ -1,16 +0,0 @@ -class <%= migration_class_name %> < ActiveRecord::Migration - def self.up - create_table :<%= session_table_name %> do |t| - t.string :session_id, :null => false - t.text :data - t.timestamps - end - - add_index :<%= session_table_name %>, :session_id - add_index :<%= session_table_name %>, :updated_at - end - - def self.down - drop_table :<%= session_table_name %> - end -end diff --git a/activerecord/lib/rails/generators/active_record.rb b/activerecord/lib/rails/generators/active_record.rb new file mode 100644 index 0000000000..1ca838b4f2 --- /dev/null +++ b/activerecord/lib/rails/generators/active_record.rb @@ -0,0 +1,30 @@ +require 'rails/generators/named_base' +require 'rails/generators/migration' +require 'rails/generators/active_model' +require 'active_record' + +module ActiveRecord + module Generators + class Base < Rails::Generators::NamedBase #:nodoc: + include Rails::Generators::Migration + + def self.source_root + @_ar_source_root ||= begin + if base_name && generator_name + File.expand_path(File.join(base_name, generator_name, 'templates'), File.dirname(__FILE__)) + end + end + end + + # Implement the required interface for Rails::Generators::Migration. + # + def self.next_migration_number(dirname) #:nodoc: + if ActiveRecord::Base.timestamped_migrations + Time.now.utc.strftime("%Y%m%d%H%M%S") + else + "%.3d" % (current_migration_number(dirname) + 1) + end + end + end + end +end diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb new file mode 100644 index 0000000000..f6159deeeb --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb @@ -0,0 +1,25 @@ +require 'rails/generators/active_record' + +module ActiveRecord + module Generators + class MigrationGenerator < Base + argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + + def create_migration_file + set_local_assigns! + migration_template "migration.rb", "db/migrate/#{file_name}.rb" + end + + protected + attr_reader :migration_action + + def set_local_assigns! + if file_name =~ /^(add|remove)_.*_(?:to|from)_(.*)/ + @migration_action = $1 + @table_name = $2.pluralize + end + end + + end + end +end diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb new file mode 100644 index 0000000000..bbb7c53d86 --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb @@ -0,0 +1,11 @@ +class <%= migration_class_name %> < ActiveRecord::Migration + def self.up<% attributes.each do |attribute| %> + <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end -%> + <%- end %> + end + + def self.down<% attributes.reverse.each do |attribute| %> + <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><% end -%> + <%- end %> + end +end diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb new file mode 100644 index 0000000000..3e72fbeca8 --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -0,0 +1,33 @@ +require 'rails/generators/active_record' + +module ActiveRecord + module Generators + class ModelGenerator < Base + argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + + check_class_collision + + class_option :migration, :type => :boolean + class_option :timestamps, :type => :boolean + class_option :parent, :type => :string, :desc => "The parent class for the generated model" + + def create_migration_file + return unless options[:migration] && options[:parent].nil? + migration_template "migration.rb", "db/migrate/create_#{table_name}.rb" + end + + def create_model_file + template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb") + end + + hook_for :test_framework + + protected + + def parent_class_name + options[:parent] || "ActiveRecord::Base" + end + + end + end +end diff --git a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb new file mode 100644 index 0000000000..1f68487304 --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb @@ -0,0 +1,16 @@ +class <%= migration_class_name %> < ActiveRecord::Migration + def self.up + create_table :<%= table_name %> do |t| +<% for attribute in attributes -%> + t.<%= attribute.type %> :<%= attribute.name %> +<% end -%> +<% if options[:timestamps] %> + t.timestamps +<% end -%> + end + end + + def self.down + drop_table :<%= table_name %> + end +end diff --git a/activerecord/lib/rails/generators/active_record/model/templates/model.rb b/activerecord/lib/rails/generators/active_record/model/templates/model.rb new file mode 100644 index 0000000000..21ae29e9f2 --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/model/templates/model.rb @@ -0,0 +1,5 @@ +class <%= class_name %> < <%= parent_class_name.classify %> +<% attributes.select {|attr| attr.reference? }.each do |attribute| -%> + belongs_to :<%= attribute.name %> +<% end -%> +end diff --git a/activerecord/lib/rails/generators/active_record/observer/observer_generator.rb b/activerecord/lib/rails/generators/active_record/observer/observer_generator.rb new file mode 100644 index 0000000000..c1c0e3f25b --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/observer/observer_generator.rb @@ -0,0 +1,15 @@ +require 'rails/generators/active_record' + +module ActiveRecord + module Generators + class ObserverGenerator < Base + check_class_collision :suffix => "Observer" + + def create_observer_file + template 'observer.rb', File.join('app/models', class_path, "#{file_name}_observer.rb") + end + + hook_for :test_framework + end + end +end diff --git a/activerecord/lib/rails/generators/active_record/observer/templates/observer.rb b/activerecord/lib/rails/generators/active_record/observer/templates/observer.rb new file mode 100644 index 0000000000..b9a3004161 --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/observer/templates/observer.rb @@ -0,0 +1,2 @@ +class <%= class_name %>Observer < ActiveRecord::Observer +end diff --git a/activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb b/activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb new file mode 100644 index 0000000000..afcda2a98a --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/session_migration/session_migration_generator.rb @@ -0,0 +1,24 @@ +require 'rails/generators/active_record' + +module ActiveRecord + module Generators + class SessionMigrationGenerator < Base + argument :name, :type => :string, :default => "add_sessions_table" + + def create_migration_file + migration_template "migration.rb", "db/migrate/#{file_name}.rb" + end + + protected + + def session_table_name + current_table_name = ActiveRecord::SessionStore::Session.table_name + if ["sessions", "session"].include?(current_table_name) + current_table_name = (ActiveRecord::Base.pluralize_table_names ? 'session'.pluralize : 'session') + end + current_table_name + end + + end + end +end diff --git a/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb new file mode 100644 index 0000000000..919822af7b --- /dev/null +++ b/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb @@ -0,0 +1,16 @@ +class <%= migration_class_name %> < ActiveRecord::Migration + def self.up + create_table :<%= session_table_name %> do |t| + t.string :session_id, :null => false + t.text :data + t.timestamps + end + + add_index :<%= session_table_name %>, :session_id + add_index :<%= session_table_name %>, :updated_at + end + + def self.down + drop_table :<%= session_table_name %> + end +end -- cgit v1.2.3 From 10825be40b982516c9b0d747dbd5b7f1d320873d Mon Sep 17 00:00:00 2001 From: Sebastian Martinez Date: Tue, 23 Mar 2010 10:20:43 -0300 Subject: rake tasks should use the new app generator path [#4257 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activerecord/lib/active_record/railties/databases.rake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index fa6caa4910..0229793a9a 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -435,7 +435,7 @@ namespace :db do task :create => :environment do raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations? require 'rails/generators' - require 'generators/rails/session_migration/session_migration_generator' + require 'rails/generators/rails/session_migration/session_migration_generator' Rails::Generators::SessionMigrationGenerator.start [ ENV["MIGRATION"] || "add_sessions_table" ] end -- cgit v1.2.3 From bc48d39e4c0348f627f9bf2d9090082c54a052c7 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 23 Mar 2010 18:01:03 -0700 Subject: do not use unloadable constants in tests [#4260 state:resolved] Signed-off-by: wycats --- activerecord/test/cases/migration_test.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'activerecord') diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 3181f27bc2..03ee8dcf3c 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1109,8 +1109,7 @@ if ActiveRecord::Base.connection.supports_migrations? ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) # now unload the migrations that have been defined - PeopleHaveLastNames.unloadable - ActiveSupport::Dependencies.remove_unloadable_constants! + Object.send(:remove_const, :PeopleHaveLastNames) ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", nil) -- cgit v1.2.3 From ed21f0c50270139ddb6993acfdaea4586ffd09a3 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 23 Mar 2010 18:20:28 -0700 Subject: expand migration paths before requiring them. [#4240 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/migration.rb | 2 +- activerecord/test/cases/migration_test.rb | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 23e4505f61..d4cda927ad 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -374,7 +374,7 @@ module ActiveRecord end def load_migration - require(filename) + require(File.expand_path(filename)) name.constantize end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 03ee8dcf3c..e213986ede 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1104,6 +1104,19 @@ if ActiveRecord::Base.connection.supports_migrations? assert_equal migrations[0].name, 'InnocentJointable' end + def test_relative_migrations + $".delete_if do |fname| + fname == (MIGRATIONS_ROOT + "/valid/1_people_have_last_names.rb") + end + Object.send(:remove_const, :PeopleHaveLastNames) + + Dir.chdir(MIGRATIONS_ROOT) do + ActiveRecord::Migrator.up("valid/", 1) + end + + assert defined?(PeopleHaveLastNames) + end + def test_only_loads_pending_migrations # migrate up to 1 ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) -- cgit v1.2.3 From e3a2fae05dfce39bbac86780c28b102acc3aa68f Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Thu, 25 Mar 2010 12:27:34 -0300 Subject: Add add_limit_offset! to adapters. --- .../abstract/database_statements.rb | 23 ++++++++++++++++++++++ .../connection_adapters/mysql_adapter.rb | 12 +++++++++++ activerecord/test/cases/adapter_test.rb | 21 ++++++++++++++++++++ 3 files changed, 56 insertions(+) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index abb695264e..0c87e052c4 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -181,6 +181,29 @@ module ActiveRecord # done if the transaction block raises an exception or returns false. def rollback_db_transaction() end + # Appends +LIMIT+ and +OFFSET+ options to an SQL statement, or some SQL + # fragment that has the same semantics as LIMIT and OFFSET. + # + # +options+ must be a Hash which contains a +:limit+ option + # and an +:offset+ option. + # + # This method *modifies* the +sql+ parameter. + # + # ===== Examples + # add_limit_offset!('SELECT * FROM suppliers', {:limit => 10, :offset => 50}) + # generates + # SELECT * FROM suppliers LIMIT 10 OFFSET 50 + + def add_limit_offset!(sql, options) + if limit = options[:limit] + sql << " LIMIT #{sanitize_limit(limit)}" + end + if offset = options[:offset] + sql << " OFFSET #{offset.to_i}" + end + sql + end + def default_sequence_name(table, column) nil end diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 1f1df7e8c3..6946701ee5 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -375,6 +375,18 @@ module ActiveRecord execute("RELEASE SAVEPOINT #{current_savepoint_name}") end + def add_limit_offset!(sql, options) #:nodoc: + limit, offset = options[:limit], options[:offset] + if limit && offset + sql << " LIMIT #{offset.to_i}, #{sanitize_limit(limit)}" + elsif limit + sql << " LIMIT #{sanitize_limit(limit)}" + elsif offset + sql << " OFFSET #{offset.to_i}" + end + sql + end + # SCHEMA STATEMENTS ======================================== def structure_dump #:nodoc: diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index c59be264a4..9b28766405 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -142,4 +142,25 @@ class AdapterTest < ActiveRecord::TestCase end end end + + def test_add_limit_offset_should_sanitize_sql_injection_for_limit_without_comas + sql_inject = "1 select * from schema" + assert_equal " LIMIT 1", @connection.add_limit_offset!("", :limit => sql_inject) + if current_adapter?(:MysqlAdapter) + assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit => sql_inject, :offset => 7) + else + assert_equal " LIMIT 1 OFFSET 7", @connection.add_limit_offset!("", :limit => sql_inject, :offset => 7) + end + end + + def test_add_limit_offset_should_sanitize_sql_injection_for_limit_with_comas + sql_inject = "1, 7 procedure help()" + if current_adapter?(:MysqlAdapter) + assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit => sql_inject) + assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit => '1 ; DROP TABLE USERS', :offset => 7) + else + assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit => sql_inject) + assert_equal " LIMIT 1,7 OFFSET 7", @connection.add_limit_offset!("", :limit => sql_inject, :offset => 7) + end + end end -- cgit v1.2.3 From e260d5fbcfd1e843c849826a184c3fb76f08f980 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Thu, 25 Mar 2010 12:28:32 -0300 Subject: Require Arel 0.3.2 --- activerecord/activerecord.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 8b1ea8596a..0881eedf35 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -22,5 +22,5 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) - s.add_dependency('arel', '~> 0.3.1') + s.add_dependency('arel', '~> 0.3.2') end -- cgit v1.2.3 From 90a4709601873583d32c422c3a6422ef56bbc81b Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 23 Mar 2010 15:27:00 -0300 Subject: Refactor relation merging to create just one relation and then assign values, instead of creating multiple relation objects. --- .../lib/active_record/relation/spawn_methods.rb | 36 +++++++++------------- 1 file changed, 14 insertions(+), 22 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb index a18380f01c..2841ff1239 100644 --- a/activerecord/lib/active_record/relation/spawn_methods.rb +++ b/activerecord/lib/active_record/relation/spawn_methods.rb @@ -4,30 +4,14 @@ module ActiveRecord merged_relation = clone return merged_relation unless r - merged_relation = merged_relation.eager_load(r.eager_load_values).preload(r.preload_values).includes(r.includes_values) - - merged_relation.readonly_value = r.readonly_value unless r.readonly_value.nil? - merged_relation.limit_value = r.limit_value if r.limit_value.present? - merged_relation.lock_value = r.lock_value unless merged_relation.lock_value - merged_relation.offset_value = r.offset_value if r.offset_value.present? - - merged_relation = merged_relation. - joins(r.joins_values). - group(r.group_values). - select(r.select_values). - from(r.from_value). - having(r.having_values) - - merged_relation.order_values = r.order_values if r.order_values.present? - - merged_relation.create_with_value = @create_with_value - - if @create_with_value && r.create_with_value - merged_relation.create_with_value = @create_with_value.merge(r.create_with_value) - else - merged_relation.create_with_value = r.create_with_value || @create_with_value + (ActiveRecord::Relation::ASSOCIATION_METHODS + ActiveRecord::Relation::MULTI_VALUE_METHODS).reject {|m| [:joins, :where].include?(m)}.each do |method| + unless (value = r.send(:"#{method}_values")).blank? + merged_relation.send(:"#{method}_values=", value) + end end + merged_relation = merged_relation.joins(r.joins_values) + merged_wheres = @where_values r.where_values.each do |w| @@ -40,6 +24,14 @@ module ActiveRecord merged_relation.where_values = merged_wheres + ActiveRecord::Relation::SINGLE_VALUE_METHODS.reject {|m| m == :lock}.each do |method| + unless (value = r.send(:"#{method}_value")).nil? + merged_relation.send(:"#{method}_value=", value) + end + end + + merged_relation.lock_value = r.lock_value unless merged_relation.lock_value + merged_relation end -- cgit v1.2.3 From fc2e25734a175641595db9612d3fb5371cb8aa2c Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 23 Mar 2010 12:56:35 -0300 Subject: Move methods from association to relation finder methods. --- activerecord/lib/active_record/associations.rb | 9 --------- activerecord/lib/active_record/relation/finder_methods.rb | 13 +++++++++++-- 2 files changed, 11 insertions(+), 11 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index a5179033f2..bff82f960c 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1673,15 +1673,6 @@ module ActiveRecord reflection end - def using_limitable_reflections?(reflections) - reflections.collect(&:collection?).length.zero? - end - - def column_aliases(join_dependency) - join_dependency.joins.collect{|join| join.column_names_with_alias.collect{|column_name, aliased_name| - "#{connection.quote_table_name join.aliased_table_name}.#{connection.quote_column_name column_name} AS #{aliased_name}"}}.flatten.join(", ") - end - def add_association_callbacks(association_name, options) callbacks = %w(before_add after_add before_remove after_remove) callbacks.each do |callback_name| diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index d6d3d66642..c1cce679b6 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -175,7 +175,7 @@ module ActiveRecord end def construct_relation_for_association_find(join_dependency) - relation = except(:includes, :eager_load, :preload, :select).select(@klass.send(:column_aliases, join_dependency)) + relation = except(:includes, :eager_load, :preload, :select).select(column_aliases(join_dependency)) apply_join_dependency(relation, join_dependency) end @@ -184,7 +184,7 @@ module ActiveRecord relation = association.join_relation(relation) end - limitable_reflections = @klass.send(:using_limitable_reflections?, join_dependency.reflections) + limitable_reflections = using_limitable_reflections?(join_dependency.reflections) if !limitable_reflections && relation.limit_value limited_id_condition = construct_limited_ids_condition(relation.except(:select)) @@ -311,5 +311,14 @@ module ActiveRecord end end + def column_aliases(join_dependency) + join_dependency.joins.collect{|join| join.column_names_with_alias.collect{|column_name, aliased_name| + "#{connection.quote_table_name join.aliased_table_name}.#{connection.quote_column_name column_name} AS #{aliased_name}"}}.flatten.join(", ") + end + + def using_limitable_reflections?(reflections) + reflections.collect(&:collection?).length.zero? + end + end end -- cgit v1.2.3 From d06a754fdd81a17206c0c404d7d1361200a84b17 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 23 Mar 2010 12:34:47 -0300 Subject: Remove unused attributes_with_quotes method. --- activerecord/lib/active_record/base.rb | 20 -------------------- 1 file changed, 20 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 3d4172f368..367b4ce217 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -2053,26 +2053,6 @@ module ActiveRecord #:nodoc: default end - # Returns a copy of the attributes hash where all the values have been safely quoted for use in - # an SQL statement. - def attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys) - quoted = {} - connection = self.class.connection - attribute_names.each do |name| - if (column = column_for_attribute(name)) && (include_primary_key || !column.primary) - value = read_attribute(name) - - # We need explicit to_yaml because quote() does not properly convert Time/Date fields to YAML. - if value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time)) - value = value.to_yaml - end - - quoted[name] = connection.quote(value, column) - end - end - include_readonly_attributes ? quoted : remove_readonly_attributes(quoted) - end - # Returns a copy of the attributes hash where all the values have been safely quoted for use in # an Arel insert/update method. def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys) -- cgit v1.2.3 From a8b93d7a05c6bf4cb4d4fec3add6cf1a04bb24ef Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 25 Mar 2010 11:52:53 -0700 Subject: Bump to arel 0.3.3 to resolve Active Support dep --- activerecord/activerecord.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 0881eedf35..8121530ab3 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -22,5 +22,5 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) - s.add_dependency('arel', '~> 0.3.2') + s.add_dependency('arel', '~> 0.3.3') end -- cgit v1.2.3 From 5176b28852dc6d0654cdf601d590bddbd6e6da1e Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Fri, 26 Mar 2010 13:09:38 +0430 Subject: Better MySQL Error message. [#3775 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activerecord/lib/active_record/connection_adapters/mysql_adapter.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 6946701ee5..521bd810d0 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -61,7 +61,7 @@ module ActiveRecord begin require_library_or_gem('mysql') rescue LoadError - $stderr.puts '!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.' + $stderr.puts '!!! Please install the mysql gem and try again: gem install mysql.' raise end end -- cgit v1.2.3 From 395d6648ce7549f71dd0a76dc061e87f608aaaab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 26 Mar 2010 18:47:55 +0100 Subject: Move application configuration to the application configuration object, remove railtie_name and engine_name and allow to set the configuration object. --- activerecord/lib/active_record/railtie.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index 60addd46c6..de47461c73 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -10,7 +10,7 @@ require "action_controller/railtie" module ActiveRecord class Railtie < Rails::Railtie - railtie_name :active_record + config.active_record = ActiveSupport::OrderedOptions.new config.generators.orm :active_record, :migration => true, :timestamps => true @@ -19,9 +19,8 @@ module ActiveRecord load "active_record/railties/databases.rake" end - # TODO If we require the wrong file, the error never comes up. require "active_record/railties/log_subscriber" - log_subscriber ActiveRecord::Railties::LogSubscriber.new + log_subscriber :active_record, ActiveRecord::Railties::LogSubscriber.new initializer "active_record.initialize_timezone" do ActiveRecord.base_hook do -- cgit v1.2.3 From afb786ad8a27ae593790a5788441a9083a516195 Mon Sep 17 00:00:00 2001 From: Kris Selden Date: Fri, 26 Mar 2010 15:21:55 -0700 Subject: In PostgreSQLAdapter, switch tables query to use current_schemas function [#918 state:resolved] Signed-off-by: wycats --- .../lib/active_record/connection_adapters/postgresql_adapter.rb | 4 +--- activerecord/test/cases/schema_authorization_test_postgresql.rb | 9 +++++++++ 2 files changed, 10 insertions(+), 3 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index b3ce8c79dd..c9a5f00dfd 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -651,14 +651,12 @@ module ActiveRecord end end - # Returns the list of all tables in the schema search path or a specified schema. def tables(name = nil) - schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',') query(<<-SQL, name).map { |row| row[0] } SELECT tablename FROM pg_tables - WHERE schemaname IN (#{schemas}) + WHERE schemaname = ANY (current_schemas(false)) SQL end diff --git a/activerecord/test/cases/schema_authorization_test_postgresql.rb b/activerecord/test/cases/schema_authorization_test_postgresql.rb index ba7754513d..2860f1ad48 100644 --- a/activerecord/test/cases/schema_authorization_test_postgresql.rb +++ b/activerecord/test/cases/schema_authorization_test_postgresql.rb @@ -66,6 +66,15 @@ class SchemaAuthorizationTest < ActiveRecord::TestCase end end end + + def test_tables_in_current_schemas + assert !@connection.tables.include?(TABLE_NAME) + USERS.each do |u| + set_session_auth u + assert @connection.tables.include?(TABLE_NAME) + set_session_auth + end + end private def set_session_auth auth = nil -- cgit v1.2.3 From 3a875e618487a06a56f6cf912cf5440f294921cc Mon Sep 17 00:00:00 2001 From: Nathaniel Bibler Date: Sun, 24 Jan 2010 13:06:29 -0500 Subject: Changed behavior of touch and added touch! Originally implemented by Obie Fernandez, updated touch! to act as a thin wrapper to touch. [#2520 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/timestamp.rb | 26 ++++++++++++++++++-------- activerecord/test/cases/timestamp_test.rb | 25 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 8 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb index da075dabd3..cd13ea0d09 100644 --- a/activerecord/lib/active_record/timestamp.rb +++ b/activerecord/lib/active_record/timestamp.rb @@ -18,9 +18,8 @@ module ActiveRecord self.record_timestamps = true end - # Saves the record with the updated_at/on attributes set to the current time. - # If the save fails because of validation errors, an ActiveRecord::RecordInvalid exception is raised. - # If an attribute name is passed, that attribute is used for the touch instead of the updated_at/on attributes. + # Updates only the record's updated_at/on attributes to the current time without checking validations. + # If an attribute name is passed, that attribute is used instead of the updated_at/on attributes. # # Examples: # @@ -30,13 +29,24 @@ module ActiveRecord current_time = current_time_from_proper_timezone if attribute - write_attribute(attribute, current_time) + update_attribute(attribute, current_time) else - write_attribute('updated_at', current_time) if respond_to?(:updated_at) - write_attribute('updated_on', current_time) if respond_to?(:updated_on) + update_attribute('updated_at', current_time) if respond_to?(:updated_at) + update_attribute('updated_on', current_time) if respond_to?(:updated_on) end - - save! + end + + # Saves the entire record with the updated_at/on attributes set to the current time. + # If the save fails because of validation errors, an ActiveRecord::RecordInvalid exception is raised. + # If an attribute name is passed, that attribute is used for the touch instead of the updated_at/on attributes. + # + # Examples: + # + # product.touch! # updates updated_at + # product.touch!(:designed_at) # updates the designed_at attribute + def touch!(attribute = nil) + raise ActiveRecord::RecordInvalid.new(self) unless valid? + touch(attribute) end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 24b237a72b..6c3596347d 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -30,6 +30,24 @@ class TimestampTest < ActiveRecord::TestCase assert @previously_updated_at != @developer.updated_at end + def test_touching_a_record_updates_its_timestamp_even_if_object_instance_is_invalid + @developer.name = nil + @developer.touch + + assert @previously_updated_at != @developer.updated_at + end + + def test_touch_bang_a_record_updates_its_timestamp + @developer.touch! + + assert @previously_updated_at != @developer.updated_at + end + + def test_touch_banging_a_record_fails_if_object_instance_is_invalid + @developer.name = nil + assert_raise(ActiveRecord::RecordInvalid) { @developer.touch! } + end + def test_touching_a_different_attribute previously_created_at = @developer.created_at @developer.touch(:created_at) @@ -37,6 +55,13 @@ class TimestampTest < ActiveRecord::TestCase assert previously_created_at != @developer.created_at end + def test_touch_banging_a_different_attribute + previously_created_at = @developer.created_at + @developer.touch!(:created_at) + + assert previously_created_at != @developer.created_at + end + def test_saving_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_update_the_parent_updated_at pet = Pet.first owner = pet.owner -- cgit v1.2.3 From 68ade93cde3fcb3ac9fdfe0541d33d22c2c748d7 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 27 Mar 2010 08:22:32 +0000 Subject: Revert "Changed behavior of touch and added touch! Originally implemented by Obie Fernandez, updated touch! to act as a thin wrapper to touch. [#2520 state:resolved]" This reverts commit 3a875e618487a06a56f6cf912cf5440f294921cc. --- activerecord/lib/active_record/timestamp.rb | 26 ++++++++------------------ activerecord/test/cases/timestamp_test.rb | 25 ------------------------- 2 files changed, 8 insertions(+), 43 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb index cd13ea0d09..da075dabd3 100644 --- a/activerecord/lib/active_record/timestamp.rb +++ b/activerecord/lib/active_record/timestamp.rb @@ -18,8 +18,9 @@ module ActiveRecord self.record_timestamps = true end - # Updates only the record's updated_at/on attributes to the current time without checking validations. - # If an attribute name is passed, that attribute is used instead of the updated_at/on attributes. + # Saves the record with the updated_at/on attributes set to the current time. + # If the save fails because of validation errors, an ActiveRecord::RecordInvalid exception is raised. + # If an attribute name is passed, that attribute is used for the touch instead of the updated_at/on attributes. # # Examples: # @@ -29,24 +30,13 @@ module ActiveRecord current_time = current_time_from_proper_timezone if attribute - update_attribute(attribute, current_time) + write_attribute(attribute, current_time) else - update_attribute('updated_at', current_time) if respond_to?(:updated_at) - update_attribute('updated_on', current_time) if respond_to?(:updated_on) + write_attribute('updated_at', current_time) if respond_to?(:updated_at) + write_attribute('updated_on', current_time) if respond_to?(:updated_on) end - end - - # Saves the entire record with the updated_at/on attributes set to the current time. - # If the save fails because of validation errors, an ActiveRecord::RecordInvalid exception is raised. - # If an attribute name is passed, that attribute is used for the touch instead of the updated_at/on attributes. - # - # Examples: - # - # product.touch! # updates updated_at - # product.touch!(:designed_at) # updates the designed_at attribute - def touch!(attribute = nil) - raise ActiveRecord::RecordInvalid.new(self) unless valid? - touch(attribute) + + save! end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 6c3596347d..24b237a72b 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -30,24 +30,6 @@ class TimestampTest < ActiveRecord::TestCase assert @previously_updated_at != @developer.updated_at end - def test_touching_a_record_updates_its_timestamp_even_if_object_instance_is_invalid - @developer.name = nil - @developer.touch - - assert @previously_updated_at != @developer.updated_at - end - - def test_touch_bang_a_record_updates_its_timestamp - @developer.touch! - - assert @previously_updated_at != @developer.updated_at - end - - def test_touch_banging_a_record_fails_if_object_instance_is_invalid - @developer.name = nil - assert_raise(ActiveRecord::RecordInvalid) { @developer.touch! } - end - def test_touching_a_different_attribute previously_created_at = @developer.created_at @developer.touch(:created_at) @@ -55,13 +37,6 @@ class TimestampTest < ActiveRecord::TestCase assert previously_created_at != @developer.created_at end - def test_touch_banging_a_different_attribute - previously_created_at = @developer.created_at - @developer.touch!(:created_at) - - assert previously_created_at != @developer.created_at - end - def test_saving_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_update_the_parent_updated_at pet = Pet.first owner = pet.owner -- cgit v1.2.3 From 41e5c7ed44fedb95636ef9b7a792c46ea03309bd Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Sat, 27 Mar 2010 12:57:41 +0430 Subject: primary_key now supports :limit. [#876 state:resolved] Signed-off-by: wycats --- .../abstract/schema_definitions.rb | 8 ++--- .../connection_adapters/mysql_adapter.rb | 26 ++++++++------ activerecord/lib/active_record/schema_dumper.rb | 42 ++++++++++++---------- activerecord/test/cases/schema_dumper_test.rb | 11 ++++-- activerecord/test/schema/schema.rb | 4 +++ 5 files changed, 57 insertions(+), 34 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 64faaef4a0..5e29baf51f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -274,7 +274,7 @@ module ActiveRecord column_options = {} column_options[:null] = null unless null.nil? column_options[:default] = default unless default.nil? - add_column_options!(column_sql, column_options) unless type.to_sym == :primary_key + add_column_options!(column_sql, column_options) column_sql end @@ -334,8 +334,8 @@ module ActiveRecord # Appends a primary key definition to the table definition. # Can be called multiple times, but this is probably not a good idea. - def primary_key(name) - column(name, :primary_key) + def primary_key(name, options = {}) + column(name, :primary_key, options) end # Returns a ColumnDefinition for the column with name +name+. @@ -357,7 +357,7 @@ module ActiveRecord # # Available options are (none of these exists by default): # * :limit - - # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary and :integer columns. + # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary, :integer and :primary_key columns. # * :default - # The column's default value. Use nil for NULL. # * :null - diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 521bd810d0..12ca02924a 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -183,7 +183,7 @@ module ActiveRecord QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze NATIVE_DATABASE_TYPES = { - :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze, + :primary_key => { :name => "DEFAULT NULL auto_increment PRIMARY KEY", :limit => 4 }, :string => { :name => "varchar", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "int", :limit => 4 }, @@ -541,15 +541,21 @@ module ActiveRecord # Maps logical Rails types to MySQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil) - return super unless type.to_s == 'integer' - - case limit - when 1; 'tinyint' - when 2; 'smallint' - when 3; 'mediumint' - when nil, 4, 11; 'int(11)' # compatibility with MySQL default - when 5..8; 'bigint' - else raise(ActiveRecordError, "No integer type has byte size #{limit}") + case type.to_s + when 'primary_key': + native = native_database_types[:primary_key] + return type_to_sql('integer', limit) + ' ' + native[:name] + when 'integer': + case limit + when 1; 'tinyint' + when 2; 'smallint' + when 3; 'mediumint' + when nil, 4, 11; 'int(11)' # compatibility with MySQL default + when 5..8; 'bigint' + else raise(ActiveRecordError, "No integer type has byte size #{limit}") + end + else + super end end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index c8e1b4f53a..22cd1cbe0c 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -76,6 +76,7 @@ HEADER def table(table, stream) columns = @connection.columns(table) begin + column_specs = columns.dup tbl = StringIO.new # first dump primary key column @@ -86,9 +87,12 @@ HEADER end tbl.print " create_table #{table.inspect}" - if columns.detect { |c| c.name == pk } - if pk != 'id' - tbl.print %Q(, :primary_key => "#{pk}") + if pkc = column_specs.detect { |c| c.name == pk } + if pkc.limit != @types[:primary_key][:limit] + tbl.print ", :id => false" + else + column_specs.delete(pkc) + tbl.print %Q(, :primary_key => "#{pk}") if pk != 'id' end else tbl.print ", :id => false" @@ -97,27 +101,29 @@ HEADER tbl.puts " do |t|" # then dump all non-primary key columns - column_specs = columns.map do |column| + column_specs.map! do |column| raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil? - next if column.name == pk spec = {} spec[:name] = column.name.inspect - - # AR has an optimisation which handles zero-scale decimals as integers. This - # code ensures that the dumper still dumps the column as a decimal. - spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } - 'decimal' - else - column.type.to_s - end spec[:limit] = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal' - spec[:precision] = column.precision.inspect if !column.precision.nil? - spec[:scale] = column.scale.inspect if !column.scale.nil? - spec[:null] = 'false' if !column.null - spec[:default] = default_string(column.default) if column.has_default? + if column.name == pk + spec[:type] = 'primary_key' + else + # AR has an optimisation which handles zero-scale decimals as integers. This + # code ensures that the dumper still dumps the column as a decimal. + spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } + 'decimal' + else + column.type.to_s + end + spec[:precision] = column.precision.inspect if !column.precision.nil? + spec[:scale] = column.scale.inspect if !column.scale.nil? + spec[:null] = 'false' if !column.null + spec[:default] = default_string(column.default) if column.has_default? + end (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")} spec - end.compact + end # find all migration keys used in this table keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map(&:keys).flatten diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 1c43e3c5b5..95039289c4 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -45,7 +45,7 @@ class SchemaDumperTest < ActiveRecord::TestCase next if column_set.empty? lengths = column_set.map do |column| - if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean)\s+"/) + if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean|primary_key)\s+"/) match[0].length end end @@ -169,6 +169,13 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r(:primary_key => "movieid"), match[1], "non-standard primary key not preserved" end + def test_mysql_schema_dump_should_honor_primary_keys_limits + output = standard_dump + match = output.match(%r{create_table "primary_key_limit",.*?:id => false\b.*? do (.*?)\bend$}m) + assert_not_nil(match, output) + assert_match %r(t.primary_key\s+"id",\s+:limit => \d+$), match[1], "limit option not found on primary key" + end + if current_adapter?(:MysqlAdapter) def test_schema_dump_should_not_add_default_value_for_mysql_text_field output = standard_dump @@ -211,7 +218,7 @@ class SchemaDumperTest < ActiveRecord::TestCase if current_adapter?(:OracleAdapter) assert_match %r{t.integer\s+"atoms_in_universe",\s+:precision => 38,\s+:scale => 0}, output else - assert_match %r{t.decimal\s+"atoms_in_universe",\s+:precision => 55,\s+:scale => 0}, output + assert_match %r{t.decimal\s+"atoms_in_universe",\s+:limit => 55,\s+:precision => 55,\s+:scale => 0}, output end end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index bec4291457..a1932ad16a 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -394,6 +394,10 @@ ActiveRecord::Schema.define do t.integer :price end + create_table :primary_key_limit, :force => true, :id => false do |t| + t.primary_key :id, :limit => 8 + end + create_table :projects, :force => true do |t| t.string :name t.string :type -- cgit v1.2.3 From 3172db12e4e7f6abab8ddd25f7911d29a5b65ea0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 18 Mar 2010 12:16:54 -0700 Subject: avoiding a few closure references by evaling. [#4223 state:resolved] Signed-off-by: wycats --- activerecord/lib/active_record/associations.rb | 30 +++++++++++++++----------- 1 file changed, 18 insertions(+), 12 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 726e6b8b81..d623ddb915 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1545,15 +1545,19 @@ module ActiveRecord case name when :destroy, :delete - define_method(method_name) do - association = send(reflection.name) - association.send(name) if association - end + class_eval <<-eoruby, __FILE__, __LINE__ + 1 + def #{method_name} + association = #{reflection.name} + association.#{name} if association + end + eoruby when :nullify - define_method(method_name) do - association = send(reflection.name) - association.update_attribute(reflection.primary_key_name, nil) if association - end + class_eval <<-eoruby, __FILE__, __LINE__ + 1 + def #{method_name} + association = #{reflection.name} + association.update_attribute(#{reflection.primary_key_name.inspect}, nil) if association + end + eoruby else raise ArgumentError, "The :dependent option expects either :destroy, :delete or :nullify (#{reflection.options[:dependent].inspect})" end @@ -1571,10 +1575,12 @@ module ActiveRecord end method_name = :"belongs_to_dependent_#{name}_for_#{reflection.name}" - define_method(method_name) do - association = send(reflection.name) - association.send(name) if association - end + class_eval <<-eoruby, __FILE__, __LINE__ + 1 + def #{method_name} + association = #{reflection.name} + association.#{name} if association + end + eoruby after_destroy method_name end end -- cgit v1.2.3 From 0cb3311d06c02649fb7444c34b6fdf2214ab85f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sat, 27 Mar 2010 11:05:21 +0100 Subject: Revert "primary_key now supports :limit. [#876 state:resolved]" since it broke AR test suite. This reverts commit 41e5c7ed44fedb95636ef9b7a792c46ea03309bd. --- .../abstract/schema_definitions.rb | 8 ++--- .../connection_adapters/mysql_adapter.rb | 26 ++++++-------- activerecord/lib/active_record/schema_dumper.rb | 42 ++++++++++------------ activerecord/test/cases/schema_dumper_test.rb | 11 ++---- activerecord/test/schema/schema.rb | 4 --- 5 files changed, 34 insertions(+), 57 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 5e29baf51f..64faaef4a0 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -274,7 +274,7 @@ module ActiveRecord column_options = {} column_options[:null] = null unless null.nil? column_options[:default] = default unless default.nil? - add_column_options!(column_sql, column_options) + add_column_options!(column_sql, column_options) unless type.to_sym == :primary_key column_sql end @@ -334,8 +334,8 @@ module ActiveRecord # Appends a primary key definition to the table definition. # Can be called multiple times, but this is probably not a good idea. - def primary_key(name, options = {}) - column(name, :primary_key, options) + def primary_key(name) + column(name, :primary_key) end # Returns a ColumnDefinition for the column with name +name+. @@ -357,7 +357,7 @@ module ActiveRecord # # Available options are (none of these exists by default): # * :limit - - # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary, :integer and :primary_key columns. + # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary and :integer columns. # * :default - # The column's default value. Use nil for NULL. # * :null - diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 12ca02924a..521bd810d0 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -183,7 +183,7 @@ module ActiveRecord QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze NATIVE_DATABASE_TYPES = { - :primary_key => { :name => "DEFAULT NULL auto_increment PRIMARY KEY", :limit => 4 }, + :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze, :string => { :name => "varchar", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "int", :limit => 4 }, @@ -541,21 +541,15 @@ module ActiveRecord # Maps logical Rails types to MySQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil) - case type.to_s - when 'primary_key': - native = native_database_types[:primary_key] - return type_to_sql('integer', limit) + ' ' + native[:name] - when 'integer': - case limit - when 1; 'tinyint' - when 2; 'smallint' - when 3; 'mediumint' - when nil, 4, 11; 'int(11)' # compatibility with MySQL default - when 5..8; 'bigint' - else raise(ActiveRecordError, "No integer type has byte size #{limit}") - end - else - super + return super unless type.to_s == 'integer' + + case limit + when 1; 'tinyint' + when 2; 'smallint' + when 3; 'mediumint' + when nil, 4, 11; 'int(11)' # compatibility with MySQL default + when 5..8; 'bigint' + else raise(ActiveRecordError, "No integer type has byte size #{limit}") end end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 22cd1cbe0c..c8e1b4f53a 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -76,7 +76,6 @@ HEADER def table(table, stream) columns = @connection.columns(table) begin - column_specs = columns.dup tbl = StringIO.new # first dump primary key column @@ -87,12 +86,9 @@ HEADER end tbl.print " create_table #{table.inspect}" - if pkc = column_specs.detect { |c| c.name == pk } - if pkc.limit != @types[:primary_key][:limit] - tbl.print ", :id => false" - else - column_specs.delete(pkc) - tbl.print %Q(, :primary_key => "#{pk}") if pk != 'id' + if columns.detect { |c| c.name == pk } + if pk != 'id' + tbl.print %Q(, :primary_key => "#{pk}") end else tbl.print ", :id => false" @@ -101,29 +97,27 @@ HEADER tbl.puts " do |t|" # then dump all non-primary key columns - column_specs.map! do |column| + column_specs = columns.map do |column| raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil? + next if column.name == pk spec = {} spec[:name] = column.name.inspect + + # AR has an optimisation which handles zero-scale decimals as integers. This + # code ensures that the dumper still dumps the column as a decimal. + spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } + 'decimal' + else + column.type.to_s + end spec[:limit] = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal' - if column.name == pk - spec[:type] = 'primary_key' - else - # AR has an optimisation which handles zero-scale decimals as integers. This - # code ensures that the dumper still dumps the column as a decimal. - spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } - 'decimal' - else - column.type.to_s - end - spec[:precision] = column.precision.inspect if !column.precision.nil? - spec[:scale] = column.scale.inspect if !column.scale.nil? - spec[:null] = 'false' if !column.null - spec[:default] = default_string(column.default) if column.has_default? - end + spec[:precision] = column.precision.inspect if !column.precision.nil? + spec[:scale] = column.scale.inspect if !column.scale.nil? + spec[:null] = 'false' if !column.null + spec[:default] = default_string(column.default) if column.has_default? (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")} spec - end + end.compact # find all migration keys used in this table keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map(&:keys).flatten diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 95039289c4..1c43e3c5b5 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -45,7 +45,7 @@ class SchemaDumperTest < ActiveRecord::TestCase next if column_set.empty? lengths = column_set.map do |column| - if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean|primary_key)\s+"/) + if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean)\s+"/) match[0].length end end @@ -169,13 +169,6 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r(:primary_key => "movieid"), match[1], "non-standard primary key not preserved" end - def test_mysql_schema_dump_should_honor_primary_keys_limits - output = standard_dump - match = output.match(%r{create_table "primary_key_limit",.*?:id => false\b.*? do (.*?)\bend$}m) - assert_not_nil(match, output) - assert_match %r(t.primary_key\s+"id",\s+:limit => \d+$), match[1], "limit option not found on primary key" - end - if current_adapter?(:MysqlAdapter) def test_schema_dump_should_not_add_default_value_for_mysql_text_field output = standard_dump @@ -218,7 +211,7 @@ class SchemaDumperTest < ActiveRecord::TestCase if current_adapter?(:OracleAdapter) assert_match %r{t.integer\s+"atoms_in_universe",\s+:precision => 38,\s+:scale => 0}, output else - assert_match %r{t.decimal\s+"atoms_in_universe",\s+:limit => 55,\s+:precision => 55,\s+:scale => 0}, output + assert_match %r{t.decimal\s+"atoms_in_universe",\s+:precision => 55,\s+:scale => 0}, output end end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index a1932ad16a..bec4291457 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -394,10 +394,6 @@ ActiveRecord::Schema.define do t.integer :price end - create_table :primary_key_limit, :force => true, :id => false do |t| - t.primary_key :id, :limit => 8 - end - create_table :projects, :force => true do |t| t.string :name t.string :type -- cgit v1.2.3 From faeca694b3d4afebf6b623b493e86731e773c462 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Sat, 27 Mar 2010 15:17:07 +0430 Subject: primary_key now supports :limit for MySQL Signed-off-by: wycats --- .../abstract/schema_definitions.rb | 8 ++--- .../connection_adapters/mysql_adapter.rb | 26 ++++++++------ activerecord/lib/active_record/schema_dumper.rb | 42 ++++++++++++---------- activerecord/test/cases/schema_dumper_test.rb | 11 ++++-- activerecord/test/schema/schema.rb | 4 +++ 5 files changed, 57 insertions(+), 34 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 64faaef4a0..5e29baf51f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -274,7 +274,7 @@ module ActiveRecord column_options = {} column_options[:null] = null unless null.nil? column_options[:default] = default unless default.nil? - add_column_options!(column_sql, column_options) unless type.to_sym == :primary_key + add_column_options!(column_sql, column_options) column_sql end @@ -334,8 +334,8 @@ module ActiveRecord # Appends a primary key definition to the table definition. # Can be called multiple times, but this is probably not a good idea. - def primary_key(name) - column(name, :primary_key) + def primary_key(name, options = {}) + column(name, :primary_key, options) end # Returns a ColumnDefinition for the column with name +name+. @@ -357,7 +357,7 @@ module ActiveRecord # # Available options are (none of these exists by default): # * :limit - - # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary and :integer columns. + # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary, :integer and :primary_key columns. # * :default - # The column's default value. Use nil for NULL. # * :null - diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 521bd810d0..8a19c7af00 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -183,7 +183,7 @@ module ActiveRecord QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze NATIVE_DATABASE_TYPES = { - :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze, + :primary_key => { :name => "DEFAULT NULL auto_increment PRIMARY KEY", :limit => 4 }, :string => { :name => "varchar", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "int", :limit => 4 }, @@ -541,15 +541,21 @@ module ActiveRecord # Maps logical Rails types to MySQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil) - return super unless type.to_s == 'integer' - - case limit - when 1; 'tinyint' - when 2; 'smallint' - when 3; 'mediumint' - when nil, 4, 11; 'int(11)' # compatibility with MySQL default - when 5..8; 'bigint' - else raise(ActiveRecordError, "No integer type has byte size #{limit}") + case type.to_s + when 'primary_key' + native = native_database_types[:primary_key] + return type_to_sql('integer', limit) + ' ' + native[:name] + when 'integer' + case limit + when 1; 'tinyint' + when 2; 'smallint' + when 3; 'mediumint' + when nil, 4, 11; 'int(11)' # compatibility with MySQL default + when 5..8; 'bigint' + else raise(ActiveRecordError, "No integer type has byte size #{limit}") + end + else + super end end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index c8e1b4f53a..22cd1cbe0c 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -76,6 +76,7 @@ HEADER def table(table, stream) columns = @connection.columns(table) begin + column_specs = columns.dup tbl = StringIO.new # first dump primary key column @@ -86,9 +87,12 @@ HEADER end tbl.print " create_table #{table.inspect}" - if columns.detect { |c| c.name == pk } - if pk != 'id' - tbl.print %Q(, :primary_key => "#{pk}") + if pkc = column_specs.detect { |c| c.name == pk } + if pkc.limit != @types[:primary_key][:limit] + tbl.print ", :id => false" + else + column_specs.delete(pkc) + tbl.print %Q(, :primary_key => "#{pk}") if pk != 'id' end else tbl.print ", :id => false" @@ -97,27 +101,29 @@ HEADER tbl.puts " do |t|" # then dump all non-primary key columns - column_specs = columns.map do |column| + column_specs.map! do |column| raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil? - next if column.name == pk spec = {} spec[:name] = column.name.inspect - - # AR has an optimisation which handles zero-scale decimals as integers. This - # code ensures that the dumper still dumps the column as a decimal. - spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } - 'decimal' - else - column.type.to_s - end spec[:limit] = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal' - spec[:precision] = column.precision.inspect if !column.precision.nil? - spec[:scale] = column.scale.inspect if !column.scale.nil? - spec[:null] = 'false' if !column.null - spec[:default] = default_string(column.default) if column.has_default? + if column.name == pk + spec[:type] = 'primary_key' + else + # AR has an optimisation which handles zero-scale decimals as integers. This + # code ensures that the dumper still dumps the column as a decimal. + spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } + 'decimal' + else + column.type.to_s + end + spec[:precision] = column.precision.inspect if !column.precision.nil? + spec[:scale] = column.scale.inspect if !column.scale.nil? + spec[:null] = 'false' if !column.null + spec[:default] = default_string(column.default) if column.has_default? + end (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")} spec - end.compact + end # find all migration keys used in this table keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map(&:keys).flatten diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 1c43e3c5b5..f79c3f0c3d 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -45,7 +45,7 @@ class SchemaDumperTest < ActiveRecord::TestCase next if column_set.empty? lengths = column_set.map do |column| - if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean)\s+"/) + if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean|primary_key)\s+"/) match[0].length end end @@ -186,6 +186,13 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r{t.text\s+"medium_text",\s+:limit => 16777215$}, output assert_match %r{t.text\s+"long_text",\s+:limit => 2147483647$}, output end + + def test_mysql_schema_dump_should_honor_primary_keys_limits + output = standard_dump + match = output.match(%r{create_table "primary_key_limit",.*?:id => false\b.*? do (.*?)\bend$}m) + assert_not_nil(match, output) + assert_match %r(t.primary_key\s+"id",\s+:limit => \d+$), match[1], "limit option not found on primary key" + end end def test_schema_dump_includes_decimal_options @@ -211,7 +218,7 @@ class SchemaDumperTest < ActiveRecord::TestCase if current_adapter?(:OracleAdapter) assert_match %r{t.integer\s+"atoms_in_universe",\s+:precision => 38,\s+:scale => 0}, output else - assert_match %r{t.decimal\s+"atoms_in_universe",\s+:precision => 55,\s+:scale => 0}, output + assert_match %r{t.decimal\s+"atoms_in_universe",\s+:limit => 55,\s+:precision => 55,\s+:scale => 0}, output end end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index bec4291457..a1932ad16a 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -394,6 +394,10 @@ ActiveRecord::Schema.define do t.integer :price end + create_table :primary_key_limit, :force => true, :id => false do |t| + t.primary_key :id, :limit => 8 + end + create_table :projects, :force => true do |t| t.string :name t.string :type -- cgit v1.2.3 From ff522cf4bcb31420baee62aa3c24c98959d80cdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sat, 27 Mar 2010 14:38:48 +0100 Subject: Revert "primary_key now supports :limit for MySQL". Break Sam Ruby app. To reproduce, start a new application, create a scaffold and run test suite. [#876 state:open] This reverts commit faeca694b3d4afebf6b623b493e86731e773c462. --- .../abstract/schema_definitions.rb | 8 ++--- .../connection_adapters/mysql_adapter.rb | 26 ++++++-------- activerecord/lib/active_record/schema_dumper.rb | 42 ++++++++++------------ activerecord/test/cases/schema_dumper_test.rb | 11 ++---- activerecord/test/schema/schema.rb | 4 --- 5 files changed, 34 insertions(+), 57 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 5e29baf51f..64faaef4a0 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -274,7 +274,7 @@ module ActiveRecord column_options = {} column_options[:null] = null unless null.nil? column_options[:default] = default unless default.nil? - add_column_options!(column_sql, column_options) + add_column_options!(column_sql, column_options) unless type.to_sym == :primary_key column_sql end @@ -334,8 +334,8 @@ module ActiveRecord # Appends a primary key definition to the table definition. # Can be called multiple times, but this is probably not a good idea. - def primary_key(name, options = {}) - column(name, :primary_key, options) + def primary_key(name) + column(name, :primary_key) end # Returns a ColumnDefinition for the column with name +name+. @@ -357,7 +357,7 @@ module ActiveRecord # # Available options are (none of these exists by default): # * :limit - - # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary, :integer and :primary_key columns. + # Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary and :integer columns. # * :default - # The column's default value. Use nil for NULL. # * :null - diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 8a19c7af00..521bd810d0 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -183,7 +183,7 @@ module ActiveRecord QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze NATIVE_DATABASE_TYPES = { - :primary_key => { :name => "DEFAULT NULL auto_increment PRIMARY KEY", :limit => 4 }, + :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze, :string => { :name => "varchar", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "int", :limit => 4 }, @@ -541,21 +541,15 @@ module ActiveRecord # Maps logical Rails types to MySQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil) - case type.to_s - when 'primary_key' - native = native_database_types[:primary_key] - return type_to_sql('integer', limit) + ' ' + native[:name] - when 'integer' - case limit - when 1; 'tinyint' - when 2; 'smallint' - when 3; 'mediumint' - when nil, 4, 11; 'int(11)' # compatibility with MySQL default - when 5..8; 'bigint' - else raise(ActiveRecordError, "No integer type has byte size #{limit}") - end - else - super + return super unless type.to_s == 'integer' + + case limit + when 1; 'tinyint' + when 2; 'smallint' + when 3; 'mediumint' + when nil, 4, 11; 'int(11)' # compatibility with MySQL default + when 5..8; 'bigint' + else raise(ActiveRecordError, "No integer type has byte size #{limit}") end end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 22cd1cbe0c..c8e1b4f53a 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -76,7 +76,6 @@ HEADER def table(table, stream) columns = @connection.columns(table) begin - column_specs = columns.dup tbl = StringIO.new # first dump primary key column @@ -87,12 +86,9 @@ HEADER end tbl.print " create_table #{table.inspect}" - if pkc = column_specs.detect { |c| c.name == pk } - if pkc.limit != @types[:primary_key][:limit] - tbl.print ", :id => false" - else - column_specs.delete(pkc) - tbl.print %Q(, :primary_key => "#{pk}") if pk != 'id' + if columns.detect { |c| c.name == pk } + if pk != 'id' + tbl.print %Q(, :primary_key => "#{pk}") end else tbl.print ", :id => false" @@ -101,29 +97,27 @@ HEADER tbl.puts " do |t|" # then dump all non-primary key columns - column_specs.map! do |column| + column_specs = columns.map do |column| raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil? + next if column.name == pk spec = {} spec[:name] = column.name.inspect + + # AR has an optimisation which handles zero-scale decimals as integers. This + # code ensures that the dumper still dumps the column as a decimal. + spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } + 'decimal' + else + column.type.to_s + end spec[:limit] = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal' - if column.name == pk - spec[:type] = 'primary_key' - else - # AR has an optimisation which handles zero-scale decimals as integers. This - # code ensures that the dumper still dumps the column as a decimal. - spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } - 'decimal' - else - column.type.to_s - end - spec[:precision] = column.precision.inspect if !column.precision.nil? - spec[:scale] = column.scale.inspect if !column.scale.nil? - spec[:null] = 'false' if !column.null - spec[:default] = default_string(column.default) if column.has_default? - end + spec[:precision] = column.precision.inspect if !column.precision.nil? + spec[:scale] = column.scale.inspect if !column.scale.nil? + spec[:null] = 'false' if !column.null + spec[:default] = default_string(column.default) if column.has_default? (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")} spec - end + end.compact # find all migration keys used in this table keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map(&:keys).flatten diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index f79c3f0c3d..1c43e3c5b5 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -45,7 +45,7 @@ class SchemaDumperTest < ActiveRecord::TestCase next if column_set.empty? lengths = column_set.map do |column| - if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean|primary_key)\s+"/) + if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean)\s+"/) match[0].length end end @@ -186,13 +186,6 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r{t.text\s+"medium_text",\s+:limit => 16777215$}, output assert_match %r{t.text\s+"long_text",\s+:limit => 2147483647$}, output end - - def test_mysql_schema_dump_should_honor_primary_keys_limits - output = standard_dump - match = output.match(%r{create_table "primary_key_limit",.*?:id => false\b.*? do (.*?)\bend$}m) - assert_not_nil(match, output) - assert_match %r(t.primary_key\s+"id",\s+:limit => \d+$), match[1], "limit option not found on primary key" - end end def test_schema_dump_includes_decimal_options @@ -218,7 +211,7 @@ class SchemaDumperTest < ActiveRecord::TestCase if current_adapter?(:OracleAdapter) assert_match %r{t.integer\s+"atoms_in_universe",\s+:precision => 38,\s+:scale => 0}, output else - assert_match %r{t.decimal\s+"atoms_in_universe",\s+:limit => 55,\s+:precision => 55,\s+:scale => 0}, output + assert_match %r{t.decimal\s+"atoms_in_universe",\s+:precision => 55,\s+:scale => 0}, output end end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index a1932ad16a..bec4291457 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -394,10 +394,6 @@ ActiveRecord::Schema.define do t.integer :price end - create_table :primary_key_limit, :force => true, :id => false do |t| - t.primary_key :id, :limit => 8 - end - create_table :projects, :force => true do |t| t.string :name t.string :type -- cgit v1.2.3 From 6c2a0675f11a9b5b8e88ed7dbccd65cb51be8029 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Sun, 28 Mar 2010 11:01:15 +0430 Subject: When creating database with rake, create schemas in schema_search_path if it doesn't exist. --- .../connection_adapters/postgresql_adapter.rb | 21 +++++++++++++++++++++ .../lib/active_record/railties/databases.rake | 6 ++++++ .../test/cases/active_schema_test_postgresql.rb | 7 +++++++ activerecord/test/cases/adapter_test.rb | 6 ++++++ 4 files changed, 40 insertions(+) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index c9a5f00dfd..8f71c7e144 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -651,6 +651,27 @@ module ActiveRecord end end + # Creates a schema for the given user + # + # Example: + # create_schema('products', 'postgres') + def create_schema(schema_name, pg_username) + execute("CREATE SCHEMA \"#{schema_name}\" AUTHORIZATION \"#{pg_username}\"") + end + + # Drops a schema + # + # Example: + # drop_schema('products', 'postgres') + def drop_schema(schema_name) + execute("DROP SCHEMA \"#{schema_name}\"") + end + + # Returns an array of all schemas in the database + def all_schemas + query('SELECT schema_name FROM information_schema.schemata').flatten + end + # Returns the list of all tables in the schema search path or a specified schema. def tables(name = nil) query(<<-SQL, name).map { |row| row[0] } diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 0229793a9a..06485b9033 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -85,8 +85,14 @@ namespace :db do end when 'postgresql' @encoding = config[:encoding] || ENV['CHARSET'] || 'utf8' + schema_search_path = config['schema_search_path'] || 'public' + first_in_schema_search_path = schema_search_path.split(',').first.strip begin ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public')) + unless ActiveRecord::Base.connection.all_schemas.include?(first_in_schema_search_path) + ActiveRecord::Base.connection.create_schema(first_in_schema_search_path, config['username']) + $stderr.puts "Schema #{first_in_schema_search_path} has been created." + end ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding)) ActiveRecord::Base.establish_connection(config) rescue diff --git a/activerecord/test/cases/active_schema_test_postgresql.rb b/activerecord/test/cases/active_schema_test_postgresql.rb index af80f724f2..67c662d694 100644 --- a/activerecord/test/cases/active_schema_test_postgresql.rb +++ b/activerecord/test/cases/active_schema_test_postgresql.rb @@ -17,6 +17,13 @@ class PostgresqlActiveSchemaTest < Test::Unit::TestCase assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1) end + def test_create_schema + assert_equal %(CREATE SCHEMA "rizwan" AUTHORIZATION "postgres"), create_schema(:rizwan, :postgres) + end + + def test_drop_schema + assert_equal %(DROP SCHEMA "rizwan"), drop_schema(:rizwan) + end private def method_missing(method_symbol, *arguments) ActiveRecord::Base.connection.send(method_symbol, *arguments) diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 9b28766405..9f78ae008c 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -81,6 +81,12 @@ class AdapterTest < ActiveRecord::TestCase def test_encoding assert_not_nil @connection.encoding end + + def test_all_schemas + @connection.create_schema(:test_schema, :postgres) + assert @connection.all_schemas.include?('test_schema') + @connection.drop_schema(:test_schema) + end end def test_table_alias -- cgit v1.2.3 From 66d57d7ba83df52ff1e0485c89f6192c2f84c6b8 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Sun, 28 Mar 2010 11:10:35 +0430 Subject: Oops, a docfix. --- .../lib/active_record/connection_adapters/postgresql_adapter.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 8f71c7e144..31d5266da8 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -662,7 +662,7 @@ module ActiveRecord # Drops a schema # # Example: - # drop_schema('products', 'postgres') + # drop_schema('products') def drop_schema(schema_name) execute("DROP SCHEMA \"#{schema_name}\"") end -- cgit v1.2.3