diff options
Diffstat (limited to 'activerecord')
110 files changed, 868 insertions, 824 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 8980a1d874..8875b7ae25 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,117 @@ +* `nil` as a value for a binary column in a query no longer logs as + "<NULL binary data>", and instead logs as just "nil". + + *Sean Griffin* + +* `attribute_will_change!` will no longer cause non-persistable attributes to + be sent to the database. + + Fixes #18407. + + *Sean Griffin* + +* Remove support for the `protected_attributes` gem. + + *Carlos Antonio da Silva*, *Roberto Miranda* + +* Fix accessing of fixtures having non-string labels like Fixnum. + + *Prathamesh Sonpatki* + +* Remove deprecated support to preload instance-dependent associations. + + *Yves Senn* + +* Remove deprecated support for PostgreSQL ranges with exclusive lower bounds. + + *Yves Senn* + +* Remove deprecation when modifying a relation with cached arel. + This raises an `ImmutableRelation` error instead. + + *Yves Senn* + +* Added `ActiveRecord::SecureToken` in order to encapsulate generation of + unique tokens for attributes in a model using `SecureRandom`. + + *Roberto Miranda* + +* Change the behavior of boolean columns to be closer to Ruby's semantics. + + Before this change we had a small set of "truthy", and all others are "falsy". + + Now, we have a small set of "falsy" values and all others are "truthy" matching + Ruby's semantics. + + *Rafael Mendonça França* + +* Deprecate `ActiveRecord::Base.errors_in_transactional_callbacks=`. + + *Rafael Mendonça França* + +* Change transaction callbacks to not swallow errors. + + Before this change any errors raised inside a transaction callback + were getting rescued and printed in the logs. + + Now these errors are not rescued anymore and just bubble up, as the other callbacks. + + *Rafael Mendonça França* + +* Remove deprecated `sanitize_sql_hash_for_conditions`. + + *Rafael Mendonça França* + +* Remove deprecated `Reflection#source_macro`. + + *Rafael Mendonça França* + +* Remove deprecated `symbolized_base_class` and `symbolized_sti_name`. + + *Rafael Mendonça França* + +* Remove deprecated `ActiveRecord::Base.disable_implicit_join_references=`. + + *Rafael Mendonça França* + +* Remove deprecated access to connection specification using a string accessor. + + Now all strings will be handled as a URL. + + *Rafael Mendonça França* + +* Change the default `null` value for `timestamps` to `false`. + + *Rafael Mendonça França* + +* Return an array of pools from `connection_pools`. + + *Rafael Mendonça França* + +* Return a null column from `column_for_attribute` when no column exists. + + *Rafael Mendonça França* + +* Remove deprecated `serialized_attributes`. + + *Rafael Mendonça França* + +* Remove deprecated automatic counter caches on `has_many :through`. + + *Rafael Mendonça França* + +* Change the way in which callback chains can be halted. + + The preferred method to halt a callback chain from now on is to explicitly + `throw(:abort)`. + In the past, returning `false` in an ActiveRecord `before_` callback had the + side effect of halting the callback chain. + This is not recommended anymore and, depending on the value of the + `config.active_support.halt_callback_chains_on_return_false` option, will + either not work at all or display a deprecation warning. + + *claudiob* + * Clear query cache on rollback. *Florian Weingarten* @@ -176,7 +290,7 @@ This option enables to define the column name of associated object's type for polymorphic associations. - *Ulisses Almeida, Kassio Borges* + *Ulisses Almeida*, *Kassio Borges* * Remove deprecated behavior allowing nested arrays to be passed as query values. diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 2eec62846b..d9d47c3d99 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -67,6 +67,7 @@ module ActiveRecord autoload :Transactions autoload :Translation autoload :Validations + autoload :SecureToken eager_autoload do autoload :ActiveRecordError, 'active_record/errors' diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 14af55f327..35bc09bb10 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1245,6 +1245,10 @@ module ActiveRecord # that is the inverse of this <tt>has_many</tt> association. Does not work in combination # with <tt>:through</tt> or <tt>:as</tt> options. # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. + # [:extend] + # Specifies a module or array of modules that will be extended into the association object returned. + # Useful for defining methods on associations, especially when they should be shared between multiple + # association objects. # # Option examples: # has_many :comments, -> { order "posted_on" } diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index d7f655d00c..2a782c06d0 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -17,7 +17,7 @@ module ActiveRecord unless empty? record = klass.human_attribute_name(reflection.name).downcase owner.errors.add(:base, :"restrict_dependent_destroy.many", record: record) - false + throw(:abort) end else diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 7a050ca224..f1e784d771 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/string/filters' - module ActiveRecord # = Active Record Has Many Through Association module Associations @@ -49,16 +47,7 @@ module ActiveRecord end save_through_record(record) - if has_cached_counter? && !through_reflection_updates_counter_cache? - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Automatic updating of counter caches on through associations has been - deprecated, and will be removed in Rails 5. Instead, please set the - appropriate `counter_cache` options on the `has_many` and `belongs_to` - for your associations to #{through_reflection.name}. - MSG - update_counter_in_database(1) - end record end @@ -211,11 +200,6 @@ module ActiveRecord def invertible_for?(record) false end - - def through_reflection_updates_counter_cache? - counter_name = cached_counter_attribute_name - inverse_updates_counter_named?(counter_name, through_reflection) - end end end end diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb index 74b8c53758..41a75b820e 100644 --- a/activerecord/lib/active_record/associations/has_one_association.rb +++ b/activerecord/lib/active_record/associations/has_one_association.rb @@ -13,7 +13,7 @@ module ActiveRecord if load_target record = klass.human_attribute_name(reflection.name).downcase owner.errors.add(:base, :"restrict_dependent_destroy.one", record: record) - false + throw(:abort) end else diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index a6e1a24360..afcaa5d55a 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -104,11 +104,11 @@ module ActiveRecord end def association_key_type - @klass.type_for_attribute(association_key_name.to_s).type + @klass.column_for_attribute(association_key_name).type end def owner_key_type - @model.type_for_attribute(owner_key_name.to_s).type + @model.column_for_attribute(owner_key_name).type end def load_slices(slices) diff --git a/activerecord/lib/active_record/attribute.rb b/activerecord/lib/active_record/attribute.rb index 88536eaac0..51e4fae62e 100644 --- a/activerecord/lib/active_record/attribute.rb +++ b/activerecord/lib/active_record/attribute.rb @@ -74,6 +74,10 @@ module ActiveRecord true end + def came_from_user? + false + end + def ==(other) self.class == other.class && name == other.name && @@ -99,6 +103,10 @@ module ActiveRecord def type_cast(value) type.type_cast_from_user(value) end + + def came_from_user? + true + end end class WithCastValue < Attribute # :nodoc: diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index b7edac791e..8f165fb1dc 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -192,7 +192,8 @@ module ActiveRecord end # Returns the column object for the named attribute. - # Returns nil if the named attribute does not exist. + # Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the + # named attribute does not exist. # # class Person < ActiveRecord::Base # end @@ -202,17 +203,12 @@ module ActiveRecord # # => #<ActiveRecord::ConnectionAdapters::Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...> # # person.column_for_attribute(:nothing) - # # => nil + # # => #<ActiveRecord::ConnectionAdapters::NullColumn:0xXXX @name=nil, @sql_type=nil, @cast_type=#<Type::Value>, ...> def column_for_attribute(name) - column = columns_hash[name.to_s] - if column.nil? - ActiveSupport::Deprecation.warn(<<-MSG.squish) - `#column_for_attribute` will return a null object for non-existent - columns in Rails 5. Use `#has_attribute?` if you need to check for - an attribute's existence. - MSG + name = name.to_s + columns_hash.fetch(name) do + ConnectionAdapters::NullColumn.new(name) end - column end end diff --git a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb index fd61febd57..56c1898551 100644 --- a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb +++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb @@ -28,6 +28,7 @@ module ActiveRecord included do attribute_method_suffix "_before_type_cast" + attribute_method_suffix "_came_from_user?" end # Returns the value of the attribute identified by +attr_name+ before @@ -66,6 +67,10 @@ module ActiveRecord def attribute_before_type_cast(attribute_name) read_attribute_before_type_cast(attribute_name) end + + def attribute_came_from_user?(attribute_name) + @attributes[attribute_name].came_from_user? + end end end end diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index d5702accaf..ce7f575150 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -134,7 +134,7 @@ module ActiveRecord # Serialized attributes should always be written in case they've been # changed in place. def keys_for_partial_write - changed + changed & persistable_attribute_names end def _field_changed?(attr, old_value) diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index 20f0936e52..24e30b6608 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/module/method_transplanting' - module ActiveRecord module AttributeMethods module Read @@ -36,42 +34,24 @@ module ActiveRecord extend ActiveSupport::Concern module ClassMethods - [:cache_attributes, :cached_attributes, :cache_attribute?].each do |method_name| - define_method method_name do |*| - cached_attributes_deprecation_warning(method_name) - true - end - end - protected - def cached_attributes_deprecation_warning(method_name) - ActiveSupport::Deprecation.warn "Calling `#{method_name}` is no longer necessary. All attributes are cached." - end + def define_method_attribute(name) + safe_name = name.unpack('h*').first + temp_method = "__temp__#{safe_name}" - if Module.methods_transplantable? - def define_method_attribute(name) - method = ReaderMethodCache[name] - generated_attribute_methods.module_eval { define_method name, method } - end - else - def define_method_attribute(name) - safe_name = name.unpack('h*').first - temp_method = "__temp__#{safe_name}" + ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name - ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name - - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 - def #{temp_method} - name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} - _read_attribute(name) { |n| missing_attribute(n, caller) } - end - STR - - generated_attribute_methods.module_eval do - alias_method name, temp_method - undef_method temp_method + generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + def #{temp_method} + name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} + _read_attribute(name) { |n| missing_attribute(n, caller) } end + STR + + generated_attribute_methods.module_eval do + alias_method name, temp_method + undef_method temp_method end end end @@ -92,12 +72,9 @@ module ActiveRecord def _read_attribute(attr_name) # :nodoc: @attributes.fetch_value(attr_name.to_s) { |n| yield n if block_given? } end + alias :attribute :_read_attribute + private :attribute - private - - def attribute(attribute_name) - _read_attribute(attribute_name) - end end end end diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index e5ec5ddca5..d0d8a968c5 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/string/filters' - module ActiveRecord module AttributeMethods module Serialization @@ -51,19 +49,6 @@ module ActiveRecord Type::Serialized.new(type, coder) end end - - def serialized_attributes - ActiveSupport::Deprecation.warn(<<-MSG.squish) - `serialized_attributes` is deprecated without replacement, and will - be removed in Rails 5.0. - MSG - - @serialized_attributes ||= Hash[ - columns.select { |t| t.cast_type.is_a?(Type::Serialized) }.map { |c| - [c.name, c.cast_type.coder] - } - ] - end end end end diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb index 16804f86bf..ab017c7b54 100644 --- a/activerecord/lib/active_record/attribute_methods/write.rb +++ b/activerecord/lib/active_record/attribute_methods/write.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/module/method_transplanting' - module ActiveRecord module AttributeMethods module Write @@ -25,27 +23,18 @@ module ActiveRecord module ClassMethods protected - if Module.methods_transplantable? - def define_method_attribute=(name) - method = WriterMethodCache[name] - generated_attribute_methods.module_eval { - define_method "#{name}=", method - } - end - else - def define_method_attribute=(name) - safe_name = name.unpack('h*').first - ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name + def define_method_attribute=(name) + safe_name = name.unpack('h*').first + ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 - def __temp__#{safe_name}=(value) - name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} - write_attribute(name, value) - end - alias_method #{(name + '=').inspect}, :__temp__#{safe_name}= - undef_method :__temp__#{safe_name}= - STR - end + generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + def __temp__#{safe_name}=(value) + name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} + write_attribute(name, value) + end + alias_method #{(name + '=').inspect}, :__temp__#{safe_name}= + undef_method :__temp__#{safe_name}= + STR end end diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index aafb990bc1..b263a89d79 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -9,6 +9,8 @@ module ActiveRecord class_attribute :user_provided_defaults, instance_accessor: false # :internal: self.user_provided_columns = {} self.user_provided_defaults = {} + + delegate :persistable_attribute_names, to: :class end module ClassMethods # :nodoc: @@ -96,6 +98,10 @@ module ActiveRecord @columns_hash ||= Hash[columns.map { |c| [c.name, c] }] end + def persistable_attribute_names # :nodoc: + @persistable_attribute_names ||= connection.schema_cache.columns_hash(table_name).keys + end + def reset_column_information # :nodoc: super clear_caches_calculated_from_columns @@ -130,6 +136,7 @@ module ActiveRecord @columns_hash = nil @content_columns = nil @default_attributes = nil + @persistable_attribute_names = nil end def raw_default_values diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index c39b045a5e..fcaaffb852 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -200,13 +200,19 @@ module ActiveRecord after_create save_method after_update save_method else - define_non_cyclic_method(save_method) { save_belongs_to_association(reflection) } + define_non_cyclic_method(save_method) { throw(:abort) if save_belongs_to_association(reflection) == false } before_save save_method end if reflection.validate? && !method_defined?(validation_method) method = (collection ? :validate_collection_association : :validate_single_association) - define_non_cyclic_method(validation_method) { send(method, reflection) } + define_non_cyclic_method(validation_method) do + send(method, reflection) + # TODO: remove the following line as soon as the return value of + # callbacks is ignored, that is, returning `false` does not + # display a deprecation warning or halts the callback chain. + true + end validate validation_method end end @@ -272,11 +278,18 @@ module ActiveRecord # go through nested autosave associations that are loaded in memory (without loading # any new ones), and return true if is changed for autosave def nested_records_changed_for_autosave? - self.class._reflections.values.any? do |reflection| - if reflection.options[:autosave] - association = association_instance_get(reflection.name) - association && Array.wrap(association.target).any?(&:changed_for_autosave?) + @_nested_records_changed_for_autosave_already_called ||= false + return false if @_nested_records_changed_for_autosave_already_called + begin + @_nested_records_changed_for_autosave_already_called = true + self.class._reflections.values.any? do |reflection| + if reflection.options[:autosave] + association = association_instance_get(reflection.name) + association && Array.wrap(association.target).any?(&:changed_for_autosave?) + end end + ensure + @_nested_records_changed_for_autosave_already_called = false end end diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index bb01231bca..100d3780f6 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -312,6 +312,7 @@ module ActiveRecord #:nodoc: include Reflection include Serialization include Store + include SecureToken end ActiveSupport.run_load_hooks(:active_record, Base) diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index 497ce8c15c..f44e5af5de 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -192,14 +192,14 @@ module ActiveRecord # # == <tt>before_validation*</tt> returning statements # - # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be + # If the +before_validation+ callback throws +:abort+, the process will be # aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a # ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object. # # == Canceling callbacks # - # If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are - # cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled. + # If a <tt>before_*</tt> callback throws +:abort+, all the later callbacks and + # the associated action are cancelled. # Callbacks are generally run in the order they are defined, with the exception of callbacks defined as # methods on the model, which are called last. # diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 6235745fb2..d99dc9a5db 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -2,7 +2,6 @@ require 'thread' require 'thread_safe' require 'monitor' require 'set' -require 'active_support/core_ext/string/filters' module ActiveRecord # Raised when a connection could not be obtained within the connection @@ -454,6 +453,10 @@ module ActiveRecord c.verify! end c + rescue + remove c + c.disconnect! + raise end end @@ -517,15 +520,7 @@ module ActiveRecord def connection_pool_list owner_to_pool.values.compact end - - def connection_pools - ActiveSupport::Deprecation.warn(<<-MSG.squish) - In the next release, this will return the same as `#connection_pool_list`. - (An array of pools, rather than a hash mapping specs to pools.) - MSG - - Hash[connection_pool_list.map { |pool| [pool.spec, pool] }] - end + alias :connection_pools :connection_pool_list def establish_connection(owner, spec) @class_to_pool.clear 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 59cdd8e98c..787d07c4c2 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -285,10 +285,16 @@ module ActiveRecord def insert_fixture(fixture, table_name) columns = schema_cache.columns_hash(table_name) - key_list = [] - value_list = fixture.map do |name, value| - key_list << quote_column_name(name) - quote(value, columns[name]) + binds = fixture.map do |name, value| + [columns[name], value] + end + key_list = fixture.keys.map { |name| quote_column_name(name) } + value_list = prepare_binds_for_database(binds).map do |_, value| + begin + quote(value) + rescue TypeError + quote(YAML.dump(value)) + end end execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert' diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb index 143d7d9574..c18caa2a2f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb @@ -10,6 +10,12 @@ module ActiveRecord return value.quoted_id if value.respond_to?(:quoted_id) if column + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Passing a column to `quote` has been deprecated. It is only used + for type casting, which should be handled elsewhere. See + https://github.com/rails/arel/commit/6160bfbda1d1781c3b08a33ec4955f170e95be11 + for more information. + MSG value = column.cast_type.type_cast_for_database(value) end @@ -90,6 +96,16 @@ module ActiveRecord value.to_s(:db) end + def prepare_binds_for_database(binds) # :nodoc: + binds.map do |column, value| + if column + column_name = column.name + value = column.cast_type.type_cast_for_database(value) + end + [column_name, value] + end + end + private def types_which_need_no_typecasting @@ -109,8 +125,7 @@ module ActiveRecord when Date, Time then "'#{quoted_date(value)}'" when Symbol then "'#{quote_string(value.to_s)}'" when Class then "'#{value}'" - else - "'#{quote_string(YAML.dump(value))}'" + else raise TypeError, "can't quote #{value.class.name}" end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb index 18ff869ea6..db20b60d60 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb @@ -28,8 +28,8 @@ module ActiveRecord end def visit_ColumnDefinition(o) - sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale) - column_sql = "#{quote_column_name(o.name)} #{sql_type}" + o.sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale) + column_sql = "#{quote_column_name(o.name)} #{o.sql_type}" add_column_options!(column_sql, column_options(o)) unless o.type == :primary_key column_sql end @@ -98,9 +98,7 @@ module ActiveRecord end def quote_default_expression(value, column) - column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale) value = type_for_column(column).type_cast_for_database(value) - @conn.quote(value) end 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 68d8a2cd6a..7eaa89c9a7 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -56,18 +56,6 @@ module ActiveRecord end end - module TimestampDefaultDeprecation # :nodoc: - def emit_warning_if_null_unspecified(options) - return if options.key?(:null) - - ActiveSupport::Deprecation.warn(<<-MSG.squish) - `#timestamp` was called without specifying an option for `null`. In Rails 5, - this behavior will change to `null: false`. You should manually specify - `null: true` to prevent the behavior of your existing migrations from changing. - MSG - end - end - class ReferenceDefinition # :nodoc: def initialize( name, @@ -167,8 +155,6 @@ module ActiveRecord # The table definitions # The Columns are stored as a ColumnDefinition in the +columns+ attribute. class TableDefinition - include TimestampDefaultDeprecation - # An array of ColumnDefinition objects, representing the column changes # that have been defined. attr_accessor :indexes @@ -375,7 +361,9 @@ module ActiveRecord # t.timestamps null: false def timestamps(*args) options = args.extract_options! - emit_warning_if_null_unspecified(options) + + options[:null] = false if options[:null].nil? + column(:created_at, :datetime, options) column(:updated_at, :datetime, options) end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index 34d60493ea..0f44c332ae 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -851,14 +851,14 @@ module ActiveRecord columns end - include TimestampDefaultDeprecation # Adds timestamps (+created_at+ and +updated_at+) columns to +table_name+. # Additional options (like <tt>null: false</tt>) are forwarded to #add_column. # # add_timestamps(:suppliers, null: false) # def add_timestamps(table_name, options = {}) - emit_warning_if_null_unspecified(options) + options[:null] = false if options[:null].nil? + add_column table_name, :created_at, :datetime, options add_column table_name, :updated_at, :datetime, options end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb index fd666c8c39..7535e9147a 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb @@ -69,16 +69,11 @@ module ActiveRecord def rollback_records ite = records.uniq while record = ite.shift - begin - record.rolledback! full_rollback? - rescue => e - raise if ActiveRecord::Base.raise_in_transactional_callbacks - record.logger.error(e) if record.respond_to?(:logger) && record.logger - end + record.rolledback!(force_restore_state: full_rollback?) end ensure ite.each do |i| - i.rolledback!(full_rollback?, false) + i.rolledback!(force_restore_state: full_rollback?, should_run_callbacks: false) end end @@ -89,16 +84,11 @@ module ActiveRecord def commit_records ite = records.uniq while record = ite.shift - begin - record.committed! - rescue => e - raise if ActiveRecord::Base.raise_in_transactional_callbacks - record.logger.error(e) if record.respond_to?(:logger) && record.logger - end + record.committed! end ensure ite.each do |i| - i.committed!(false) + i.committed!(should_run_callbacks: false) end end @@ -127,8 +117,6 @@ module ActiveRecord def commit connection.release_savepoint(savepoint_name) super - parent = connection.transaction_manager.current_transaction - records.each { |r| parent.add_record(r) } end def full_rollback?; false; end @@ -176,7 +164,9 @@ module ActiveRecord end def commit_transaction - @stack.pop.commit + transaction = @stack.pop + transaction.commit + transaction.records.each { |r| current_transaction.add_record(r) } end def rollback_transaction diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index fa24d9b43f..c941c9f1eb 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -25,7 +25,6 @@ module ActiveRecord autoload :TableDefinition autoload :Table autoload :AlterTable - autoload :TimestampDefaultDeprecation end autoload_at 'active_record/connection_adapters/abstract/connection_pool' do @@ -114,7 +113,8 @@ module ActiveRecord class BindCollector < Arel::Collectors::Bind def compile(bvs, conn) - super(bvs.map { |bv| conn.quote(*bv.reverse) }) + casted_binds = conn.prepare_binds_for_database(bvs) + super(casted_binds.map { |_, value| conn.quote(value) }) end end @@ -393,7 +393,7 @@ module ActiveRecord end def column_name_for_operation(operation, node) # :nodoc: - node.to_sql + visitor.accept(node, collector).value end protected diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb index af307b57a4..e74de60a83 100644 --- a/activerecord/lib/active_record/connection_adapters/column.rb +++ b/activerecord/lib/active_record/connection_adapters/column.rb @@ -5,7 +5,6 @@ module ActiveRecord module ConnectionAdapters # An abstract definition of a column in a table. class Column - TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set module Format @@ -30,13 +29,13 @@ module ActiveRecord # <tt>company_name varchar(60)</tt>. # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute. # +null+ determines if this column allows +NULL+ values. - def initialize(name, default, cast_type, sql_type = nil, null = true) + def initialize(name, default, cast_type, sql_type = nil, null = true, default_function = nil) @name = name @cast_type = cast_type @sql_type = sql_type @null = null @default = default - @default_function = nil + @default_function = default_function end def has_default? @@ -77,6 +76,12 @@ module ActiveRecord [self.class, name, default, cast_type, sql_type, null, default_function] end end + + class NullColumn < Column + def initialize(name) + super name, nil, Type::Value.new + end + end end # :startdoc: end diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb index e54e3199ff..08d46fca96 100644 --- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -1,5 +1,4 @@ require 'uri' -require 'active_support/core_ext/string/filters' module ActiveRecord module ConnectionAdapters @@ -210,30 +209,12 @@ module ActiveRecord when Symbol resolve_symbol_connection spec when String - resolve_string_connection spec + resolve_url_connection spec when Hash resolve_hash_connection spec end end - def resolve_string_connection(spec) - # Rails has historically accepted a string to mean either - # an environment key or a URL spec, so we have deprecated - # this ambiguous behaviour and in the future this function - # can be removed in favor of resolve_url_connection. - if configurations.key?(spec) || spec !~ /:/ - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing a string to ActiveRecord::Base.establish_connection for a - configuration lookup is deprecated, please pass a symbol - (#{spec.to_sym.inspect}) instead. - MSG - - resolve_symbol_connection(spec) - else - resolve_url_connection(spec) - end - end - # Takes the environment such as +:production+ or +:development+. # This requires that the @configurations was initialized with a key that # matches. diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/column.rb b/activerecord/lib/active_record/connection_adapters/postgresql/column.rb index 1458fbf496..acb1278499 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/column.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/column.rb @@ -2,18 +2,17 @@ module ActiveRecord module ConnectionAdapters # PostgreSQL-specific extensions to column definitions in a table. class PostgreSQLColumn < Column #:nodoc: - attr_accessor :array + attr_reader :array + alias :array? :array def initialize(name, default, cast_type, sql_type = nil, null = true, default_function = nil) if sql_type =~ /\[\]$/ @array = true - super(name, default, cast_type, sql_type[0..sql_type.length - 3], null) + sql_type = sql_type[0..sql_type.length - 3] else @array = false - super(name, default, cast_type, sql_type, null) end - - @default_function = default_function + super end def serial? diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb index 961e6224c4..3adfb8b9d8 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb @@ -25,16 +25,7 @@ module ActiveRecord to = type_cast_single extracted[:to] if !infinity?(from) && extracted[:exclude_start] - if from.respond_to?(:succ) - from = from.succ - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Excluding the beginning of a Range is only partialy supported - through `#succ`. This is not reliable and will be removed in - the future. - MSG - else - raise ArgumentError, "The Ruby Range object does not support excluding the beginning of a Range. (unsupported value: '#{value}')" - end + raise ArgumentError, "The Ruby Range object does not support excluding the beginning of a Range. (unsupported value: '#{value}')" end ::Range.new(from, to, extracted[:exclude_end]) end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb index 607848884b..9de9e2c7dc 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb @@ -56,7 +56,8 @@ module ActiveRecord if column.type == :uuid && value =~ /\(\)/ value else - quote(value, column) + value = column.cast_type.type_cast_for_database(value) + quote(value) end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 13bb5c187e..f4f9747359 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -64,7 +64,7 @@ module ActiveRecord # <tt>SET client_min_messages TO <min_messages></tt> call on the connection. # * <tt>:variables</tt> - An optional hash of additional parameters that # will be used in <tt>SET SESSION key = val</tt> calls on the connection. - # * <tt>:insert_returning</tt> - An optional boolean to control the use or <tt>RETURNING</tt> for <tt>INSERT</tt> statements + # * <tt>:insert_returning</tt> - An optional boolean to control the use of <tt>RETURNING</tt> for <tt>INSERT</tt> statements # defaults to true. # # Any further options are used as connection parameters to libpq. See @@ -144,7 +144,7 @@ module ActiveRecord # AbstractAdapter def prepare_column_options(column) # :nodoc: spec = super - spec[:array] = 'true' if column.respond_to?(:array) && column.array + spec[:array] = 'true' if column.array? spec[:default] = "\"#{column.default_function}\"" if column.default_function spec end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 38b2d632d2..a7aff9f724 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -87,13 +87,6 @@ module ActiveRecord mattr_accessor :maintain_test_schema, instance_accessor: false - def self.disable_implicit_join_references=(value) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Implicit join references were removed with Rails 4.1. - Make sure to remove this configuration because it does nothing. - MSG - end - class_attribute :default_connection_handler, instance_writer: false class_attribute :find_by_statement_cache @@ -281,16 +274,14 @@ module ActiveRecord # ==== Example: # # Instantiates a single new object # User.new(first_name: 'Jamie') - def initialize(attributes = nil, options = {}) + def initialize(attributes = nil) @attributes = self.class._default_attributes.dup + self.class.define_attribute_methods init_internals initialize_internals_callback - self.class.define_attribute_methods - # +options+ argument is only needed to make protected_attributes gem easier to hook. - # Remove it when we drop support to this gem. - init_attributes(attributes, options) if attributes + assign_attributes(attributes) if attributes yield self if block_given? _run_initialize_callbacks @@ -564,12 +555,6 @@ module ActiveRecord def initialize_internals_callback end - # This method is needed to make protected_attributes gem easier to hook. - # Remove it when we drop support to this gem. - def init_attributes(attributes, options) - assign_attributes(attributes) - end - def thaw if frozen? @attributes = @attributes.dup diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 4732462b05..10e9be20b5 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -633,7 +633,7 @@ module ActiveRecord # interpolate the fixture label row.each do |key, value| - row[key] = value.gsub("$LABEL", label) if value.is_a?(String) + row[key] = value.gsub("$LABEL", label.to_s) if value.is_a?(String) end # generate a primary key if necessary @@ -768,12 +768,6 @@ module ActiveRecord end - #-- - # Deprecate 'Fixtures' in favor of 'FixtureSet'. - #++ - # :nodoc: - Fixtures = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActiveRecord::Fixtures', 'ActiveRecord::FixtureSet') - class Fixture #:nodoc: include Enumerable @@ -888,7 +882,7 @@ module ActiveRecord @fixture_cache[fs_name] ||= {} instances = fixture_names.map do |f_name| - f_name = f_name.to_s + f_name = f_name.to_s if f_name.is_a?(Symbol) @fixture_cache[fs_name].delete(f_name) if force_reload if @loaded_fixtures[fs_name][f_name] diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index b91e9ac137..fd1e22349b 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -79,16 +79,6 @@ module ActiveRecord :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) end - def symbolized_base_class - ActiveSupport::Deprecation.warn('`ActiveRecord::Base.symbolized_base_class` is deprecated and will be removed without replacement.') - @symbolized_base_class ||= base_class.to_s.to_sym - end - - def symbolized_sti_name - ActiveSupport::Deprecation.warn('`ActiveRecord::Base.symbolized_sti_name` is deprecated and will be removed without replacement.') - @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class - end - # Returns the class descending directly from ActiveRecord::Base, or # an abstract class, if any, in the inheritance hierarchy. # diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index 9f053453bd..6f2b65c137 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -66,6 +66,15 @@ module ActiveRecord send(lock_col + '=', previous_lock_value + 1) end + def _create_record(attribute_names = self.attribute_names, *) # :nodoc: + if locking_enabled? + # We always want to persist the locking version, even if we don't detect + # a change from the default, since the database might have no default + attribute_names |= [self.class.locking_column] + end + super + end + def _update_record(attribute_names = self.attribute_names) #:nodoc: return super unless locking_enabled? return 0 if attribute_names.empty? @@ -116,12 +125,8 @@ module ActiveRecord relation = super if locking_enabled? - column_name = self.class.locking_column - column = self.class.columns_hash[column_name] - substitute = self.class.connection.substitute_at(column) - - relation = relation.where(self.class.arel_table[column_name].eq(substitute)) - relation.bind_values << [column, self[column_name].to_i] + locking_column = self.class.locking_column + relation = relation.where(locking_column => _read_attribute(locking_column)) end relation @@ -185,11 +190,6 @@ module ActiveRecord super.to_i end - def changed?(old_value, *) - # Ensure we save if the default was `nil` - super || old_value == 0 - end - def init_with(coder) __setobj__(coder['subtype']) end diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb index eb64d197f0..a5c7279db9 100644 --- a/activerecord/lib/active_record/log_subscriber.rb +++ b/activerecord/lib/active_record/log_subscriber.rb @@ -22,10 +22,10 @@ module ActiveRecord def render_bind(column, value) if column - if column.binary? + if column.binary? && value # This specifically deals with the PG adapter that casts bytea columns into a Hash. value = value[:value] if value.is_a?(Hash) - value = value ? "<#{value.bytesize} bytes of binary data>" : "<NULL binary data>" + value = "<#{value.bytesize} bytes of binary data>" end [column.name, value] diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index f53c5f17ef..6306a25745 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -113,9 +113,9 @@ module ActiveRecord # the current time. However, if you supply <tt>touch: false</tt>, these # timestamps will not be updated. # - # There's a series of callbacks associated with +save+. If any of the - # <tt>before_*</tt> callbacks return +false+ the action is cancelled and - # +save+ returns +false+. See ActiveRecord::Callbacks for further + # There's a series of callbacks associated with #save. If any of the + # <tt>before_*</tt> callbacks throws +:abort+ the action is cancelled and + # #save returns +false+. See ActiveRecord::Callbacks for further # details. # # Attributes marked as readonly are silently ignored if the record is @@ -139,9 +139,9 @@ module ActiveRecord # the current time. However, if you supply <tt>touch: false</tt>, these # timestamps will not be updated. # - # There's a series of callbacks associated with <tt>save!</tt>. If any of - # the <tt>before_*</tt> callbacks return +false+ the action is cancelled - # and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See + # There's a series of callbacks associated with #save!. If any of + # the <tt>before_*</tt> callbacks throws +:abort+ the action is cancelled + # and #save! raises ActiveRecord::RecordNotSaved. See # ActiveRecord::Callbacks for further details. # # Attributes marked as readonly are silently ignored if the record is @@ -171,10 +171,10 @@ module ActiveRecord # Deletes the record in the database and freezes this instance to reflect # that no changes should be made (since they can't be persisted). # - # There's a series of callbacks associated with <tt>destroy</tt>. If - # the <tt>before_destroy</tt> callback return +false+ the action is cancelled - # and <tt>destroy</tt> returns +false+. See - # ActiveRecord::Callbacks for further details. + # There's a series of callbacks associated with #destroy. If the + # <tt>before_destroy</tt> callback throws +:abort+ the action is cancelled + # and #destroy returns +false+. + # See ActiveRecord::Callbacks for further details. def destroy raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly? destroy_associations @@ -186,10 +186,10 @@ module ActiveRecord # Deletes the record in the database and freezes this instance to reflect # that no changes should be made (since they can't be persisted). # - # There's a series of callbacks associated with <tt>destroy!</tt>. If - # the <tt>before_destroy</tt> callback return +false+ the action is cancelled - # and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See - # ActiveRecord::Callbacks for further details. + # There's a series of callbacks associated with #destroy!. If the + # <tt>before_destroy</tt> callback throws +:abort+ the action is cancelled + # and #destroy! raises ActiveRecord::RecordNotDestroyed. + # See ActiveRecord::Callbacks for further details. def destroy! destroy || raise(ActiveRecord::RecordNotDestroyed, self) end @@ -495,15 +495,7 @@ module ActiveRecord end def relation_for_destroy - pk = self.class.primary_key - column = self.class.columns_hash[pk] - substitute = self.class.connection.substitute_at(column) - - relation = self.class.unscoped.where( - self.class.arel_table[pk].eq(substitute)) - - relation.bind_values = [[column, id]] - relation + self.class.unscoped.where(self.class.primary_key => id) end def create_or_update(*args) diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index 7696ef13c7..dab5a502a5 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -153,15 +153,6 @@ module ActiveRecord JoinKeys.new(foreign_key, active_record_primary_key) end - def source_macro - ActiveSupport::Deprecation.warn(<<-MSG.squish) - ActiveRecord::Base.source_macro is deprecated and will be removed - without replacement. - MSG - - macro - end - def constraints scope_chain.flatten end @@ -352,13 +343,10 @@ module ActiveRecord return unless scope if scope.arity > 0 - ActiveSupport::Deprecation.warn(<<-MSG.squish) + raise ArgumentError, <<-MSG.squish The association scope '#{name}' is instance dependent (the scope - block takes an argument). Preloading happens before the individual - instances are created. This means that there is no instance being - passed to the association scope. This will most likely result in - broken or incorrect behavior. Joining, Preloading and eager loading - of these associations is deprecated and will be removed in the future. + block takes an argument). Preloading instance dependent scopes is + not supported. MSG end end @@ -763,16 +751,6 @@ module ActiveRecord source_reflection.join_keys(association_klass) end - # The macro used by the source association - def source_macro - ActiveSupport::Deprecation.warn(<<-MSG.squish) - ActiveRecord::Base.source_macro is deprecated and will be removed - without replacement. - MSG - - source_reflection.source_macro - end - # A through association is nested if there would be more than one join table def nested? chain.length > 2 diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index ab3debc03b..dd78814c6a 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -558,8 +558,9 @@ module ActiveRecord end arel = relation.arel - binds = (arel.bind_values + relation.bind_values).dup - binds.map! { |bv| connection.quote(*bv.reverse) } + binds = arel.bind_values + relation.bind_values + binds = connection.prepare_binds_for_database(binds) + binds.map! { |_, value| connection.quote(value) } collect = visitor.accept(arel.ast, Arel::Collectors::Bind.new) collect.substitute_binds(binds).join end diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb index 50f4d5c7ab..d4a8823cfe 100644 --- a/activerecord/lib/active_record/relation/delegation.rb +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -1,6 +1,5 @@ require 'set' require 'active_support/concern' -require 'active_support/deprecation' module ActiveRecord module Delegation # :nodoc: diff --git a/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb index 4b5f5773a0..95dbd6a77f 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/string/filters' - module ActiveRecord class PredicateBuilder class ArrayHandler # :nodoc: diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index ef380abfe8..d6e6cb4d05 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -62,15 +62,14 @@ module ActiveRecord Relation::MULTI_VALUE_METHODS.each do |name| class_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{name}_values # def select_values - @values[:#{name}] || [] # @values[:select] || [] - end # end - # - def #{name}_values=(values) # def select_values=(values) - raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded - check_cached_relation - @values[:#{name}] = values # @values[:select] = values - end # end + def #{name}_values # def select_values + @values[:#{name}] || [] # @values[:select] || [] + end # end + # + def #{name}_values=(values) # def select_values=(values) + assert_mutability! # assert_mutability! + @values[:#{name}] = values # @values[:select] = values + end # end CODE end @@ -85,23 +84,12 @@ module ActiveRecord Relation::SINGLE_VALUE_METHODS.each do |name| class_eval <<-CODE, __FILE__, __LINE__ + 1 def #{name}_value=(value) # def readonly_value=(value) - raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded - check_cached_relation + assert_mutability! # assert_mutability! @values[:#{name}] = value # @values[:readonly] = value end # end CODE end - def check_cached_relation # :nodoc: - if defined?(@arel) && @arel - @arel = nil - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Modifying already cached Relation. The cache will be reset. Use a - cloned Relation to prevent this warning. - MSG - end - end - def create_with_value # :nodoc: @values[:create_with] || {} end @@ -757,6 +745,9 @@ module ActiveRecord def from!(value, subquery_name = nil) # :nodoc: self.from_value = [value, subquery_name] + if value.is_a? Relation + self.bind_values = value.arel.bind_values + value.bind_values + bind_values + end self end @@ -857,6 +848,11 @@ module ActiveRecord private + def assert_mutability! + raise ImmutableRelation if @loaded + raise ImmutableRelation if defined?(@arel) && @arel + end + def build_arel arel = Arel::SelectManager.new(table) @@ -1006,7 +1002,6 @@ module ActiveRecord case opts when Relation name ||= 'subquery' - self.bind_values = opts.bind_values + self.bind_values opts.arel.as(name.to_s) else opts @@ -1159,13 +1154,11 @@ module ActiveRecord end end - # This function is recursive just for better readablity. - # #where argument doesn't support more than one level nested hash in real world. def add_relations_to_bind_values(attributes) if attributes.is_a?(Hash) attributes.each_value do |value| if value.is_a?(ActiveRecord::Relation) - self.bind_values += value.bind_values + self.bind_values += value.arel.bind_values + value.bind_values else add_relations_to_bind_values(value) end diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index f5aa60a69a..313e767dcb 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -3,14 +3,11 @@ module ActiveRecord extend ActiveSupport::Concern module ClassMethods - def quote_value(value, column) #:nodoc: - connection.quote(value, column) - end - # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>. def sanitize(object) #:nodoc: connection.quote(object) end + alias_method :quote_value, :sanitize protected @@ -72,35 +69,6 @@ module ActiveRecord expanded_attrs end - # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause. - # { name: "foo'bar", group_id: 4 } - # # => "name='foo''bar' and group_id= 4" - # { status: nil, group_id: [1,2,3] } - # # => "status IS NULL and group_id IN (1,2,3)" - # { age: 13..18 } - # # => "age BETWEEN 13 AND 18" - # { 'other_records.id' => 7 } - # # => "`other_records`.`id` = 7" - # { other_records: { id: 7 } } - # # => "`other_records`.`id` = 7" - # And for value objects on a composed_of relationship: - # { address: Address.new("123 abc st.", "chicago") } - # # => "address_street='123 abc st.' and address_city='chicago'" - def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) - table = Arel::Table.new(table_name).alias(default_table_name) - predicate_builder = PredicateBuilder.new(TableMetadata.new(self, table)) - ActiveSupport::Deprecation.warn(<<-EOWARN) -sanitize_sql_hash_for_conditions is deprecated, and will be removed in Rails 5.0 - EOWARN - attrs = predicate_builder.resolve_column_aliases(attrs) - attrs = expand_hash_conditions_for_aggregates(attrs) - - predicate_builder.build_from_hash(attrs).map { |b| - connection.visitor.compile b - }.join(' AND ') - end - alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions - # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. # { status: nil, group_id: 1 } # # => "status = NULL , group_id = 1" @@ -185,7 +153,7 @@ sanitize_sql_hash_for_conditions is deprecated, and will be removed in Rails 5.0 # TODO: Deprecate this def quoted_id - self.class.quote_value(id, column_for_attribute(self.class.primary_key)) + self.class.quote_value(@attributes[self.class.primary_key].value_for_database) end end end diff --git a/activerecord/lib/active_record/secure_token.rb b/activerecord/lib/active_record/secure_token.rb new file mode 100644 index 0000000000..be3c3bc847 --- /dev/null +++ b/activerecord/lib/active_record/secure_token.rb @@ -0,0 +1,39 @@ +module ActiveRecord + module SecureToken + extend ActiveSupport::Concern + + module ClassMethods + # Example using has_secure_token + # + # # Schema: User(toke:string, auth_token:string) + # class User < ActiveRecord::Base + # has_secure_token + # has_secure_token :auth_token + # end + # + # user = User.new + # user.save + # user.token # => "4kUgL2pdQMSCQtjE" + # user.auth_token # => "77TMHrHJFvFDwodq8w7Ev2m7" + # user.regenerate_token # => true + # user.regenerate_auth_token # => true + # + # SecureRandom::base58 is used to generate the 24-character unique token, so collisions are highly unlikely. + # + # Note that it's still possible to generate a race condition in the database in the same way that + # validates_presence_of can. You're encouraged to add a unique index in the database to deal with + # this even more unlikely scenario. + def has_secure_token(attribute = :token) + # Load securerandom only when has_secure_token is used. + require 'active_support/core_ext/securerandom' + define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token } + before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token) } + end + + def generate_unique_secure_token + SecureRandom.base58(24) + end + end + end +end + diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb index 192a19f05d..3047a81ec4 100644 --- a/activerecord/lib/active_record/statement_cache.rb +++ b/activerecord/lib/active_record/statement_cache.rb @@ -47,8 +47,8 @@ module ActiveRecord def sql_for(binds, connection) val = @values.dup - binds = binds.dup - @indexes.each { |i| val[i] = connection.quote(*binds.shift.reverse) } + binds = connection.prepare_binds_for_database(binds) + @indexes.each { |i| val[i] = connection.quote(binds.shift.last) } val.join end end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index de701edca0..0fd2862b2c 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -4,24 +4,10 @@ module ActiveRecord extend ActiveSupport::Concern #:nodoc: ACTIONS = [:create, :destroy, :update] - #:nodoc: - CALLBACK_WARN_MESSAGE = "Currently, Active Record suppresses errors raised " \ - "within `after_rollback`/`after_commit` callbacks and only print them to " \ - "the logs. In the next version, these errors will no longer be suppressed. " \ - "Instead, the errors will propagate normally just like in other Active " \ - "Record callbacks.\n" \ - "\n" \ - "You can opt into the new behavior and remove this warning by setting:\n" \ - "\n" \ - " config.active_record.raise_in_transactional_callbacks = true\n\n" included do define_callbacks :commit, :rollback, - terminator: ->(_, result) { result == false }, scope: [:kind, :name] - - mattr_accessor :raise_in_transactional_callbacks, instance_writer: false - self.raise_in_transactional_callbacks = false end # = Active Record Transactions @@ -237,9 +223,6 @@ module ActiveRecord def after_commit(*args, &block) set_options_for_callbacks!(args) set_callback(:commit, :after, *args, &block) - unless ActiveRecord::Base.raise_in_transactional_callbacks - ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE) - end end # This callback is called after a create, update, or destroy are rolled back. @@ -248,9 +231,16 @@ module ActiveRecord def after_rollback(*args, &block) set_options_for_callbacks!(args) set_callback(:rollback, :after, *args, &block) - unless ActiveRecord::Base.raise_in_transactional_callbacks - ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE) - end + end + + def raise_in_transactional_callbacks + ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks is deprecated and will be removed without replacement.') + true + end + + def raise_in_transactional_callbacks=(value) + ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks= is deprecated, has no effect and will be removed without replacement.') + value end private @@ -310,7 +300,7 @@ module ActiveRecord # # Ensure that it is not called if the object was never persisted (failed create), # but call it after the commit of a destroyed object. - def committed!(should_run_callbacks = true) #:nodoc: + def committed!(should_run_callbacks: true) #:nodoc: _run_commit_callbacks if should_run_callbacks && destroyed? || persisted? ensure force_clear_transaction_record_state @@ -318,7 +308,7 @@ module ActiveRecord # Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record # state should be rolled back to the beginning or just to the last savepoint. - def rolledback!(force_restore_state = false, should_run_callbacks = true) #:nodoc: + def rolledback!(force_restore_state: false, should_run_callbacks: true) #:nodoc: _run_rollback_callbacks if should_run_callbacks ensure restore_transaction_record_state(force_restore_state) @@ -388,7 +378,7 @@ module ActiveRecord thaw unless restore_state[:frozen?] @new_record = restore_state[:new_record] @destroyed = restore_state[:destroyed] - write_attribute(self.class.primary_key, restore_state[:id]) + write_attribute(self.class.primary_key, restore_state[:id]) if self.class.primary_key end end end diff --git a/activerecord/lib/active_record/type/boolean.rb b/activerecord/lib/active_record/type/boolean.rb index 978d16d524..f6a75512fd 100644 --- a/activerecord/lib/active_record/type/boolean.rb +++ b/activerecord/lib/active_record/type/boolean.rb @@ -10,19 +10,8 @@ module ActiveRecord def cast_value(value) if value == '' nil - elsif ConnectionAdapters::Column::TRUE_VALUES.include?(value) - true else - if !ConnectionAdapters::Column::FALSE_VALUES.include?(value) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - You attempted to assign a value which is not explicitly `true` or `false` - to a boolean column. Currently this value casts to `false`. This will - change to match Ruby's semantics, and will cast to `true` in Rails 5. - If you would like to maintain the current behavior, you should - explicitly handle the values you would like cast to `false`. - MSG - end - false + !ConnectionAdapters::Column::FALSE_VALUES.include?(value) end end end diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb index f7bf6987c4..5b3e57dcf6 100644 --- a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb @@ -4,14 +4,19 @@ class <%= migration_class_name %> < ActiveRecord::Migration <% attributes.each do |attribute| -%> <% if attribute.password_digest? -%> t.string :password_digest<%= attribute.inject_options %> +<% elsif attribute.token? -%> + t.string :<%= attribute.name %><%= attribute.inject_options %> <% else -%> t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %> <% end -%> <% end -%> <% if options[:timestamps] %> - t.timestamps null: false + t.timestamps <% end -%> end +<% attributes.select(&:token?).each do |attribute| -%> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true +<% end -%> <% attributes_with_index.each do |attribute| -%> add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> <% 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 index ae9c74fd05..23a377db6a 100644 --- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb @@ -4,6 +4,9 @@ class <%= migration_class_name %> < ActiveRecord::Migration <% attributes.each do |attribute| -%> <%- if attribute.reference? -%> add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %> + <%- elsif attribute.token? -%> + add_column :<%= table_name %>, :<%= attribute.name %>, :string<%= attribute.inject_options %> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true <%- else -%> add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %> <%- if attribute.has_index? -%> diff --git a/activerecord/lib/rails/generators/active_record/model/templates/model.rb b/activerecord/lib/rails/generators/active_record/model/templates/model.rb index 539d969fce..55dc65c8ad 100644 --- a/activerecord/lib/rails/generators/active_record/model/templates/model.rb +++ b/activerecord/lib/rails/generators/active_record/model/templates/model.rb @@ -3,6 +3,9 @@ class <%= class_name %> < <%= parent_class_name.classify %> <% attributes.select(&:reference?).each do |attribute| -%> belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %><%= ', required: true' if attribute.required? %> <% end -%> +<% attributes.select(&:token?).each do |attribute| -%> + has_secure_token<% if attribute.name != "token" %> :<%= attribute.name %><% end %> +<% end -%> <% if attributes.any?(&:password_digest?) -%> has_secure_password <% end -%> diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index 042beab23f..77055f5b7a 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -35,13 +35,13 @@ class PostgresqlArrayTest < ActiveRecord::TestCase def test_column assert_equal :string, @column.type assert_equal "character varying", @column.sql_type - assert @column.array + assert @column.array? assert_not @column.number? assert_not @column.binary? ratings_column = PgArray.columns_hash['ratings'] assert_equal :integer, ratings_column.type - assert ratings_column.array + assert ratings_column.array? assert_not ratings_column.number? end @@ -74,7 +74,7 @@ class PostgresqlArrayTest < ActiveRecord::TestCase assert_equal :text, column.type assert_equal [], PgArray.column_defaults['snippets'] - assert column.array + assert column.array? end def test_change_column_cant_make_non_array_column_to_array diff --git a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb index 72222c01fd..f154ba4cdc 100644 --- a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb @@ -28,7 +28,7 @@ class PostgresqlBitStringTest < ActiveRecord::TestCase assert_equal "bit(8)", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_bit_string_varying_column @@ -37,7 +37,7 @@ class PostgresqlBitStringTest < ActiveRecord::TestCase assert_equal "bit varying(4)", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_default diff --git a/activerecord/test/cases/adapters/postgresql/citext_test.rb b/activerecord/test/cases/adapters/postgresql/citext_test.rb index 85bff979c9..5a8083f7a7 100644 --- a/activerecord/test/cases/adapters/postgresql/citext_test.rb +++ b/activerecord/test/cases/adapters/postgresql/citext_test.rb @@ -34,7 +34,7 @@ if ActiveRecord::Base.connection.supports_extensions? assert_equal 'citext', column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_change_table_supports_json diff --git a/activerecord/test/cases/adapters/postgresql/composite_test.rb b/activerecord/test/cases/adapters/postgresql/composite_test.rb index cfab5ca902..24c1969dee 100644 --- a/activerecord/test/cases/adapters/postgresql/composite_test.rb +++ b/activerecord/test/cases/adapters/postgresql/composite_test.rb @@ -52,7 +52,7 @@ class PostgresqlCompositeTest < ActiveRecord::TestCase assert_equal "full_address", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_composite_mapping @@ -113,7 +113,7 @@ class PostgresqlCompositeWithCustomOIDTest < ActiveRecord::TestCase assert_equal "full_address", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_composite_mapping diff --git a/activerecord/test/cases/adapters/postgresql/domain_test.rb b/activerecord/test/cases/adapters/postgresql/domain_test.rb index 1500adb42d..ebb04814bb 100644 --- a/activerecord/test/cases/adapters/postgresql/domain_test.rb +++ b/activerecord/test/cases/adapters/postgresql/domain_test.rb @@ -31,7 +31,7 @@ class PostgresqlDomainTest < ActiveRecord::TestCase assert_equal "custom_money", column.sql_type assert column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_domain_acts_like_basetype diff --git a/activerecord/test/cases/adapters/postgresql/enum_test.rb b/activerecord/test/cases/adapters/postgresql/enum_test.rb index 83cedc5a7b..88b3b2cc0e 100644 --- a/activerecord/test/cases/adapters/postgresql/enum_test.rb +++ b/activerecord/test/cases/adapters/postgresql/enum_test.rb @@ -33,7 +33,7 @@ class PostgresqlEnumTest < ActiveRecord::TestCase assert_equal "mood", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_enum_defaults diff --git a/activerecord/test/cases/adapters/postgresql/full_text_test.rb b/activerecord/test/cases/adapters/postgresql/full_text_test.rb index dca35422b9..a370a5adc6 100644 --- a/activerecord/test/cases/adapters/postgresql/full_text_test.rb +++ b/activerecord/test/cases/adapters/postgresql/full_text_test.rb @@ -23,7 +23,7 @@ class PostgresqlFullTextTest < ActiveRecord::TestCase assert_equal "tsvector", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_update_tsvector diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb index 228221e034..ed2bf554bb 100644 --- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb +++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb @@ -28,7 +28,7 @@ class PostgresqlPointTest < ActiveRecord::TestCase assert_equal "point", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_default diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index 00ff456e16..a0aa10630c 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -56,7 +56,7 @@ if ActiveRecord::Base.connection.supports_extensions? assert_equal "hstore", @column.sql_type assert_not @column.number? assert_not @column.binary? - assert_not @column.array + assert_not @column.array? end def test_default diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb index 340ca29c0e..7be7e00463 100644 --- a/activerecord/test/cases/adapters/postgresql/json_test.rb +++ b/activerecord/test/cases/adapters/postgresql/json_test.rb @@ -36,7 +36,7 @@ module PostgresqlJSONSharedTestCases assert_equal column_type.to_s, column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_default diff --git a/activerecord/test/cases/adapters/postgresql/ltree_test.rb b/activerecord/test/cases/adapters/postgresql/ltree_test.rb index 5a0f505072..771a825840 100644 --- a/activerecord/test/cases/adapters/postgresql/ltree_test.rb +++ b/activerecord/test/cases/adapters/postgresql/ltree_test.rb @@ -32,7 +32,7 @@ class PostgresqlLtreeTest < ActiveRecord::TestCase assert_equal "ltree", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_write diff --git a/activerecord/test/cases/adapters/postgresql/money_test.rb b/activerecord/test/cases/adapters/postgresql/money_test.rb index 54cff192c1..f3a24eee85 100644 --- a/activerecord/test/cases/adapters/postgresql/money_test.rb +++ b/activerecord/test/cases/adapters/postgresql/money_test.rb @@ -27,7 +27,7 @@ class PostgresqlMoneyTest < ActiveRecord::TestCase assert_equal 2, column.scale assert column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_default diff --git a/activerecord/test/cases/adapters/postgresql/network_test.rb b/activerecord/test/cases/adapters/postgresql/network_test.rb index 4e49ea1e02..daa590f369 100644 --- a/activerecord/test/cases/adapters/postgresql/network_test.rb +++ b/activerecord/test/cases/adapters/postgresql/network_test.rb @@ -25,7 +25,7 @@ class PostgresqlNetworkTest < ActiveRecord::TestCase assert_equal "cidr", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_inet_column @@ -34,7 +34,7 @@ class PostgresqlNetworkTest < ActiveRecord::TestCase assert_equal "inet", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_macaddr_column @@ -43,7 +43,7 @@ class PostgresqlNetworkTest < ActiveRecord::TestCase assert_equal "macaddr", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_network_types diff --git a/activerecord/test/cases/adapters/postgresql/quoting_test.rb b/activerecord/test/cases/adapters/postgresql/quoting_test.rb index 9ac0036d66..894cf1ffa2 100644 --- a/activerecord/test/cases/adapters/postgresql/quoting_test.rb +++ b/activerecord/test/cases/adapters/postgresql/quoting_test.rb @@ -34,13 +34,14 @@ module ActiveRecord def test_quote_range range = "1,2]'; SELECT * FROM users; --".."a" - c = PostgreSQLColumn.new(nil, nil, OID::Range.new(Type::Integer.new, :int8range)) - assert_equal "'[1,0]'", @conn.quote(range, c) + type = OID::Range.new(Type::Integer.new, :int8range) + assert_equal "'[1,0]'", @conn.quote(type.type_cast_for_database(range)) end def test_quote_bit_string - c = PostgreSQLColumn.new(nil, 1, OID::Bit.new) - assert_equal nil, @conn.quote("'); SELECT * FROM users; /*\n01\n*/--", c) + value = "'); SELECT * FROM users; /*\n01\n*/--" + type = OID::Bit.new + assert_equal nil, @conn.quote(type.type_cast_for_database(value)) end end end diff --git a/activerecord/test/cases/adapters/postgresql/range_test.rb b/activerecord/test/cases/adapters/postgresql/range_test.rb index d812cd01c4..70cf21100a 100644 --- a/activerecord/test/cases/adapters/postgresql/range_test.rb +++ b/activerecord/test/cases/adapters/postgresql/range_test.rb @@ -230,36 +230,14 @@ _SQL assert_nil_round_trip(@first_range, :int8_range, 39999...39999) end - def test_exclude_beginning_for_subtypes_with_succ_method_is_deprecated - tz = ::ActiveRecord::Base.default_timezone - - silence_warnings { - assert_deprecated { - range = PostgresqlRange.create!(date_range: "(''2012-01-02'', ''2012-01-04'']") - assert_equal Date.new(2012, 1, 3)..Date.new(2012, 1, 4), range.date_range - } - assert_deprecated { - range = PostgresqlRange.create!(ts_range: "(''2010-01-01 14:30'', ''2011-01-01 14:30'']") - assert_equal Time.send(tz, 2010, 1, 1, 14, 30, 1)..Time.send(tz, 2011, 1, 1, 14, 30, 0), range.ts_range - } - assert_deprecated { - range = PostgresqlRange.create!(tstz_range: "(''2010-01-01 14:30:00+05'', ''2011-01-01 14:30:00-03'']") - assert_equal Time.parse('2010-01-01 09:30:01 UTC')..Time.parse('2011-01-01 17:30:00 UTC'), range.tstz_range - } - assert_deprecated { - range = PostgresqlRange.create!(int4_range: "(1, 10]") - assert_equal 2..10, range.int4_range - } - assert_deprecated { - range = PostgresqlRange.create!(int8_range: "(10, 100]") - assert_equal 11..100, range.int8_range - } - } - end - def test_exclude_beginning_for_subtypes_without_succ_method_is_not_supported assert_raises(ArgumentError) { PostgresqlRange.create!(num_range: "(0.1, 0.2]") } assert_raises(ArgumentError) { PostgresqlRange.create!(float_range: "(0.5, 0.7]") } + assert_raises(ArgumentError) { PostgresqlRange.create!(int4_range: "(1, 10]") } + assert_raises(ArgumentError) { PostgresqlRange.create!(int8_range: "(10, 100]") } + assert_raises(ArgumentError) { PostgresqlRange.create!(date_range: "(''2012-01-02'', ''2012-01-04'']") } + assert_raises(ArgumentError) { PostgresqlRange.create!(ts_range: "(''2010-01-01 14:30'', ''2011-01-01 14:30'']") } + assert_raises(ArgumentError) { PostgresqlRange.create!(tstz_range: "(''2010-01-01 14:30:00+05'', ''2011-01-01 14:30:00-03'']") } end def test_update_all_with_ranges diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index d5d2dd16e2..7d2fae69d5 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -51,7 +51,7 @@ class PostgresqlUUIDTest < ActiveRecord::TestCase assert_equal "uuid", column.sql_type assert_not column.number? assert_not column.binary? - assert_not column.array + assert_not column.array? end def test_treat_blank_uuid_as_nil diff --git a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb index df497e761c..274e358e4a 100644 --- a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb @@ -85,9 +85,9 @@ module ActiveRecord def test_quoting_binary_strings value = "hello".encode('ascii-8bit') - column = Column.new(nil, 1, SQLite3String.new) + type = SQLite3String.new - assert_equal "'hello'", @conn.quote(value, column) + assert_equal "'hello'", @conn.quote(type.type_cast_for_database(value)) end end end diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb index 025c9fe6f9..f4e8003bc3 100644 --- a/activerecord/test/cases/ar_schema_test.rb +++ b/activerecord/test/cases/ar_schema_test.rb @@ -93,69 +93,38 @@ if ActiveRecord::Base.connection.supports_migrations? assert_equal "20131219224947", ActiveRecord::SchemaMigration.normalize_migration_number("20131219224947") end - def test_timestamps_without_null_is_deprecated_on_create_table - assert_deprecated do - ActiveRecord::Schema.define do - create_table :has_timestamps do |t| - t.timestamps - end + def test_timestamps_without_null_set_null_to_false_on_create_table + ActiveRecord::Schema.define do + create_table :has_timestamps do |t| + t.timestamps end end + + assert !@connection.columns(:has_timestamps).find { |c| c.name == 'created_at' }.null + assert !@connection.columns(:has_timestamps).find { |c| c.name == 'updated_at' }.null end - def test_timestamps_without_null_is_deprecated_on_change_table - assert_deprecated do - ActiveRecord::Schema.define do - create_table :has_timestamps + def test_timestamps_without_null_set_null_to_false_on_change_table + ActiveRecord::Schema.define do + create_table :has_timestamps - change_table :has_timestamps do |t| - t.timestamps - end + change_table :has_timestamps do |t| + t.timestamps default: Time.now end end - end - def test_timestamps_without_null_is_deprecated_on_add_timestamps - assert_deprecated do - ActiveRecord::Schema.define do - create_table :has_timestamps - add_timestamps :has_timestamps - end - end + assert !@connection.columns(:has_timestamps).find { |c| c.name == 'created_at' }.null + assert !@connection.columns(:has_timestamps).find { |c| c.name == 'updated_at' }.null end - def test_no_deprecation_warning_from_timestamps_on_create_table - assert_not_deprecated do - ActiveRecord::Schema.define do - create_table :has_timestamps do |t| - t.timestamps null: true - end - - drop_table :has_timestamps - - create_table :has_timestamps do |t| - t.timestamps null: false - end - end + def test_timestamps_without_null_set_null_to_false_on_add_timestamps + ActiveRecord::Schema.define do + create_table :has_timestamps + add_timestamps :has_timestamps, default: Time.now end - end - - def test_no_deprecation_warning_from_timestamps_on_change_table - assert_not_deprecated do - ActiveRecord::Schema.define do - create_table :has_timestamps - change_table :has_timestamps do |t| - t.timestamps null: true - end - drop_table :has_timestamps - - create_table :has_timestamps - change_table :has_timestamps do |t| - t.timestamps null: false, default: Time.now - end - end - end + assert !@connection.columns(:has_timestamps).find { |c| c.name == 'created_at' }.null + assert !@connection.columns(:has_timestamps).find { |c| c.name == 'updated_at' }.null end end end diff --git a/activerecord/test/cases/associations/deprecated_counter_cache_on_has_many_through_test.rb b/activerecord/test/cases/associations/deprecated_counter_cache_on_has_many_through_test.rb deleted file mode 100644 index 48f7ddbe83..0000000000 --- a/activerecord/test/cases/associations/deprecated_counter_cache_on_has_many_through_test.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "cases/helper" - -class DeprecatedCounterCacheOnHasManyThroughTest < ActiveRecord::TestCase - class Post < ActiveRecord::Base - has_many :taggings, as: :taggable - has_many :tags, through: :taggings - end - - class Tagging < ActiveRecord::Base - belongs_to :taggable, polymorphic: true - belongs_to :tag - end - - class Tag < ActiveRecord::Base - end - - test "counter caches are updated in the database if the belongs_to association doesn't specify a counter cache" do - post = Post.create!(title: 'Hello', body: 'World!') - assert_deprecated { post.tags << Tag.create!(name: 'whatever') } - - assert_equal 1, post.tags.size - assert_equal 1, post.tags_count - assert_equal 1, post.reload.tags.size - assert_equal 1, post.reload.tags_count - end -end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index fdb437d11d..371635d20a 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -826,18 +826,6 @@ class EagerAssociationTest < ActiveRecord::TestCase ) end - def test_preload_with_interpolation - assert_deprecated do - post = Post.includes(:comments_with_interpolated_conditions).find(posts(:welcome).id) - assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions - end - - assert_deprecated do - post = Post.joins(:comments_with_interpolated_conditions).find(posts(:welcome).id) - assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions - end - end - def test_polymorphic_type_condition post = Post.all.merge!(:includes => :taggings).find(posts(:thinking).id) assert post.taggings.include?(taggings(:thinking_general)) @@ -1294,23 +1282,22 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal pets(:parrot), Owner.including_last_pet.first.last_pet end - test "include instance dependent associations is deprecated" do + test "preloading and eager loading of instance dependent associations is not supported" do message = "association scope 'posts_with_signature' is" - assert_deprecated message do - begin - Author.includes(:posts_with_signature).to_a - rescue NoMethodError - # it's expected that preloading of this association fails - end + error = assert_raises(ArgumentError) do + Author.includes(:posts_with_signature).to_a end + assert_match message, error.message - assert_deprecated message do - Author.preload(:posts_with_signature).to_a rescue NoMethodError + error = assert_raises(ArgumentError) do + Author.preload(:posts_with_signature).to_a end + assert_match message, error.message - assert_deprecated message do + error = assert_raises(ArgumentError) do Author.eager_load(:posts_with_signature).to_a end + assert_match message, error.message end test "preloading readonly association" do diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 731d433706..359503db98 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -502,7 +502,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_typecast_attribute_from_select_to_false Topic.create(:title => 'Budget') # Oracle does not support boolean expressions in SELECT - if current_adapter?(:OracleAdapter) + if current_adapter?(:OracleAdapter, :FbAdapter) topic = Topic.all.merge!(:select => "topics.*, 0 as is_test").first else topic = Topic.all.merge!(:select => "topics.*, 1=2 as is_test").first @@ -513,7 +513,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_typecast_attribute_from_select_to_true Topic.create(:title => 'Budget') # Oracle does not support boolean expressions in SELECT - if current_adapter?(:OracleAdapter) + if current_adapter?(:OracleAdapter, :FbAdapter) topic = Topic.all.merge!(:select => "topics.*, 1 as is_test").first else topic = Topic.all.merge!(:select => "topics.*, 2=2 as is_test").first @@ -531,20 +531,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end - def test_deprecated_cache_attributes - assert_deprecated do - Topic.cache_attributes :replies_count - end - - assert_deprecated do - Topic.cached_attributes - end - - assert_deprecated do - Topic.cache_attribute? :replies_count - end - end - def test_converted_values_are_returned_after_assignment developer = Developer.new(name: 1337, salary: "50000") @@ -902,6 +888,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase assert_not_equal ['id'], @target.column_names end + def test_came_from_user + model = @target.first + + assert_not model.id_came_from_user? + model.id = "omg" + assert model.id_came_from_user? + end + private def new_topic_like_ar_class(&block) diff --git a/activerecord/test/cases/attribute_test.rb b/activerecord/test/cases/attribute_test.rb index 7b325abf1d..39a976fcc8 100644 --- a/activerecord/test/cases/attribute_test.rb +++ b/activerecord/test/cases/attribute_test.rb @@ -5,6 +5,7 @@ module ActiveRecord class AttributeTest < ActiveRecord::TestCase setup do @type = Minitest::Mock.new + @type.expect(:==, false, [false]) end teardown do diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 04d5a2869c..52765881d0 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -1030,6 +1030,16 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase assert_equal 'The Vile Insanity', @pirate.reload.ship.name end + def test_changed_for_autosave_should_handle_cycles + @ship.pirate = @pirate + assert_queries(0) { @ship.save! } + + @parrot = @pirate.parrots.create(name: "some_name") + @parrot.name="changed_name" + assert_queries(1) { @ship.save! } + assert_queries(0) { @ship.save! } + end + def test_should_automatically_save_bang_the_associated_model @pirate.ship.name = 'The Vile Insanity' @pirate.save! diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 6acd9aa39f..0debd30e5c 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -88,6 +88,7 @@ class BasicsTest < ActiveRecord::TestCase 'Mysql2Adapter' => '`', 'PostgreSQLAdapter' => '"', 'OracleAdapter' => '"', + 'FbAdapter' => '"' }.fetch(classname) { raise "need a bad char for #{classname}" } @@ -111,7 +112,7 @@ class BasicsTest < ActiveRecord::TestCase assert_nil Edge.primary_key end - unless current_adapter?(:PostgreSQLAdapter, :OracleAdapter, :SQLServerAdapter) + unless current_adapter?(:PostgreSQLAdapter, :OracleAdapter, :SQLServerAdapter, :FbAdapter) def test_limit_with_comma assert Topic.limit("1,2").to_a end diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index c4634d11e2..66663b3e0e 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -1,9 +1,11 @@ require 'cases/helper' require 'models/topic' +require 'models/author' +require 'models/post' module ActiveRecord class BindParameterTest < ActiveRecord::TestCase - fixtures :topics + fixtures :topics, :authors, :posts class LogListener attr_accessor :calls @@ -30,6 +32,12 @@ module ActiveRecord end if ActiveRecord::Base.connection.supports_statement_cache? + def test_bind_from_join_in_subquery + subquery = Author.joins(:thinking_posts).where(name: 'David') + scope = Author.from(subquery, 'authors').where(id: 1) + assert_equal 1, scope.count + end + def test_binds_are_logged sub = @connection.substitute_at(@pk) binds = [[@pk, 1]] diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index d4cc081f32..670d94dc06 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -49,6 +49,11 @@ class CallbackDeveloperWithFalseValidation < CallbackDeveloper before_validation proc { |model| model.history << [:before_validation, :should_never_get_here] } end +class CallbackDeveloperWithHaltedValidation < CallbackDeveloper + before_validation proc { |model| model.history << [:before_validation, :throwing_abort]; throw(:abort) } + before_validation proc { |model| model.history << [:before_validation, :should_never_get_here] } +end + class ParentDeveloper < ActiveRecord::Base self.table_name = 'developers' attr_accessor :after_save_called @@ -73,6 +78,20 @@ class ImmutableDeveloper < ActiveRecord::Base end end +class DeveloperWithCanceledCallbacks < ActiveRecord::Base + self.table_name = 'developers' + + validates_inclusion_of :salary, in: 50000..200000 + + before_save :cancel + before_destroy :cancel + + private + def cancel + throw(:abort) + end +end + class OnCallbacksDeveloper < ActiveRecord::Base self.table_name = 'developers' @@ -136,6 +155,23 @@ class CallbackCancellationDeveloper < ActiveRecord::Base after_destroy { @after_destroy_called = true } end +class CallbackHaltedDeveloper < ActiveRecord::Base + self.table_name = 'developers' + + 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 { throw(:abort) if defined?(@cancel_before_save) } + before_create { throw(:abort) if @cancel_before_create } + before_update { throw(:abort) if @cancel_before_update } + before_destroy { throw(:abort) if @cancel_before_destroy } + + after_save { @after_save_called = true } + after_update { @after_update_called = true } + after_create { @after_create_called = true } + after_destroy { @after_destroy_called = true } +end + class CallbacksTest < ActiveRecord::TestCase fixtures :developers @@ -393,12 +429,14 @@ class CallbacksTest < ActiveRecord::TestCase ], david.history end - def test_before_save_returning_false + def test_deprecated_before_save_returning_false david = ImmutableDeveloper.find(1) - assert david.valid? - assert !david.save - exc = assert_raise(ActiveRecord::RecordNotSaved) { david.save! } - assert_equal exc.record, david + assert_deprecated do + assert david.valid? + assert !david.save + exc = assert_raise(ActiveRecord::RecordNotSaved) { david.save! } + assert_equal exc.record, david + end david = ImmutableDeveloper.find(1) david.salary = 10_000_000 @@ -408,38 +446,48 @@ class CallbacksTest < ActiveRecord::TestCase someone = CallbackCancellationDeveloper.find(1) someone.cancel_before_save = true - assert someone.valid? - assert !someone.save + assert_deprecated do + assert someone.valid? + assert !someone.save + end assert_save_callbacks_not_called(someone) end - def test_before_create_returning_false + def test_deprecated_before_create_returning_false someone = CallbackCancellationDeveloper.new someone.cancel_before_create = true - assert someone.valid? - assert !someone.save + assert_deprecated do + assert someone.valid? + assert !someone.save + end assert_save_callbacks_not_called(someone) end - def test_before_update_returning_false + def test_deprecated_before_update_returning_false someone = CallbackCancellationDeveloper.find(1) someone.cancel_before_update = true - assert someone.valid? - assert !someone.save + assert_deprecated do + assert someone.valid? + assert !someone.save + end assert_save_callbacks_not_called(someone) end - def test_before_destroy_returning_false + def test_deprecated_before_destroy_returning_false david = ImmutableDeveloper.find(1) - assert !david.destroy - exc = assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! } - assert_equal exc.record, david + assert_deprecated do + assert !david.destroy + exc = assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! } + assert_equal exc.record, david + end assert_not_nil ImmutableDeveloper.find_by_id(1) someone = CallbackCancellationDeveloper.find(1) someone.cancel_before_destroy = true - assert !someone.destroy - assert_raise(ActiveRecord::RecordNotDestroyed) { someone.destroy! } + assert_deprecated do + assert !someone.destroy + assert_raise(ActiveRecord::RecordNotDestroyed) { someone.destroy! } + end assert !someone.after_destroy_called end @@ -450,9 +498,59 @@ class CallbacksTest < ActiveRecord::TestCase end private :assert_save_callbacks_not_called + def test_before_create_throwing_abort + someone = CallbackHaltedDeveloper.new + someone.cancel_before_create = true + assert someone.valid? + assert !someone.save + assert_save_callbacks_not_called(someone) + end + + def test_before_save_throwing_abort + david = DeveloperWithCanceledCallbacks.find(1) + assert david.valid? + assert !david.save + exc = assert_raise(ActiveRecord::RecordNotSaved) { david.save! } + assert_equal exc.record, david + + david = DeveloperWithCanceledCallbacks.find(1) + david.salary = 10_000_000 + assert !david.valid? + assert !david.save + assert_raise(ActiveRecord::RecordInvalid) { david.save! } + + someone = CallbackHaltedDeveloper.find(1) + someone.cancel_before_save = true + assert someone.valid? + assert !someone.save + assert_save_callbacks_not_called(someone) + end + + def test_before_update_throwing_abort + someone = CallbackHaltedDeveloper.find(1) + someone.cancel_before_update = true + assert someone.valid? + assert !someone.save + assert_save_callbacks_not_called(someone) + end + + def test_before_destroy_throwing_abort + david = DeveloperWithCanceledCallbacks.find(1) + assert !david.destroy + exc = assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! } + assert_equal exc.record, david + assert_not_nil ImmutableDeveloper.find_by_id(1) + + someone = CallbackHaltedDeveloper.find(1) + someone.cancel_before_destroy = true + assert !someone.destroy + assert_raise(ActiveRecord::RecordNotDestroyed) { someone.destroy! } + assert !someone.after_destroy_called + end + def test_callback_returning_false david = CallbackDeveloperWithFalseValidation.find(1) - david.save + assert_deprecated { david.save } assert_equal [ [ :after_find, :method ], [ :after_find, :string ], @@ -478,6 +576,34 @@ class CallbacksTest < ActiveRecord::TestCase ], david.history end + def test_callback_throwing_abort + david = CallbackDeveloperWithHaltedValidation.find(1) + david.save + assert_equal [ + [ :after_find, :method ], + [ :after_find, :string ], + [ :after_find, :proc ], + [ :after_find, :object ], + [ :after_find, :block ], + [ :after_initialize, :method ], + [ :after_initialize, :string ], + [ :after_initialize, :proc ], + [ :after_initialize, :object ], + [ :after_initialize, :block ], + [ :before_validation, :method ], + [ :before_validation, :string ], + [ :before_validation, :proc ], + [ :before_validation, :object ], + [ :before_validation, :block ], + [ :before_validation, :throwing_abort ], + [ :after_rollback, :block ], + [ :after_rollback, :object ], + [ :after_rollback, :proc ], + [ :after_rollback, :string ], + [ :after_rollback, :method ], + ], david.history + end + def test_inheritance_of_callbacks parent = ParentDeveloper.new assert !parent.after_save_called diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index 3e33b30144..b72f8ca88c 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -44,9 +44,7 @@ module ActiveRecord end def test_connection_pools - assert_deprecated do - assert_equal({ Base.connection_pool.spec => @pool }, @handler.connection_pools) - end + assert_equal([@pool], @handler.connection_pools) end end end diff --git a/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb b/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb index 37ad469476..9ee92a3cd2 100644 --- a/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb +++ b/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb @@ -51,34 +51,6 @@ module ActiveRecord assert_equal expected, actual end - def test_resolver_with_database_uri_and_and_current_env_string_key - ENV['DATABASE_URL'] = "postgres://localhost/foo" - config = { "default_env" => { "adapter" => "not_postgres", "database" => "not_foo" } } - actual = assert_deprecated { resolve_spec("default_env", config) } - expected = { "adapter"=>"postgresql", "database"=>"foo", "host"=>"localhost" } - assert_equal expected, actual - end - - def test_resolver_with_database_uri_and_and_current_env_string_key_and_rails_env - ENV['DATABASE_URL'] = "postgres://localhost/foo" - ENV['RAILS_ENV'] = "foo" - - config = { "not_production" => {"adapter" => "not_postgres", "database" => "not_foo" } } - actual = assert_deprecated { resolve_spec("foo", config) } - expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost" } - assert_equal expected, actual - end - - def test_resolver_with_database_uri_and_and_current_env_string_key_and_rack_env - ENV['DATABASE_URL'] = "postgres://localhost/foo" - ENV['RACK_ENV'] = "foo" - - config = { "not_production" => {"adapter" => "not_postgres", "database" => "not_foo" } } - actual = assert_deprecated { resolve_spec("foo", config) } - expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost" } - assert_equal expected, actual - end - def test_resolver_with_database_uri_and_known_key ENV['DATABASE_URL'] = "postgres://localhost/foo" config = { "production" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" } } @@ -95,16 +67,6 @@ module ActiveRecord end end - def test_resolver_with_database_uri_and_unknown_string_key - ENV['DATABASE_URL'] = "postgres://localhost/foo" - config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } } - assert_deprecated do - assert_raises AdapterNotSpecified do - resolve_spec("production", config) - end - end - end - def test_resolver_with_database_uri_and_supplied_url ENV['DATABASE_URL'] = "not-postgres://not-localhost/not_foo" config = { "production" => { "adapter" => "also_not_postgres", "database" => "also_not_foo" } } diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index 98cf60a8c4..ae4a8aab2c 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -165,18 +165,6 @@ class DirtyTest < ActiveRecord::TestCase assert_equal parrot.name_change, parrot.title_change end - def test_reset_attribute! - pirate = Pirate.create!(:catchphrase => 'Yar!') - pirate.catchphrase = 'Ahoy!' - - assert_deprecated do - pirate.reset_catchphrase! - end - assert_equal "Yar!", pirate.catchphrase - assert_equal Hash.new, pirate.changes - assert !pirate.catchphrase_changed? - end - def test_restore_attribute! pirate = Pirate.create!(:catchphrase => 'Yar!') pirate.catchphrase = 'Ahoy!' @@ -720,6 +708,19 @@ class DirtyTest < ActiveRecord::TestCase assert model.first_name_changed? end + test "attribute_will_change! doesn't try to save non-persistable attributes" do + klass = Class.new(ActiveRecord::Base) do + self.table_name = 'people' + attribute :non_persisted_attribute, ActiveRecord::Type::String.new + end + + record = klass.new(first_name: "Sean") + record.non_persisted_attribute_will_change! + + assert record.non_persisted_attribute_changed? + assert record.save + end + private def with_partial_writes(klass, on = true) old = klass.partial_writes? diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 02dc5d3ad3..39308866ee 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -55,7 +55,7 @@ class FinderTest < ActiveRecord::TestCase end def test_symbols_table_ref - gc_disabled = GC.disable if RUBY_VERSION >= '2.2.0' + gc_disabled = GC.disable Post.where("author_id" => nil) # warm up x = Symbol.all_symbols.count Post.where("title" => {"xxxqqqq" => "bar"}) diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 9edeb8b47f..07ec08ccf5 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -792,6 +792,10 @@ class FoxyFixturesTest < ActiveRecord::TestCase assert_equal("X marks the spot!", pirates(:mark).catchphrase) end + def test_supports_label_interpolation_for_fixnum_label + assert_equal("#1 pirate!", pirates(1).catchphrase) + end + def test_supports_polymorphic_belongs_to assert_equal(pirates(:redbeard), treasures(:sapphire).looter) assert_equal(parrots(:louis), treasures(:ruby).looter) diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 80ac57ec7c..925491acbd 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -24,9 +24,6 @@ ActiveSupport::Deprecation.debug = true # Disable available locale checks to avoid warnings running the test suite. I18n.enforce_available_locales = false -# Enable raise errors in after_commit and after_rollback. -ActiveRecord::Base.raise_in_transactional_callbacks = true - # Connect to the database ARTest.connect diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index ee43f07dd7..848174df06 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -215,10 +215,12 @@ class OptimisticLockingTest < ActiveRecord::TestCase def test_lock_with_custom_column_without_default_sets_version_to_zero t1 = LockWithCustomColumnWithoutDefault.new assert_equal 0, t1.custom_lock_version + assert_nil t1.custom_lock_version_before_type_cast - t1.save - t1 = LockWithCustomColumnWithoutDefault.find(t1.id) + t1.save! + t1.reload assert_equal 0, t1.custom_lock_version + assert [0, "0"].include?(t1.custom_lock_version_before_type_cast) end def test_readonly_attributes diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index a578e81844..97c0350911 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -125,12 +125,5 @@ class LogSubscriberTest < ActiveRecord::TestCase wait assert_match(/<16 bytes of binary data>/, @logger.logged(:debug).join) end - - def test_nil_binary_data_is_logged - binary = Binary.create(data: "") - binary.update_attributes(data: nil) - wait - assert_match(/<NULL binary data>/, @logger.logged(:debug).join) - end end end diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb index d774cfebc4..b3129a8984 100644 --- a/activerecord/test/cases/migration/change_schema_test.rb +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -82,7 +82,7 @@ module ActiveRecord columns = connection.columns(:testings) array_column = columns.detect { |c| c.name == "foo" } - assert array_column.array + assert array_column.array? end def test_create_table_with_array_column @@ -93,7 +93,7 @@ module ActiveRecord columns = connection.columns(:testings) array_column = columns.detect { |c| c.name == "foo" } - assert array_column.array + assert array_column.array? end end @@ -195,32 +195,29 @@ module ActiveRecord end def test_create_table_with_timestamps_should_create_datetime_columns - # FIXME: Remove the silence when we change the default `null` behavior - ActiveSupport::Deprecation.silence do - connection.create_table table_name do |t| - t.timestamps - end + connection.create_table table_name do |t| + t.timestamps end created_columns = connection.columns(table_name) created_at_column = created_columns.detect {|c| c.name == 'created_at' } updated_at_column = created_columns.detect {|c| c.name == 'updated_at' } - assert created_at_column.null - assert updated_at_column.null + assert !created_at_column.null + assert !updated_at_column.null end def test_create_table_with_timestamps_should_create_datetime_columns_with_options connection.create_table table_name do |t| - t.timestamps :null => false + t.timestamps null: true end created_columns = connection.columns(table_name) created_at_column = created_columns.detect {|c| c.name == 'created_at' } updated_at_column = created_columns.detect {|c| c.name == 'updated_at' } - assert !created_at_column.null - assert !updated_at_column.null + assert created_at_column.null + assert updated_at_column.null end def test_create_table_without_a_block diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index 51e21528c2..f8b1bf8c9d 100644 --- a/activerecord/test/cases/migration/foreign_key_test.rb +++ b/activerecord/test/cases/migration/foreign_key_test.rb @@ -29,7 +29,7 @@ module ActiveRecord teardown do if defined?(@connection) - @connection.drop_table "astronauts" if @connection.table_exists? 'astronauts' + @connection.drop_table "astronauts" if @connection.table_exists? 'astronauts' @connection.drop_table "rockets" if @connection.table_exists? 'rockets' end end @@ -220,6 +220,18 @@ module ActiveRecord ensure silence_stream($stdout) { migration.migrate(:down) } end + + private + + def silence_stream(stream) + old_stream = stream.dup + stream.reopen(IO::NULL) + stream.sync = true + yield + ensure + stream.reopen(old_stream) + old_stream.close + end end end end diff --git a/activerecord/test/cases/migration/rename_table_test.rb b/activerecord/test/cases/migration/rename_table_test.rb index c8b3f75e10..a018bac43d 100644 --- a/activerecord/test/cases/migration/rename_table_test.rb +++ b/activerecord/test/cases/migration/rename_table_test.rb @@ -39,33 +39,35 @@ module ActiveRecord end end - def test_rename_table - rename_table :test_models, :octopi + unless current_adapter?(:FbAdapter) # Firebird cannot rename tables + def test_rename_table + rename_table :test_models, :octopi - connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" + connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" - assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1") - end + assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1") + end - def test_rename_table_with_an_index - add_index :test_models, :url + def test_rename_table_with_an_index + add_index :test_models, :url - rename_table :test_models, :octopi + rename_table :test_models, :octopi - connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" + connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" - assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1") - index = connection.indexes(:octopi).first - assert index.columns.include?("url") - assert_equal 'index_octopi_on_url', index.name - end + assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1") + index = connection.indexes(:octopi).first + assert index.columns.include?("url") + assert_equal 'index_octopi_on_url', index.name + end - def test_rename_table_does_not_rename_custom_named_index - add_index :test_models, :url, name: 'special_url_idx' + def test_rename_table_does_not_rename_custom_named_index + add_index :test_models, :url, name: 'special_url_idx' - rename_table :test_models, :octopi + rename_table :test_models, :octopi - assert_equal ['special_url_idx'], connection.indexes(:octopi).map(&:name) + assert_equal ['special_url_idx'], connection.indexes(:octopi).map(&:name) + end end if current_adapter?(:PostgreSQLAdapter) diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 3192b797b4..7c2d3e81d6 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -936,4 +936,14 @@ class CopyMigrationsTest < ActiveRecord::TestCase end end end + + def silence_stream(stream) + old_stream = stream.dup + stream.reopen(IO::NULL) + stream.sync = true + yield + ensure + stream.reopen(old_stream) + old_stream.close + end end diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index 3831de6ae3..15c60d5562 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -93,6 +93,13 @@ class MultipleDbTest < ActiveRecord::TestCase assert_not_equal Entrant.arel_engine.connection, Course.arel_engine.connection end + def test_count_on_custom_connection + ActiveRecord::Base.remove_connection + assert_equal 1, College.count + ensure + ActiveRecord::Base.establish_connection :arunit + end + unless in_memory_db? def test_associations_should_work_when_model_has_no_connection begin diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb index 1d6ae2f67f..ad09340518 100644 --- a/activerecord/test/cases/quoting_test.rb +++ b/activerecord/test/cases/quoting_test.rb @@ -125,14 +125,11 @@ module ActiveRecord end def test_crazy_object - crazy = Class.new.new - expected = "'#{YAML.dump(crazy)}'" - assert_equal expected, @quoter.quote(crazy, nil) - end - - def test_crazy_object_calls_quote_string - crazy = Class.new { def initialize; @lol = 'lo\l' end }.new - assert_match "lo\\\\l", @quoter.quote(crazy, nil) + crazy = Object.new + e = assert_raises(TypeError) do + @quoter.quote(crazy, nil) + end + assert_equal "can't quote Object", e.message end def test_quote_string_no_column diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index e86b892a0a..a2252a836f 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -80,10 +80,24 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal :integer, @first.column_for_attribute("id").type end - def test_non_existent_columns_return_nil - assert_deprecated do - assert_nil @first.column_for_attribute("attribute_that_doesnt_exist") - end + def test_non_existent_columns_return_null_object + column = @first.column_for_attribute("attribute_that_doesnt_exist") + assert_instance_of ActiveRecord::ConnectionAdapters::NullColumn, column + assert_equal "attribute_that_doesnt_exist", column.name + assert_equal nil, column.sql_type + assert_equal nil, column.type + assert_not column.number? + assert_not column.text? + assert_not column.binary? + end + + def test_non_existent_columns_are_identity_types + column = @first.column_for_attribute("attribute_that_doesnt_exist") + object = Object.new + + assert_equal object, column.type_cast_from_database(object) + assert_equal object, column.type_cast_from_user(object) + assert_equal object, column.type_cast_for_database(object) end def test_reflection_klass_for_nested_class_name diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb index d675953da6..b0573579da 100644 --- a/activerecord/test/cases/relation/where_test.rb +++ b/activerecord/test/cases/relation/where_test.rb @@ -1,13 +1,15 @@ require "cases/helper" -require 'models/author' -require 'models/price_estimate' -require 'models/treasure' -require 'models/post' -require 'models/comment' -require 'models/edge' -require 'models/topic' -require 'models/binary' -require 'models/vertex' +require "models/author" +require "models/binary" +require "models/cake_designer" +require "models/chef" +require "models/comment" +require "models/edge" +require "models/post" +require "models/price_estimate" +require "models/topic" +require "models/treasure" +require "models/vertex" module ActiveRecord class WhereTest < ActiveRecord::TestCase @@ -26,6 +28,16 @@ module ActiveRecord } end + def test_where_copies_arel_bind_params + chef = Chef.create! + CakeDesigner.create!(chef: chef) + + cake_designers = CakeDesigner.joins(:chef).where(chefs: { id: chef.id }) + chefs = Chef.where(employable: cake_designers) + + assert_equal [chef], chefs.to_a + end + def test_rewhere_on_root assert_equal posts(:welcome), Post.rewhere(title: 'Welcome to the weblog').first end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index fb9258c038..9631ea79be 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -1382,12 +1382,6 @@ class RelationTest < ActiveRecord::TestCase assert_equal "id", Post.all.primary_key end - def test_disable_implicit_join_references_is_deprecated - assert_deprecated do - ActiveRecord::Base.disable_implicit_join_references = true - end - end - def test_ordering_with_extra_spaces assert_equal authors(:david), Author.order('id DESC , name DESC').last end @@ -1657,6 +1651,14 @@ class RelationTest < ActiveRecord::TestCase end end + test "relations with cached arel can't be mutated [internal API]" do + relation = Post.all + relation.count + + assert_raises(ActiveRecord::ImmutableRelation) { relation.limit!(5) } + assert_raises(ActiveRecord::ImmutableRelation) { relation.where!("1 = 2") } + end + test "relations show the records in #inspect" do relation = Post.limit(2) assert_equal "#<ActiveRecord::Relation [#{Post.limit(2).map(&:inspect).join(', ')}]>", relation.inspect diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb index f477cf7d92..262e0abc22 100644 --- a/activerecord/test/cases/sanitize_test.rb +++ b/activerecord/test/cases/sanitize_test.rb @@ -7,17 +7,6 @@ class SanitizeTest < ActiveRecord::TestCase def setup end - def test_sanitize_sql_hash_handles_associations - quoted_bambi = ActiveRecord::Base.connection.quote("Bambi") - quoted_column_name = ActiveRecord::Base.connection.quote_column_name("name") - quoted_table_name = ActiveRecord::Base.connection.quote_table_name("adorable_animals") - expected_value = "#{quoted_table_name}.#{quoted_column_name} = #{quoted_bambi}" - - assert_deprecated do - assert_equal expected_value, Binary.send(:sanitize_sql_hash, {adorable_animals: {name: 'Bambi'}}) - end - end - def test_sanitize_sql_array_handles_string_interpolation quoted_bambi = ActiveRecord::Base.connection.quote_string("Bambi") assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi"]) diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 57b7346503..b52c66356c 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -272,6 +272,8 @@ class SchemaDumperTest < ActiveRecord::TestCase # Oracle supports precision up to 38 and it identifies decimals with scale 0 as integers if current_adapter?(:OracleAdapter) assert_match %r{t.integer\s+"atoms_in_universe",\s+precision: 38}, output + elsif current_adapter?(:FbAdapter) + assert_match %r{t.integer\s+"atoms_in_universe",\s+precision: 18}, output else assert_match %r{t.decimal\s+"atoms_in_universe",\s+precision: 55}, output end diff --git a/activerecord/test/cases/secure_token_test.rb b/activerecord/test/cases/secure_token_test.rb new file mode 100644 index 0000000000..3f7455d12d --- /dev/null +++ b/activerecord/test/cases/secure_token_test.rb @@ -0,0 +1,25 @@ +require 'cases/helper' +require 'models/user' + +class SecureTokenTest < ActiveRecord::TestCase + setup do + @user = User.new + end + + def test_token_values_are_generated_for_specified_attributes_and_persisted_on_save + @user.save + assert_not_nil @user.token + assert_not_nil @user.auth_token + end + + def test_regenerating_the_secure_token + @user.save + old_token = @user.token + old_auth_token = @user.auth_token + @user.regenerate_token + @user.regenerate_auth_token + + assert_not_equal @user.token, old_token + assert_not_equal @user.auth_token, old_auth_token + end +end diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index c261a5b1c0..e29f7462c8 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -22,12 +22,6 @@ class SerializedAttributeTest < ActiveRecord::TestCase end end - def test_list_of_serialized_attributes - assert_deprecated do - assert_equal %w(content), Topic.serialized_attributes.keys - end - end - def test_serialized_attribute Topic.serialize("content", MyObject) diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index 0f5caa52e3..185fc22e98 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -266,47 +266,6 @@ class TransactionCallbacksTest < ActiveRecord::TestCase assert_equal 2, @first.rollbacks end - def test_after_transaction_callbacks_should_prevent_callbacks_from_being_called - old_transaction_config = ActiveRecord::Base.raise_in_transactional_callbacks - ActiveRecord::Base.raise_in_transactional_callbacks = false - - def @first.last_after_transaction_error=(e); @last_transaction_error = e; end - def @first.last_after_transaction_error; @last_transaction_error; end - @first.after_commit_block{|r| r.last_after_transaction_error = :commit; raise "fail!";} - @first.after_rollback_block{|r| r.last_after_transaction_error = :rollback; raise "fail!";} - - second = TopicWithCallbacks.find(3) - second.after_commit_block{|r| r.history << :after_commit} - second.after_rollback_block{|r| r.history << :after_rollback} - - Topic.transaction do - @first.save! - second.save! - end - assert_equal :commit, @first.last_after_transaction_error - assert_equal [:after_commit], second.history - - second.history.clear - Topic.transaction do - @first.save! - second.save! - raise ActiveRecord::Rollback - end - assert_equal :rollback, @first.last_after_transaction_error - assert_equal [:after_rollback], second.history - ensure - ActiveRecord::Base.raise_in_transactional_callbacks = old_transaction_config - end - - def test_after_commit_should_not_raise_when_raise_in_transactional_callbacks_false - old_transaction_config = ActiveRecord::Base.raise_in_transactional_callbacks - ActiveRecord::Base.raise_in_transactional_callbacks = false - @first.after_commit_block{ fail "boom" } - Topic.transaction { @first.save! } - ensure - ActiveRecord::Base.raise_in_transactional_callbacks = old_transaction_config - end - def test_after_commit_callback_should_not_swallow_errors @first.after_commit_block{ fail "boom" } assert_raises(RuntimeError) do diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 0bbb4bb79e..d1d8e71c34 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -194,6 +194,16 @@ class TransactionTest < ActiveRecord::TestCase assert_equal posts_count, author.posts(true).size end + def test_cancellation_from_returning_false_in_before_filter + def @first.before_save_for_transaction + false + end + + assert_deprecated do + @first.save + end + end + def test_cancellation_from_before_destroy_rollbacks_in_destroy add_cancelling_before_destroy_with_db_side_effect_to_topic @first nbooks_before_destroy = Book.count @@ -493,35 +503,32 @@ class TransactionTest < ActiveRecord::TestCase assert topic.frozen?, 'not frozen' end - # The behavior of killed threads having a status of "aborting" was changed - # in Ruby 2.0, so Thread#kill on 1.9 will prematurely commit the transaction - # and there's nothing we can do about it. - if !RUBY_VERSION.start_with?('1.9') && !in_memory_db? - def test_rollback_when_thread_killed - queue = Queue.new - thread = Thread.new do - Topic.transaction do - @first.approved = true - @second.approved = false - @first.save + def test_rollback_when_thread_killed + return if in_memory_db? - queue.push nil - sleep + queue = Queue.new + thread = Thread.new do + Topic.transaction do + @first.approved = true + @second.approved = false + @first.save - @second.save - end + queue.push nil + sleep + + @second.save end + end - queue.pop - thread.kill - thread.join + queue.pop + thread.kill + thread.join - assert @first.approved?, "First should still be changed in the objects" - assert !@second.approved?, "Second should still be changed in the objects" + assert @first.approved?, "First should still be changed in the objects" + assert !@second.approved?, "Second should still be changed in the objects" - assert !Topic.find(1).approved?, "First shouldn't have been approved" - assert Topic.find(2).approved?, "Second should still be approved" - end + assert !Topic.find(1).approved?, "First shouldn't have been approved" + assert Topic.find(2).approved?, "Second should still be approved" end def test_restore_active_record_state_for_all_records_in_a_transaction @@ -643,6 +650,27 @@ class TransactionTest < ActiveRecord::TestCase assert transaction.state.committed? end + def test_transaction_rollback_with_primarykeyless_tables + connection = ActiveRecord::Base.connection + connection.create_table(:transaction_without_primary_keys, force: true, id: false) do |t| + t.integer :thing_id + end + + klass = Class.new(ActiveRecord::Base) do + self.table_name = 'transaction_without_primary_keys' + after_commit { } # necessary to trigger the has_transactional_callbacks branch + end + + assert_no_difference(-> { klass.count }) do + ActiveRecord::Base.transaction do + klass.create! + raise ActiveRecord::Rollback + end + end + ensure + connection.execute("DROP TABLE IF EXISTS transaction_without_primary_keys") + end + private %w(validation save destroy).each do |filter| @@ -650,7 +678,7 @@ class TransactionTest < ActiveRecord::TestCase meta = class << topic; self; end meta.send("define_method", "before_#{filter}_for_transaction") do Book.create - false + throw(:abort) end end end diff --git a/activerecord/test/cases/types_test.rb b/activerecord/test/cases/types_test.rb index b0979cbe1f..73e92addfe 100644 --- a/activerecord/test/cases/types_test.rb +++ b/activerecord/test/cases/types_test.rb @@ -17,6 +17,10 @@ module ActiveRecord assert type.type_cast_from_user('TRUE') assert type.type_cast_from_user('on') assert type.type_cast_from_user('ON') + assert type.type_cast_from_user(' ') + assert type.type_cast_from_user("\u3000\r\n") + assert type.type_cast_from_user("\u0000") + assert type.type_cast_from_user('SOMETHING RANDOM') # explicitly check for false vs nil assert_equal false, type.type_cast_from_user(false) @@ -28,12 +32,6 @@ module ActiveRecord assert_equal false, type.type_cast_from_user('FALSE') assert_equal false, type.type_cast_from_user('off') assert_equal false, type.type_cast_from_user('OFF') - assert_deprecated do - assert_equal false, type.type_cast_from_user(' ') - assert_equal false, type.type_cast_from_user("\u3000\r\n") - assert_equal false, type.type_cast_from_user("\u0000") - assert_equal false, type.type_cast_from_user('SOMETHING RANDOM') - end end def test_type_cast_float diff --git a/activerecord/test/fixtures/pirates.yml b/activerecord/test/fixtures/pirates.yml index 1bb3bf0051..0b1a785853 100644 --- a/activerecord/test/fixtures/pirates.yml +++ b/activerecord/test/fixtures/pirates.yml @@ -10,3 +10,6 @@ redbeard: mark: catchphrase: "X $LABELs the spot!" + +1: + catchphrase: "#$LABEL pirate!" diff --git a/activerecord/test/models/bird.rb b/activerecord/test/models/bird.rb index dff099c1fb..2a51d903b8 100644 --- a/activerecord/test/models/bird.rb +++ b/activerecord/test/models/bird.rb @@ -7,6 +7,6 @@ class Bird < ActiveRecord::Base attr_accessor :cancel_save_from_callback before_save :cancel_save_callback_method, :if => :cancel_save_from_callback def cancel_save_callback_method - false + throw(:abort) end end diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb index 831a0d5387..a6e83fe353 100644 --- a/activerecord/test/models/bulb.rb +++ b/activerecord/test/models/bulb.rb @@ -46,6 +46,6 @@ end class FailedBulb < Bulb before_destroy do - false + throw(:abort) end end diff --git a/activerecord/test/models/parrot.rb b/activerecord/test/models/parrot.rb index 8c83de573f..b26035d944 100644 --- a/activerecord/test/models/parrot.rb +++ b/activerecord/test/models/parrot.rb @@ -11,7 +11,7 @@ class Parrot < ActiveRecord::Base attr_accessor :cancel_save_from_callback before_save :cancel_save_callback_method, :if => :cancel_save_from_callback def cancel_save_callback_method - false + throw(:abort) end end diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb index 641a33f9be..366c70f902 100644 --- a/activerecord/test/models/pirate.rb +++ b/activerecord/test/models/pirate.rb @@ -56,7 +56,7 @@ class Pirate < ActiveRecord::Base attr_accessor :cancel_save_from_callback, :parrots_limit before_save :cancel_save_callback_method, :if => :cancel_save_from_callback def cancel_save_callback_method - false + throw(:abort) end private diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 56073cc588..7b637c9e3f 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -72,10 +72,6 @@ class Post < ActiveRecord::Base through: :author_with_address, source: :author_address_extra - has_many :comments_with_interpolated_conditions, - ->(p) { where "#{"#{p.aliased_table_name}." rescue ""}body = ?", 'Thank you for the welcome' }, - :class_name => 'Comment' - has_one :very_special_comment has_one :very_special_comment_with_post, -> { includes(:post) }, :class_name => "VerySpecialComment" has_one :very_special_comment_with_post_with_joins, -> { joins(:post).order('posts.id') }, class_name: "VerySpecialComment" diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb index 5f618a50d2..c2f6d492d8 100644 --- a/activerecord/test/models/ship.rb +++ b/activerecord/test/models/ship.rb @@ -14,7 +14,7 @@ class Ship < ActiveRecord::Base attr_accessor :cancel_save_from_callback before_save :cancel_save_callback_method, :if => :cancel_save_from_callback def cancel_save_callback_method - false + throw(:abort) end end diff --git a/activerecord/test/models/user.rb b/activerecord/test/models/user.rb new file mode 100644 index 0000000000..23cd2e0e1c --- /dev/null +++ b/activerecord/test/models/user.rb @@ -0,0 +1,4 @@ +class User < ActiveRecord::Base + has_secure_token + has_secure_token :auth_token +end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 5907d6ef97..21b23d8e0c 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -479,6 +479,8 @@ ActiveRecord::Schema.define do # Oracle/SQLServer supports precision up to 38 if current_adapter?(:OracleAdapter, :SQLServerAdapter) t.decimal :atoms_in_universe, precision: 38, scale: 0 + elsif current_adapter?(:FbAdapter) + t.decimal :atoms_in_universe, precision: 18, scale: 0 else t.decimal :atoms_in_universe, precision: 55, scale: 0 end @@ -892,6 +894,11 @@ ActiveRecord::Schema.define do t.string :overloaded_string_with_limit, limit: 255 t.string :string_with_default, default: 'the original default' end + + create_table :users, force: true do |t| + t.string :token + t.string :auth_token + end end Course.connection.create_table :courses, force: true do |t| |