diff options
Diffstat (limited to 'activerecord')
127 files changed, 1173 insertions, 423 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index b5dd19988d..6c129a1c79 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,5 +1,62 @@ -* Dont enroll records in the transaction if they dont have commit callbacks. - That was causing a memory grow problem when creating a lot of records inside a transaction. +* Ignore psqlrc when loading database structure. + + *Jason Weathered* + +* Fix referencing wrong table aliases while joining tables of has many through + association (only when calling calculation methods). + + Fixes #19276. + + *pinglamb* + +* Correctly persist a serialized attribute that has been returned to + its default value by an in-place modification. + + Fixes #19467. + + *Matthew Draper* + +* Fix generating the schema file when using PostgreSQL `BigInt[]` data type. + Previously the `limit: 8` was not coming through, and this caused it to + become `Int[]` data type after rebuilding from the schema. + + Fixes #19420. + + *Jake Waller* + +* Reuse the `CollectionAssociation#reader` cache when the foreign key is + available prior to save. + + *Ben Woosley* + +* Add `config.active_record.dump_schemas` to fix `db:structure:dump` + when using schema_search_path and PostgreSQL extensions. + + Fixes #17157. + + *Ryan Wallace* + +* Renaming `use_transactional_fixtures` to `use_transactional_tests` for clarity. + + Fixes #18864. + + *Brandon Weiss* + +* Increase pg gem version requirement to `~> 0.18`. Earlier versions of the + pg gem are known to have problems with Ruby 2.2. + + *Matt Brictson* + +* Correctly dump `serial` and `bigserial`. + + *Ryuta Kamizono* + +* Fix default `format` value in `ActiveRecord::Tasks::DatabaseTasks#schema_file`. + + *James Cox* + +* Don't enroll records in the transaction if they don't have commit callbacks. + This was causing a memory leak when creating many records inside a transaction. Fixes #15549. @@ -12,11 +69,11 @@ *Sean Griffin* -* Add `SchemaMigration.create_table` support any unicode charsets for MySQL. +* Add `SchemaMigration.create_table` support for any unicode charsets with MySQL. *Ryuta Kamizono* -* PostgreSQL, no longer disables user triggers if system triggers can't be +* PostgreSQL no longer disables user triggers if system triggers can't be disabled. Disabling user triggers does not fulfill what the method promises. Rails currently requires superuser privileges for this method. @@ -30,12 +87,12 @@ *Toby Ovod-Everett*, *Yves Senn* -* PostgreSQL, print warning message if `disable_referential_integrity` fails - due to missing permissions. +* In PostgreSQL, print a warning message if `disable_referential_integrity` + fails due to missing permissions. *Andrey Nering*, *Yves Senn* -* Allow `:limit` option for MySQL bigint primary key support. +* Allow a `:limit` option for MySQL bigint primary key support. Example: @@ -58,7 +115,7 @@ *Josef Šimánek* * Fixed ActiveRecord::Relation#becomes! and changed_attributes issues for type - column. + columns. Fixes #17139. @@ -68,7 +125,7 @@ *Ryuta Kamizono* -* Allow `:precision` option for time type columns. +* Allow a `:precision` option for time type columns. *Ryuta Kamizono* @@ -85,10 +142,10 @@ recipients: commentable.recipients } end - That's what you want the bulk of the time. New comment creates a new - Notification. But there may well be off cases, like copying a commentable - and its comments, where you don't want that. So you'd have a concern - something like this: + That's what you want the bulk of the time. A new comment creates a new + Notification. There may be edge cases where you don't want that, like + when copying a commentable and its comments, in which case write a + concern with something like this: module Copyable def copy_to(destination) @@ -107,7 +164,7 @@ *Hyonjee Joo* -* Deprecated passing of `start` value to `find_in_batches` and `find_each` +* Deprecate passing of `start` value to `find_in_batches` and `find_each` in favour of `begin_at` value. *Vipul A M* @@ -116,9 +173,10 @@ *Tõnis Simo* -* Use SQL COUNT and LIMIT 1 queries for `none?` and `one?` methods if no block or limit is given, - instead of loading the entire collection to memory. - This applies to relations (e.g. `User.all`) as well as associations (e.g. `account.users`) +* Use SQL COUNT and LIMIT 1 queries for `none?` and `one?` methods + if no block or limit is given, instead of loading the entire + collection into memory. This applies to relations (e.g. `User.all`) + as well as associations (e.g. `account.users`) # Before: @@ -167,16 +225,16 @@ *Vipul A M* -* Fix rounding problem for PostgreSQL timestamp column. +* Fix a rounding problem for PostgreSQL timestamp columns. - If timestamp column have the precision, it need to format according to - the precision of timestamp column. + If a timestamp column has a precision specified, it needs to + format according to that. *Ryuta Kamizono* * Respect the database default charset for `schema_migrations` table. - The charset of `version` column in `schema_migrations` table is depend + The charset of `version` column in `schema_migrations` table depends on the database default charset and collation rather than the encoding of the connection. @@ -184,12 +242,12 @@ * Raise `ArgumentError` when passing `nil` or `false` to `Relation#merge`. - These are not valid values to merge in a relation so it should warn the users + These are not valid values to merge in a relation, so it should warn users early. *Rafael Mendonça França* -* Use `SCHEMA` instead of `DB_STRUCTURE` for specifying structure file. +* Use `SCHEMA` instead of `DB_STRUCTURE` for specifying a structure file. This makes the db:structure tasks consistent with test:load_structure. @@ -201,7 +259,7 @@ *Sean Griffin* -* Fixed several edge cases which could result in a counter cache updating +* Fix several edge cases which could result in a counter cache updating twice or not updating at all for `has_many` and `has_many :through`. Fixes #10865. @@ -234,11 +292,13 @@ *Sammy Larbi* * Change the default error message from `can't be blank` to `must exist` for - the presence validator of the `:required` option on `belongs_to`/`has_one` associations. + the presence validator of the `:required` option on `belongs_to`/`has_one` + associations. *Henrik Nygren* -* Fixed ActiveRecord::Relation#group method when argument is SQL reserved key word: +* Fixed ActiveRecord::Relation#group method when an argument is an SQL + reserved key word: Example: @@ -369,7 +429,7 @@ *Yves Senn* -* Remove deprecation when modifying a relation with cached arel. +* Remove deprecation when modifying a relation with cached Arel. This raises an `ImmutableRelation` error instead. *Yves Senn* @@ -459,13 +519,13 @@ *Florian Weingarten* -* Fixed setting of foreign_key for through associations while building of new record. +* Fix setting of foreign_key for through associations when building a new record. Fixes #12698. *Ivan Antropov* -* Improve a dump of the primary key support. If it is not a default primary key, +* Improve dumping of the primary key. If it is not a default primary key, correctly dump the type and options. Fixes #14169, #16599. @@ -483,18 +543,18 @@ *Ryuta Kamizono* -* Allow precision option for MySQL datetimes. +* Allow a precision option for MySQL datetimes. *Ryuta Kamizono* -* Fixed automatic inverse_of for models nested in module. +* Fixed automatic `inverse_of` for models nested in a module. *Andrew McCloud* * Change `ActiveRecord::Relation#update` behavior so that it can be called without passing ids of the records to be updated. - This change allows to update multiple records returned by + This change allows updating multiple records returned by `ActiveRecord::Relation` with callbacks and validations. # Before @@ -526,6 +586,13 @@ *Rafael Mendonça França* +* Fix change detection problem for PostgreSQL bytea type and + `ArgumentError: string contains null byte` exception with pg-0.18. + + Fixes #17680. + + *Lars Kanis* + * When a table has a composite primary key, the `primary_key` method for SQLite3 and PostgreSQL adapters was only returning the first field of the key. Ensures that it will return nil instead, as Active Record doesn't support @@ -535,7 +602,7 @@ *arthurnn* -* `validates_size_of` / `validates_length_of` do not count records, +* `validates_size_of` / `validates_length_of` do not count records which are `marked_for_destruction?`. Fixes #7247. @@ -577,7 +644,7 @@ *Ryuta Kamizono* -* Support for any type primary key. +* Support for any type of primary key. Fixes #14194. @@ -603,7 +670,7 @@ *Yves Senn* -* Fixes bug with 'ActiveRecord::Type::Numeric' that causes negative values to +* Fix bug with 'ActiveRecord::Type::Numeric' that caused negative values to be marked as having changed when set to the same negative value. Closes #18161. diff --git a/activerecord/Rakefile b/activerecord/Rakefile index 976b559da9..f1facac21b 100644 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -51,7 +51,7 @@ end t.libs << 'test' t.test_files = (Dir.glob( "test/cases/**/*_test.rb" ).reject { |x| x =~ /\/adapters\// - } + Dir.glob("test/cases/adapters/#{adapter_short}/**/*_test.rb")).sort + } + Dir.glob("test/cases/adapters/#{adapter_short}/**/*_test.rb")) t.warning = true t.verbose = true diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index c5cd0c89f7..c88b9e8718 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Object-relational mapper framework (part of Rails).' s.description = 'Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.' - s.required_ruby_version = '>= 2.2.0' + s.required_ruby_version = '>= 2.2.1' s.license = 'MIT' diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index ef14e065ae..58a4694880 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -43,6 +43,7 @@ module ActiveRecord autoload :Explain autoload :Inheritance autoload :Integration + autoload :LegacyYamlAdapter autoload :Migration autoload :Migrator, 'active_record/migration' autoload :ModelSchema diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index cecb2dbd0b..5e3e5f709b 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -113,19 +113,19 @@ module ActiveRecord # These classes will be loaded when associations are created. # So there is no need to eager load them. - autoload :Association, 'active_record/associations/association' - autoload :SingularAssociation, 'active_record/associations/singular_association' - autoload :CollectionAssociation, 'active_record/associations/collection_association' - autoload :ForeignAssociation, 'active_record/associations/foreign_association' - autoload :CollectionProxy, 'active_record/associations/collection_proxy' + autoload :Association + autoload :SingularAssociation + autoload :CollectionAssociation + autoload :ForeignAssociation + autoload :CollectionProxy - autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association' - autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association' - autoload :HasManyAssociation, 'active_record/associations/has_many_association' - autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association' - autoload :HasOneAssociation, 'active_record/associations/has_one_association' - autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association' - autoload :ThroughAssociation, 'active_record/associations/through_association' + autoload :BelongsToAssociation + autoload :BelongsToPolymorphicAssociation + autoload :HasManyAssociation + autoload :HasManyThroughAssociation + autoload :HasOneAssociation + autoload :HasOneThroughAssociation + autoload :ThroughAssociation module Builder #:nodoc: autoload :Association, 'active_record/associations/builder/association' @@ -139,10 +139,10 @@ module ActiveRecord end eager_autoload do - autoload :Preloader, 'active_record/associations/preloader' - autoload :JoinDependency, 'active_record/associations/join_dependency' - autoload :AssociationScope, 'active_record/associations/association_scope' - autoload :AliasTracker, 'active_record/associations/alias_tracker' + autoload :Preloader + autoload :JoinDependency + autoload :AssociationScope + autoload :AliasTracker end # Returns the association instance for the given name, instantiating it if it doesn't already exist diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index 0d8e4ba870..930f678ae8 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -8,12 +8,12 @@ module ActiveRecord # # Association # SingularAssociation - # HasOneAssociation + # HasOneAssociation + ForeignAssociation # HasOneThroughAssociation + ThroughAssociation # BelongsToAssociation # BelongsToPolymorphicAssociation # CollectionAssociation - # HasManyAssociation + # HasManyAssociation + ForeignAssociation # HasManyThroughAssociation + ThroughAssociation class Association #:nodoc: attr_reader :owner, :target, :reflection diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 82a7c27799..88531205a1 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -33,10 +33,10 @@ module ActiveRecord reload end - if owner.new_record? + if null_scope? # Cache the proxy separately before the owner has an id # or else a post-save proxy will still lack the id - @new_record_proxy ||= CollectionProxy.create(klass, self) + @null_proxy ||= CollectionProxy.create(klass, self) else @proxy ||= CollectionProxy.create(klass, self) end @@ -129,11 +129,11 @@ module ActiveRecord first_nth_or_last(:last, *args) end - def take + def take(n = nil) if loaded? - target.first + n ? target.take(n) : target.first else - scope.take.tap do |record| + scope.take(n).tap do |record| set_inverse_instance record if record.is_a? ActiveRecord::Base end end @@ -432,8 +432,7 @@ module ActiveRecord def get_records if reflection.scope_chain.any?(&:any?) || scope.eager_loading? || - klass.current_scope || - klass.default_scopes.any? + klass.scope_attributes? return scope.to_a end diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 87e80e88b2..685c3a5f17 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -227,8 +227,8 @@ module ActiveRecord @association.last(*args) end - def take - @association.take + def take(n = nil) + @association.take(n) end # Returns a new object of the collection type that has been instantiated @@ -976,6 +976,9 @@ module ActiveRecord # Equivalent to +delete_all+. The difference is that returns +self+, instead # of an array with the deleted objects, so methods can be chained. See # +delete_all+ for more information. + # Note that because +delete_all+ removes records by directly + # running an SQL query into the database, the +updated_at+ column of + # the object is not changed. def clear delete_all self diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index c44242a0f0..58d0f7d65d 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -41,8 +41,7 @@ module ActiveRecord def get_records if reflection.scope_chain.any?(&:any?) || scope.eager_loading? || - klass.current_scope || - klass.default_scopes.any? + klass.scope_attributes? return scope.limit(1).to_a end diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb index 3ce9cffdbc..af1bce523c 100644 --- a/activerecord/lib/active_record/associations/through_association.rb +++ b/activerecord/lib/active_record/associations/through_association.rb @@ -33,7 +33,7 @@ module ActiveRecord # Construct attributes for :through pointing to owner and associate. This is used by the # methods which create and delete records on the association. # - # We only support indirectly modifying through associations which has a belongs_to source. + # We only support indirectly modifying through associations which have a belongs_to source. # This is the "has_many :tags, through: :taggings" situation, where the join model # typically has a belongs_to on both side. In other words, associations which could also # be represented as has_and_belongs_to_many associations. diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb index 483d4200bd..cc265e2af6 100644 --- a/activerecord/lib/active_record/attribute_assignment.rb +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -29,6 +29,13 @@ module ActiveRecord assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty? end + # Re-raise with the ActiveRecord constant in case of an error + def _assign_attribute(k, v) # :nodoc: + super + rescue ActiveModel::UnknownAttributeError + raise UnknownAttributeError.new(self, k) + end + # Assign any deferred nested attributes after the base attributes have been set. def assign_nested_parameter_attributes(pairs) pairs.each { |k, v| _assign_attribute(k, v) } diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index c8979a60d7..50339b6f69 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -28,15 +28,18 @@ module ActiveRecord # information about providing custom type objects. # # ==== Options + # # The following options are accepted: # # +default+ The default value to use when no value is provided. If this option # is not passed, the previous default value (if any) will be used. # Otherwise, the default will be +nil+. # - # +array+ (PG only) specifies that the type should be an array (see the examples below). + # +array+ (PG only) specifies that the type should be an array (see the + # examples below). # - # +range+ (PG only) specifies that the type should be a range (see the examples below). + # +range+ (PG only) specifies that the type should be a range (see the + # examples below). # # ==== Examples # @@ -101,12 +104,11 @@ module ActiveRecord # ==== Creating Custom Types # # Users may also define their own custom types, as long as they respond - # to the methods defined on the value type. The method - # +deserialize+ or +cast+ will be called on - # your type object, with raw input from the database or from your - # controllers. See ActiveRecord::Type::Value for the expected API. It is - # recommended that your type objects inherit from an existing type, or - # from ActiveRecord::Type::Value + # to the methods defined on the value type. The method +deserialize+ or + # +cast+ will be called on your type object, with raw input from the + # database or from your controllers. See ActiveRecord::Type::Value for the + # expected API. It is recommended that your type objects inherit from an + # existing type, or from ActiveRecord::Type::Value # # class MoneyType < ActiveRecord::Type::Integer # def cast(value) @@ -150,7 +152,7 @@ module ActiveRecord # end # # # value will be the result of +deserialize+ or - # # +cast+. Assumed to be in instance of +Money+ in + # # +cast+. Assumed to be an instance of +Money+ in # # this case. # def serialize(value) # value_in_bitcoins = @currency_converter.convert_to_bitcoins(value) 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 42ad285340..42c794c828 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -136,7 +136,7 @@ module ActiveRecord # # In order to get around this problem, #transaction will emulate the effect # of nested transactions, by using savepoints: - # http://dev.mysql.com/doc/refman/5.0/en/savepoint.html + # http://dev.mysql.com/doc/refman/5.6/en/savepoint.html # Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8' # supports savepoints. # @@ -189,7 +189,7 @@ module ActiveRecord # semantics of these different levels: # # * http://www.postgresql.org/docs/9.1/static/transaction-iso.html - # * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html + # * https://dev.mysql.com/doc/refman/5.6/en/set-transaction.html # # An <tt>ActiveRecord::TransactionIsolationError</tt> will be raised if: # 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 0acc815d51..a768ee2d70 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -401,7 +401,7 @@ module ActiveRecord # Adds a reference. Optionally adds a +type+ column, if the # +:polymorphic+ option is provided. +references+ and +belongs_to+ - # are acceptable. The reference column will be an +integer+ by default, + # are interchangeable. The reference column will be an +integer+ by default, # the +:type+ option can be used to specify a different type. A foreign # key will be created if the +:foreign_key+ option is passed. # @@ -535,6 +535,8 @@ module ActiveRecord # Checks to see if a column exists. # + # t.string(:name) unless t.column_exists?(:name, :string) + # # See SchemaStatements#column_exists? def column_exists?(column_name, type = nil, options = {}) @base.column_exists?(name, column_name, type, options) @@ -554,6 +556,10 @@ module ActiveRecord # Checks to see if an index exists. # + # unless t.index_exists?(:branch_id) + # t.index(:branch_id) + # end + # # See SchemaStatements#index_exists? def index_exists?(column_name, options = {}) @base.index_exists?(name, column_name, options) @@ -667,10 +673,20 @@ module ActiveRecord end alias :remove_belongs_to :remove_references + # Adds a foreign key. + # + # t.foreign_key(:authors) + # + # See SchemaStatements#add_foreign_key def foreign_key(*args) # :nodoc: @base.add_foreign_key(name, *args) end + # Checks to see if a foreign key exists. + # + # t.foreign_key(:authors) unless t.foreign_key_exists?(:authors) + # + # See SchemaStatements#foreign_key_exists? def foreign_key_exists?(*args) # :nodoc: @base.foreign_key_exists?(name, *args) end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb index af7ef7cbaa..999cb0ec5a 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb @@ -24,7 +24,7 @@ module ActiveRecord def prepare_column_options(column) spec = {} spec[:name] = column.name.inspect - spec[:type] = column.type.to_s + spec[:type] = schema_type(column) spec[:null] = 'false' unless column.null limit = column.limit || native_database_types[column.type][:limit] @@ -45,6 +45,10 @@ module ActiveRecord private + def schema_type(column) + column.type.to_s + end + def schema_default(column) type = lookup_cast_type_from_column(column) default = type.deserialize(column.default) 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 d42f9a894b..72e019066e 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -652,7 +652,7 @@ module ActiveRecord alias :add_belongs_to :add_reference # Removes the reference(s). Also removes a +type+ column if one exists. - # <tt>remove_reference</tt>, <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable. + # <tt>remove_reference</tt> and <tt>remove_belongs_to</tt> are acceptable. # # ====== Remove the reference # diff --git a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb index 3a1e4a4a88..295a7bed87 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb @@ -1,13 +1,10 @@ module ActiveRecord module ConnectionAdapters class TransactionState - attr_reader :parent - VALID_STATES = Set.new([:committed, :rolledback, nil]) def initialize(state = nil) @state = state - @parent = nil end def finalized? @@ -27,7 +24,7 @@ module ActiveRecord end def set_state(state) - if !VALID_STATES.include?(state) + unless VALID_STATES.include?(state) raise ArgumentError, "Invalid transaction state: #{state}" end @state = state @@ -47,11 +44,12 @@ module ActiveRecord attr_reader :connection, :state, :records, :savepoint_name attr_writer :joinable - def initialize(connection, options) + def initialize(connection, options, run_commit_callbacks: false) @connection = connection @state = TransactionState.new @records = [] @joinable = options.fetch(:joinable, true) + @run_commit_callbacks = run_commit_callbacks end def add_record(record) @@ -78,18 +76,21 @@ module ActiveRecord end def before_commit_records - records.uniq.each(&:before_committed!) + records.uniq.each(&:before_committed!) if @run_commit_callbacks end def commit_records ite = records.uniq while record = ite.shift - record.committed! + if @run_commit_callbacks + record.committed! + else + # if not running callbacks, only adds the record to the parent transaction + record.add_to_transaction + end end ensure - ite.each do |i| - i.committed!(should_run_callbacks: false) - end + ite.each { |i| i.committed!(should_run_callbacks: false) } end def full_rollback?; true; end @@ -100,8 +101,8 @@ module ActiveRecord class SavepointTransaction < Transaction - def initialize(connection, savepoint_name, options) - super(connection, options) + def initialize(connection, savepoint_name, options, *args) + super(connection, options, *args) if options[:isolation] raise ActiveRecord::TransactionIsolationError, "cannot set transaction isolation in a nested transaction" end @@ -123,7 +124,7 @@ module ActiveRecord class RealTransaction < Transaction - def initialize(connection, options) + def initialize(connection, options, *args) super if options[:isolation] connection.begin_isolated_db_transaction(options[:isolation]) @@ -150,11 +151,13 @@ module ActiveRecord end def begin_transaction(options = {}) + run_commit_callbacks = !current_transaction.joinable? transaction = if @stack.empty? - RealTransaction.new(@connection, options) + RealTransaction.new(@connection, options, run_commit_callbacks: run_commit_callbacks) else - SavepointTransaction.new(@connection, "active_record_#{@stack.size}", options) + SavepointTransaction.new(@connection, "active_record_#{@stack.size}", options, + run_commit_callbacks: run_commit_callbacks) end @stack.push(transaction) @@ -162,18 +165,11 @@ module ActiveRecord end def commit_transaction - inner_transaction = @stack.pop - - if current_transaction.joinable? - inner_transaction.commit - inner_transaction.records.each do |r| - r.add_to_transaction - end - else - inner_transaction.before_commit_records - inner_transaction.commit - inner_transaction.commit_records - end + transaction = @stack.last + transaction.before_commit_records + @stack.pop + transaction.commit + transaction.commit_records end def rollback_transaction(transaction = nil) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb index c084431588..b7c7ff1187 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -86,8 +86,8 @@ module ActiveRecord def column_spec_for_primary_key(column) spec = {} if column.auto_increment? - return unless column.limit == 8 - spec[:id] = ':bigint' + spec[:id] = ':bigint' if column.bigint? + return if spec.empty? else spec[:id] = column.type.inspect spec.merge!(prepare_column_options(column).delete_if { |key, _| [:name, :type, :null].include?(key) }) @@ -785,7 +785,9 @@ module ActiveRecord subselect = Arel::SelectManager.new(select.engine) subselect.project Arel.sql(key.name) - subselect.from subsubselect.as('__active_record_temp') + # Materialized subquery by adding distinct + # to work with MySQL 5.7.6 which sets optimizer_switch='derived_merge=on' + subselect.from subsubselect.distinct.as('__active_record_temp') end def add_index_length(option_strings, column_names, options = {}) @@ -903,8 +905,7 @@ module ActiveRecord def configure_connection variables = @config.fetch(:variables, {}).stringify_keys - # By default, MySQL 'where id is null' selects the last inserted id. - # Turn this off. http://dev.rubyonrails.org/ticket/6778 + # By default, MySQL 'where id is null' selects the last inserted id; Turn this off. variables['sql_auto_is_null'] = 0 # Increase timeout so the server doesn't disconnect us. @@ -913,14 +914,14 @@ module ActiveRecord variables['wait_timeout'] = self.class.type_cast_config_to_integer(wait_timeout) # Make MySQL reject illegal values rather than truncating or blanking them, see - # http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_strict_all_tables + # http://dev.mysql.com/doc/refman/5.6/en/sql-mode.html#sqlmode_strict_all_tables # If the user has provided another value for sql_mode, don't replace it. unless variables.has_key?('sql_mode') variables['sql_mode'] = strict_mode? ? 'STRICT_ALL_TABLES' : '' end # NAMES does not have an equals sign, see - # http://dev.mysql.com/doc/refman/5.0/en/set-statement.html#id944430 + # http://dev.mysql.com/doc/refman/5.6/en/set-statement.html#id944430 # (trailing comma because variable_assignments will always have content) if @config[:encoding] encoding = "NAMES #{@config[:encoding]}" diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb index fa5ed07b8a..a67127bd71 100644 --- a/activerecord/lib/active_record/connection_adapters/column.rb +++ b/activerecord/lib/active_record/connection_adapters/column.rb @@ -31,7 +31,11 @@ module ActiveRecord end def has_default? - !default.nil? + !default.nil? || default_function + end + + def bigint? + /bigint/ === sql_type end # Returns the human name of the column name. diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 64985ee933..45b935f1d6 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -56,9 +56,9 @@ module ActiveRecord # * <tt>:password</tt> - Defaults to nothing. # * <tt>:database</tt> - The name of the database. No default, must be provided. # * <tt>:encoding</tt> - (Optional) Sets the client encoding by executing "SET NAMES <encoding>" after connection. - # * <tt>:reconnect</tt> - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html). - # * <tt>:strict</tt> - Defaults to true. Enable STRICT_ALL_TABLES. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html) - # * <tt>:variables</tt> - (Optional) A hash session variables to send as <tt>SET @@SESSION.key = value</tt> on each database connection. Use the value +:default+ to set a variable to its DEFAULT value. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/set-statement.html). + # * <tt>:reconnect</tt> - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.6/en/auto-reconnect.html). + # * <tt>:strict</tt> - Defaults to true. Enable STRICT_ALL_TABLES. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.6/en/sql-mode.html) + # * <tt>:variables</tt> - (Optional) A hash session variables to send as <tt>SET @@SESSION.key = value</tt> on each database connection. Use the value +:default+ to set a variable to its DEFAULT value. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.6/en/set-statement.html). # * <tt>:sslca</tt> - Necessary to use MySQL with an SSL connection. # * <tt>:sslkey</tt> - Necessary to use MySQL with an SSL connection. # * <tt>:sslcert</tt> - Necessary to use MySQL with an SSL connection. diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/column.rb b/activerecord/lib/active_record/connection_adapters/postgresql/column.rb index 0eb4fb468c..be13ead120 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/column.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/column.rb @@ -6,7 +6,9 @@ module ActiveRecord alias :array? :array def serial? - default_function && default_function =~ /\Anextval\(.*\)\z/ + return unless default_function + + %r{\Anextval\('(?<table_name>.+)_#{name}_seq'::regclass\)\z} === default_function end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb index fb4e0de2a8..f486c5ecb7 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb @@ -18,7 +18,7 @@ module ActiveRecord end attr_reader :subtype, :delimiter - delegate :type, :user_input_in_time_zone, to: :subtype + delegate :type, :user_input_in_time_zone, :limit, to: :subtype def initialize(subtype, delimiter = ',') @subtype = subtype diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb index b3b610a5f6..91d339f32c 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb @@ -7,7 +7,9 @@ module ActiveRecord :enum end - def cast(value) + private + + def cast_value(value) value.to_s end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb b/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb index c1835380f9..44a7338bf5 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb @@ -14,7 +14,7 @@ module ActiveRecord transaction(requires_new: true) do execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";")) end - rescue => e + rescue ActiveRecord::ActiveRecordError => e original_exception = e end @@ -34,10 +34,10 @@ Rails needs superuser privileges to disable referential integrity. end begin - transaction(require_new: true) do + transaction(requires_new: true) do execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";")) end - rescue + rescue ActiveRecord::ActiveRecordError end else yield diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index 75b9d079bd..eeb141dd1e 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -514,14 +514,14 @@ module ActiveRecord sql = case type.to_s when 'binary' # PostgreSQL doesn't support limits on binary (bytea) columns. - # The hard limit is 1Gb, because of a 32-bit size field, and TOAST. + # The hard limit is 1GB, because of a 32-bit size field, and TOAST. case limit when nil, 0..0x3fffffff; super(type) else raise(ActiveRecordError, "No binary type has byte size #{limit}.") end when 'text' # PostgreSQL doesn't support limits on text columns. - # The hard limit is 1Gb, according to section 8.3 in the manual. + # The hard limit is 1GB, according to section 8.3 in the manual. case limit when nil, 0..0x3fffffff; super(type) else raise(ActiveRecordError, "The limit on text can be at most 1GB - 1byte.") diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 6d25b53b21..96a3ac7c31 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -12,8 +12,8 @@ require "active_record/connection_adapters/statement_pool" require 'arel/visitors/bind_visitor' -# Make sure we're using pg high enough for PGResult#values -gem 'pg', '~> 0.15' +# Make sure we're using pg high enough for Ruby 2.2+ compatibility +gem 'pg', '~> 0.18' require 'pg' require 'ipaddr' @@ -128,7 +128,7 @@ module ActiveRecord def column_spec_for_primary_key(column) spec = {} if column.serial? - return unless column.sql_type == 'bigint' + return unless column.bigint? spec[:id] = ':bigserial' elsif column.type == :uuid spec[:id] = ':uuid' @@ -145,7 +145,6 @@ module ActiveRecord def prepare_column_options(column) # :nodoc: spec = super spec[:array] = 'true' if column.array? - spec[:default] = "\"#{column.default_function}\"" if column.default_function spec end @@ -154,6 +153,26 @@ module ActiveRecord super + [:array] end + def schema_type(column) + return super unless column.serial? + + if column.bigint? + 'bigserial' + else + 'serial' + end + end + private :schema_type + + def schema_default(column) + if column.default_function + column.default_function.inspect unless column.serial? + else + super + end + end + private :schema_default + # Returns +true+, since this connection adapter supports prepared statement # caching. def supports_statement_cache? diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index d41872d767..9a39a0e919 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -85,6 +85,15 @@ module ActiveRecord mattr_accessor :dump_schema_after_migration, instance_writer: false self.dump_schema_after_migration = true + ## + # :singleton-method: + # Specifies which database schemas to dump when calling db:structure:dump. + # If :schema_search_path (the default), it will dumps any schemas listed in schema_search_path. + # Use :all to always dumps all schemas regardless of the schema_search_path. + # A string of comma separated schemas can also be used to pass a custom list of schemas. + mattr_accessor :dump_schemas, instance_writer: false + self.dump_schemas = :schema_search_path + mattr_accessor :maintain_test_schema, instance_accessor: false mattr_accessor :belongs_to_required_by_default, instance_accessor: false @@ -123,8 +132,7 @@ module ActiveRecord return super unless ids.length == 1 return super if block_given? || primary_key.nil? || - default_scopes.any? || - current_scope || + scope_attributes? || columns_hash.include?(inheritance_column) || ids.first.kind_of?(Array) @@ -152,8 +160,7 @@ module ActiveRecord end def find_by(*args) # :nodoc: - return super if current_scope || !(Hash === args.first) || reflect_on_all_aggregations.any? - return super if default_scopes.any? + return super if scope_attributes? || !(Hash === args.first) || reflect_on_all_aggregations.any? hash = args.first @@ -300,6 +307,7 @@ module ActiveRecord # post.init_with('attributes' => { 'title' => 'hello world' }) # post.title # => 'hello world' def init_with(coder) + coder = LegacyYamlAdapter.convert(self.class, coder) @attributes = coder['attributes'] init_internals @@ -370,6 +378,7 @@ module ActiveRecord coder['raw_attributes'] = attributes_before_type_cast coder['attributes'] = @attributes coder['new_record'] = new_record? + coder['active_record_yaml_version'] = 1 end # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ @@ -483,51 +492,6 @@ module ActiveRecord private - def set_transaction_state(state) # :nodoc: - @transaction_state = state - end - - def has_transactional_callbacks? # :nodoc: - !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty? - end - - # Updates the attributes on this particular ActiveRecord object so that - # if it is associated with a transaction, then the state of the AR object - # will be updated to reflect the current state of the transaction - # - # The @transaction_state variable stores the states of the associated - # transaction. This relies on the fact that a transaction can only be in - # one rollback or commit (otherwise a list of states would be required) - # Each AR object inside of a transaction carries that transaction's - # TransactionState. - # - # This method checks to see if the ActiveRecord object's state reflects - # the TransactionState, and rolls back or commits the ActiveRecord object - # as appropriate. - # - # Since ActiveRecord objects can be inside multiple transactions, this - # method recursively goes through the parent of the TransactionState and - # checks if the ActiveRecord object reflects the state of the object. - def sync_with_transaction_state - update_attributes_from_transaction_state(@transaction_state, 0) - end - - def update_attributes_from_transaction_state(transaction_state, depth) - @reflects_state = [false] if depth == 0 - - if transaction_state && transaction_state.finalized? && !has_transactional_callbacks? - unless @reflects_state[depth] - restore_transaction_record_state if transaction_state.rolledback? - clear_transaction_record_state - @reflects_state[depth] = true - end - - if transaction_state.parent && !@reflects_state[depth+1] - update_attributes_from_transaction_state(transaction_state.parent, depth+1) - end - end - end - # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements # of the array, and then rescues from the possible NoMethodError. If those elements are # ActiveRecord::Base's, then this triggers the various method_missing's that we have, diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index d710d96a9a..98aee77557 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -178,10 +178,8 @@ module ActiveRecord class DangerousAttributeError < ActiveRecordError end - UnknownAttributeError = ActiveSupport::Deprecation::DeprecatedConstantProxy.new( # :nodoc: - 'ActiveRecord::UnknownAttributeError', - 'ActiveModel::AttributeAssignment::UnknownAttributeError' - ) + # Raised when unknown attributes are supplied via mass assignment. + UnknownAttributeError = ActiveModel::UnknownAttributeError # Raised when an error occurred while doing a mass assignment to an attribute through the # +attributes=+ method. The exception has an +attribute+ property that is the name of the diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 75b0e1e08d..2c1771dd6c 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -139,13 +139,13 @@ module ActiveRecord # name: kitten.png # sha: <%= file_sha 'files/kitten.png' %> # - # = Transactional Fixtures + # = Transactional Tests # # Test cases can use begin+rollback to isolate their changes to the database instead of having to # delete+insert for every test case. # # class FooTest < ActiveSupport::TestCase - # self.use_transactional_fixtures = true + # self.use_transactional_tests = true # # test "godzilla" do # assert !Foo.all.empty? @@ -159,14 +159,14 @@ module ActiveRecord # end # # If you preload your test database with all fixture data (probably in the rake task) and use - # transactional fixtures, then you may omit all fixtures declarations in your test cases since + # transactional tests, then you may omit all fixtures declarations in your test cases since # all the data's already there and every case rolls back its changes. # # In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to # true. This will provide access to fixture data for every table that has been loaded through # fixtures (depending on the value of +use_instantiated_fixtures+). # - # When *not* to use transactional fixtures: + # When *not* to use transactional tests: # # 1. You're testing whether a transaction works correctly. Nested transactions don't commit until # all parent transactions commit, particularly, the fixtures transaction which is begun in setup @@ -539,12 +539,10 @@ module ActiveRecord conn.insert_fixture(row, fixture_set_name) end end - end - # Cap primary key sequences to max(pk). - if connection.respond_to?(:reset_pk_sequence!) - fixture_sets.each do |fs| - connection.reset_pk_sequence!(fs.table_name) + # Cap primary key sequences to max(pk). + if conn.respond_to?(:reset_pk_sequence!) + conn.reset_pk_sequence!(fs.table_name) end end end @@ -837,13 +835,15 @@ module ActiveRecord class_attribute :fixture_path, :instance_writer => false class_attribute :fixture_table_names class_attribute :fixture_class_names + class_attribute :use_transactional_tests class_attribute :use_transactional_fixtures class_attribute :use_instantiated_fixtures # true, false, or :no_instances class_attribute :pre_loaded_fixtures class_attribute :config + singleton_class.deprecate 'use_transactional_fixtures=' => 'use use_transactional_tests= instead' + self.fixture_table_names = [] - self.use_transactional_fixtures = true self.use_instantiated_fixtures = false self.pre_loaded_fixtures = false self.config = ActiveRecord::Base @@ -851,6 +851,16 @@ module ActiveRecord self.fixture_class_names = Hash.new do |h, fixture_set_name| h[fixture_set_name] = ActiveRecord::FixtureSet.default_fixture_model_name(fixture_set_name, self.config) end + + silence_warnings do + define_singleton_method :use_transactional_tests do + if use_transactional_fixtures.nil? + true + else + use_transactional_fixtures + end + end + end end module ClassMethods @@ -921,13 +931,13 @@ module ActiveRecord end def run_in_transaction? - use_transactional_fixtures && + use_transactional_tests && !self.class.uses_transaction?(method_name) end def setup_fixtures(config = ActiveRecord::Base) - if pre_loaded_fixtures && !use_transactional_fixtures - raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures' + if pre_loaded_fixtures && !use_transactional_tests + raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_tests' end @fixture_cache = {} diff --git a/activerecord/lib/active_record/legacy_yaml_adapter.rb b/activerecord/lib/active_record/legacy_yaml_adapter.rb new file mode 100644 index 0000000000..89dee58423 --- /dev/null +++ b/activerecord/lib/active_record/legacy_yaml_adapter.rb @@ -0,0 +1,46 @@ +module ActiveRecord + module LegacyYamlAdapter + def self.convert(klass, coder) + return coder unless coder.is_a?(Psych::Coder) + + case coder["active_record_yaml_version"] + when 1 then coder + else + if coder["attributes"].is_a?(AttributeSet) + Rails420.convert(klass, coder) + else + Rails41.convert(klass, coder) + end + end + end + + module Rails420 + def self.convert(klass, coder) + attribute_set = coder["attributes"] + + klass.attribute_names.each do |attr_name| + attribute = attribute_set[attr_name] + if attribute.type.is_a?(Delegator) + type_from_klass = klass.type_for_attribute(attr_name) + attribute_set[attr_name] = attribute.with_type(type_from_klass) + end + end + + coder + end + end + + module Rails41 + def self.convert(klass, coder) + attributes = klass.attributes_builder + .build_from_database(coder["attributes"]) + new_record = coder["attributes"][klass.primary_key].blank? + + { + "attributes" => attributes, + "new_record" => new_record, + } + end + end + end +end diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb index ff7102d35b..3d95c54ef3 100644 --- a/activerecord/lib/active_record/locking/pessimistic.rb +++ b/activerecord/lib/active_record/locking/pessimistic.rb @@ -51,7 +51,7 @@ module ActiveRecord # end # # Database-specific information on row locking: - # MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html + # MySQL: http://dev.mysql.com/doc/refman/5.6/en/innodb-locking-reads.html # PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE module Pessimistic # Obtain a row lock on this record. Reloads the record to obtain the requested diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb index fa6eaa7e64..74894d0c37 100644 --- a/activerecord/lib/active_record/null_relation.rb +++ b/activerecord/lib/active_record/null_relation.rb @@ -14,7 +14,7 @@ module ActiveRecord 0 end - def update_all(_updates, _conditions = nil, _options = {}) + def update_all(_updates) 0 end @@ -80,7 +80,7 @@ module ActiveRecord end end - def exists?(_id = false) + def exists?(_conditions = :none) false end diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 7c076864a3..a6176dffdb 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -96,7 +96,8 @@ module ActiveRecord # Returns true if the record is persisted, i.e. it's not a new record and it was # not destroyed, otherwise returns false. def persisted? - !(new_record? || destroyed?) + sync_with_transaction_state + !(@new_record || @destroyed) end # Saves the model. diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index b6de90e89d..f1bdbc845c 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -58,9 +58,6 @@ module ActiveRecord require "active_record/railties/console_sandbox" if app.sandbox? require "active_record/base" console = ActiveSupport::Logger.new(STDERR) - console.formatter = Rails.logger.formatter - console.level = Rails.logger.level - Rails.logger.extend ActiveSupport::Logger.broadcast console end diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index dab5a502a5..4265afc0a5 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -166,8 +166,8 @@ module ActiveRecord # AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods. # # MacroReflection + # AggregateReflection # AssociationReflection - # AggregateReflection # HasManyReflection # HasOneReflection # BelongsToReflection @@ -370,6 +370,12 @@ module ActiveRecord [self] end + # This is for clearing cache on the reflection. Useful for tests that need to compare + # SQL queries on associations. + def clear_association_scope_cache # :nodoc: + @association_scope_cache.clear + end + def nested? false end @@ -694,7 +700,7 @@ module ActiveRecord def chain @chain ||= begin a = source_reflection.chain - b = through_reflection.chain + b = through_reflection.chain.map(&:dup) if options[:source_type] b[0] = PolymorphicReflection.new(b[0], self) @@ -706,6 +712,15 @@ module ActiveRecord end end + # This is for clearing cache on the reflection. Useful for tests that need to compare + # SQL queries on associations. + def clear_association_scope_cache # :nodoc: + @chain = nil + delegate_reflection.clear_association_scope_cache + source_reflection.clear_association_scope_cache + through_reflection.clear_association_scope_cache + end + # Consider the following example: # # class Person diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 6bbec7c0c0..85648a7f8f 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -205,7 +205,9 @@ module ActiveRecord # constraint an exception may be raised, just retry: # # begin - # CreditAccount.find_or_create_by(user_id: user.id) + # CreditAccount.transaction(requires_new: true) do + # CreditAccount.find_or_create_by(user_id: user.id) + # end # rescue ActiveRecord::RecordNotUnique # retry # end diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 7f27e7b463..8f16de3519 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -182,7 +182,7 @@ module ActiveRecord private def has_include?(column_name) - eager_loading? || (includes_values.present? && ((column_name && column_name != :all) || references_eager_loaded_tables?)) + eager_loading? || (includes_values.present? && column_name && column_name != :all) end def perform_calculation(operation, column_name) diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 7bd091b66c..3f747a20b3 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -378,7 +378,7 @@ module ActiveRecord def construct_relation_for_association_calculations from = arel.froms.first if Arel::Table === from - apply_join_dependency(self, construct_join_dependency) + apply_join_dependency(self, construct_join_dependency(joins_values)) else # FIXME: as far as I can tell, `from` will always be an Arel::Table. # There are no tests that test this branch, but presumably it's diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb index fca4f1c9d3..f049b658c4 100644 --- a/activerecord/lib/active_record/scoping.rb +++ b/activerecord/lib/active_record/scoping.rb @@ -17,6 +17,17 @@ module ActiveRecord def current_scope=(scope) #:nodoc: ScopeRegistry.set_value_for(:current_scope, self.to_s, scope) end + + # Collects attributes from scopes that should be applied when creating + # an AR instance for the particular class this is called on. + def scope_attributes # :nodoc: + all.scope_for_create + end + + # Are there attributes associated with this scope? + def scope_attributes? # :nodoc: + current_scope + end end def populate_with_current_scope_attributes diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb index 18190cb535..5ec2c88b47 100644 --- a/activerecord/lib/active_record/scoping/default.rb +++ b/activerecord/lib/active_record/scoping/default.rb @@ -33,6 +33,11 @@ module ActiveRecord block_given? ? relation.scoping { yield } : relation end + # Are there attributes associated with this scope? + def scope_attributes? # :nodoc: + super || default_scopes.any? + end + def before_remove_const #:nodoc: self.current_scope = nil end diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb index 43c7b1c574..7b62626896 100644 --- a/activerecord/lib/active_record/scoping/named.rb +++ b/activerecord/lib/active_record/scoping/named.rb @@ -39,17 +39,6 @@ module ActiveRecord end end - # Collects attributes from scopes that should be applied when creating - # an AR instance for the particular class this is called on. - def scope_attributes # :nodoc: - all.scope_for_create - end - - # Are there default attributes associated with this scope? - def scope_attributes? # :nodoc: - current_scope || default_scopes.any? - end - # Adds a class method for retrieving and querying objects. A \scope # represents a narrowing of a database query, such as # <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>. diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index 69aceb66b1..683741768b 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -212,7 +212,7 @@ module ActiveRecord load_schema(*args) end - def schema_file(format = ActiveSupport::Base.schema_format) + def schema_file(format = ActiveRecord::Base.schema_format) case format when :ruby File.join(db_dir, "schema.rb") diff --git a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb index ce1de4b76e..d7da95c8a9 100644 --- a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb @@ -46,7 +46,15 @@ module ActiveRecord def structure_dump(filename) set_psql_env - search_path = configuration['schema_search_path'] + + search_path = case ActiveRecord::Base.dump_schemas + when :schema_search_path + configuration['schema_search_path'] + when :all + nil + when String + ActiveRecord::Base.dump_schemas + end unless search_path.blank? search_path = search_path.split(",").map{|search_path_part| "--schema=#{Shellwords.escape(search_path_part.strip)}" }.join(" ") end @@ -59,7 +67,7 @@ module ActiveRecord def structure_load(filename) set_psql_env - Kernel.system("psql -q -f #{Shellwords.escape(filename)} #{configuration['database']}") + Kernel.system("psql -X -q -f #{Shellwords.escape(filename)} #{configuration['database']}") end private diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index 598defce50..2293d1b258 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -227,8 +227,6 @@ module ActiveRecord # after_commit :do_foo_bar, on: [:create, :update] # after_commit :do_bar_baz, on: [:update, :destroy] # - # Note that transactional fixtures do not play well with this feature. Please - # use the +test_after_commit+ gem to have these hooks fired in tests. def after_commit(*args, &block) set_options_for_callbacks!(args) set_callback(:commit, :after, *args, &block) @@ -356,6 +354,7 @@ module ActiveRecord if has_transactional_callbacks? self.class.connection.add_transaction_record(self) else + sync_with_transaction_state set_transaction_state(self.class.connection.transaction_state) end remember_transaction_record_state @@ -413,13 +412,14 @@ module ActiveRecord transaction_level = (@_start_transaction_state[:level] || 0) - 1 if transaction_level < 1 || force restore_state = @_start_transaction_state - thaw unless restore_state[:frozen?] + thaw @new_record = restore_state[:new_record] @destroyed = restore_state[:destroyed] pk = self.class.primary_key if pk && read_attribute(pk) != restore_state[:id] write_attribute(pk, restore_state[:id]) end + freeze if restore_state[:frozen?] end end end @@ -442,5 +442,43 @@ module ActiveRecord end end end + + private + + def set_transaction_state(state) # :nodoc: + @transaction_state = state + end + + def has_transactional_callbacks? # :nodoc: + !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty? + end + + # Updates the attributes on this particular ActiveRecord object so that + # if it's associated with a transaction, then the state of the ActiveRecord + # object will be updated to reflect the current state of the transaction + # + # The @transaction_state variable stores the states of the associated + # transaction. This relies on the fact that a transaction can only be in + # one rollback or commit (otherwise a list of states would be required) + # Each ActiveRecord object inside of a transaction carries that transaction's + # TransactionState. + # + # This method checks to see if the ActiveRecord object's state reflects + # the TransactionState, and rolls back or commits the ActiveRecord object + # as appropriate. + # + # Since ActiveRecord objects can be inside multiple transactions, this + # method recursively goes through the parent of the TransactionState and + # checks if the ActiveRecord object reflects the state of the object. + def sync_with_transaction_state + update_attributes_from_transaction_state(@transaction_state) + end + + def update_attributes_from_transaction_state(transaction_state) + if transaction_state && transaction_state.finalized? + restore_transaction_record_state if transaction_state.rolledback? + clear_transaction_record_state + end + end end end diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb index 732029c723..ea3e0d6a45 100644 --- a/activerecord/lib/active_record/type/serialized.rb +++ b/activerecord/lib/active_record/type/serialized.rb @@ -26,9 +26,15 @@ module ActiveRecord end end + def inspect + Kernel.instance_method(:inspect).bind(self).call + end + def changed_in_place?(raw_old_value, value) return false if value.nil? - subtype.changed_in_place?(raw_old_value, serialize(value)) + raw_new_value = serialize(value) + raw_old_value.nil? != raw_new_value.nil? || + subtype.changed_in_place?(raw_old_value, raw_new_value) end def accessor diff --git a/activerecord/lib/active_record/type/value.rb b/activerecord/lib/active_record/type/value.rb index fc3ef5e83b..6b9d147ecc 100644 --- a/activerecord/lib/active_record/type/value.rb +++ b/activerecord/lib/active_record/type/value.rb @@ -12,7 +12,7 @@ module ActiveRecord def type # :nodoc: end - # Convert a value from database input to the appropriate ruby type. The + # Converts a value from database input to the appropriate ruby type. The # return value of this method will be returned from # ActiveRecord::AttributeMethods::Read#read_attribute. The default # implementation just calls Value#cast. @@ -36,7 +36,7 @@ module ActiveRecord cast_value(value) unless value.nil? end - # Cast a value from the ruby type to a type that the database knows how + # Casts a value from the ruby type to a type that the database knows how # to understand. The returned value from this method should be a # +String+, +Numeric+, +Date+, +Time+, +Symbol+, +true+, +false+, or # +nil+. @@ -44,7 +44,7 @@ module ActiveRecord value end - # Type cast a value for schema dumping. This method is private, as we are + # Type casts a value for schema dumping. This method is private, as we are # hoping to remove it entirely. def type_cast_for_schema(value) # :nodoc: value.inspect diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index ecf1368a91..1712ff0ac6 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -226,7 +226,7 @@ module ActiveRecord end class AdapterTestWithoutTransaction < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Klass < ActiveRecord::Base end diff --git a/activerecord/test/cases/adapters/mysql/consistency_test.rb b/activerecord/test/cases/adapters/mysql/consistency_test.rb index e972d6b330..ae190b728d 100644 --- a/activerecord/test/cases/adapters/mysql/consistency_test.rb +++ b/activerecord/test/cases/adapters/mysql/consistency_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class MysqlConsistencyTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Consistency < ActiveRecord::Base self.table_name = "mysql_consistency" diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb index 2f9c070255..ec1c394f40 100644 --- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb @@ -71,7 +71,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase #fixtures self.use_instantiated_fixtures = true - self.use_transactional_fixtures = false + self.use_transactional_tests = false #activerecord model class with reserved-word table name def test_activerecord_model diff --git a/activerecord/test/cases/adapters/mysql/unsigned_type_test.rb b/activerecord/test/cases/adapters/mysql/unsigned_type_test.rb index 8f521e9181..e9edc53f93 100644 --- a/activerecord/test/cases/adapters/mysql/unsigned_type_test.rb +++ b/activerecord/test/cases/adapters/mysql/unsigned_type_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class UnsignedTypeTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class UnsignedType < ActiveRecord::Base end diff --git a/activerecord/test/cases/adapters/mysql2/boolean_test.rb b/activerecord/test/cases/adapters/mysql2/boolean_test.rb index 0e641ba3bf..0d81dd6eee 100644 --- a/activerecord/test/cases/adapters/mysql2/boolean_test.rb +++ b/activerecord/test/cases/adapters/mysql2/boolean_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class Mysql2BooleanTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class BooleanType < ActiveRecord::Base self.table_name = "mysql_booleans" diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index beb829fc46..799e60a683 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -71,7 +71,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase #fixtures self.use_instantiated_fixtures = true - self.use_transactional_fixtures = false + self.use_transactional_tests = false #activerecord model class with reserved-word table name def test_activerecord_model diff --git a/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb b/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb index 8f521e9181..e9edc53f93 100644 --- a/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb +++ b/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class UnsignedTypeTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class UnsignedType < ActiveRecord::Base end diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index 2163e35e70..6edbd9c3a6 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -23,6 +23,7 @@ class PostgresqlArrayTest < ActiveRecord::TestCase t.hstore :hstores, array: true end end + PgArray.reset_column_information @column = PgArray.columns_hash['tags'] @type = PgArray.type_for_attribute("tags") end diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb index 4f48a7bce3..2c14252ae4 100644 --- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb +++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb @@ -12,7 +12,7 @@ class PostgresqlLtree < ActiveRecord::Base end class PostgresqlDataTypeTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false def setup @connection = ActiveRecord::Base.connection diff --git a/activerecord/test/cases/adapters/postgresql/enum_test.rb b/activerecord/test/cases/adapters/postgresql/enum_test.rb index 7458de23d8..ed084483bc 100644 --- a/activerecord/test/cases/adapters/postgresql/enum_test.rb +++ b/activerecord/test/cases/adapters/postgresql/enum_test.rb @@ -80,4 +80,12 @@ class PostgresqlEnumTest < ActiveRecord::TestCase assert_equal "happy", enum.current_mood end + + def test_assigning_enum_to_nil + model = PostgresqlEnum.new(current_mood: nil) + + assert_nil model.current_mood + assert model.save + assert_nil model.reload.current_mood + end end diff --git a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb index 7b99fcdda0..06d427f464 100644 --- a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb +++ b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class PostgresqlExtensionMigrationTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class EnableHstore < ActiveRecord::Migration def change diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index e6835031c3..ad9dd311a6 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -27,6 +27,7 @@ if ActiveRecord::Base.connection.supports_extensions? t.hstore 'settings' end end + Hstore.reset_column_information @column = Hstore.columns_hash['tags'] @type = Hstore.type_for_attribute("tags") end diff --git a/activerecord/test/cases/adapters/postgresql/infinity_test.rb b/activerecord/test/cases/adapters/postgresql/infinity_test.rb index 24199c69b8..d9d7832094 100644 --- a/activerecord/test/cases/adapters/postgresql/infinity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/infinity_test.rb @@ -24,6 +24,15 @@ class PostgresqlInfinityTest < ActiveRecord::TestCase assert_equal Float::INFINITY, record.float end + test "type casting string on a float column" do + record = PostgresqlInfinity.new(float: 'Infinity') + assert_equal Float::INFINITY, record.float + record = PostgresqlInfinity.new(float: '-Infinity') + assert_equal(-Float::INFINITY, record.float) + record = PostgresqlInfinity.new(float: 'NaN') + assert_send [record.float, :nan?] + end + test "update_all with infinity on a float column" do record = PostgresqlInfinity.create! PostgresqlInfinity.update_all(float: Float::INFINITY) diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb index d8fded16b4..6878516aeb 100644 --- a/activerecord/test/cases/adapters/postgresql/json_test.rb +++ b/activerecord/test/cases/adapters/postgresql/json_test.rb @@ -21,11 +21,11 @@ module PostgresqlJSONSharedTestCases rescue ActiveRecord::StatementInvalid skip "do not test on PostgreSQL without #{column_type} type." end - @column = JsonDataType.columns_hash['payload'] end def teardown @connection.drop_table :json_data_type, if_exists: true + JsonDataType.reset_column_information end def test_column diff --git a/activerecord/test/cases/adapters/postgresql/range_test.rb b/activerecord/test/cases/adapters/postgresql/range_test.rb index b6b451ca5c..bbf96278b0 100644 --- a/activerecord/test/cases/adapters/postgresql/range_test.rb +++ b/activerecord/test/cases/adapters/postgresql/range_test.rb @@ -7,7 +7,7 @@ if ActiveRecord::Base.connection.supports_ranges? end class PostgresqlRangeTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false include ConnectionHelper def setup diff --git a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb index 98291f1bbf..d76e762815 100644 --- a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb @@ -2,13 +2,17 @@ require 'cases/helper' require 'support/connection_helper' class PostgreSQLReferentialIntegrityTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false include ConnectionHelper + IS_REFERENTIAL_INTEGRITY_SQL = lambda do |sql| + sql.match(/DISABLE TRIGGER ALL/) || sql.match(/ENABLE TRIGGER ALL/) + end + module MissingSuperuserPrivileges def execute(sql) - if sql.match(/DISABLE TRIGGER ALL/) || sql.match(/ENABLE TRIGGER ALL/) + if IS_REFERENTIAL_INTEGRITY_SQL.call(sql) super "BROKEN;" rescue nil # put transaction in broken state raise ActiveRecord::StatementInvalid, 'PG::InsufficientPrivilege' else @@ -17,6 +21,16 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::TestCase end end + module ProgrammerMistake + def execute(sql) + if IS_REFERENTIAL_INTEGRITY_SQL.call(sql) + raise ArgumentError, 'something is not right.' + else + super + end + end + end + def setup @connection = ActiveRecord::Base.connection end @@ -81,6 +95,14 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::TestCase end end + def test_only_catch_active_record_errors_others_bubble_up + @connection.extend ProgrammerMistake + + assert_raises ArgumentError do + @connection.disable_referential_integrity {} + end + end + private def assert_transaction_is_not_broken diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb index 6937145439..359a45bbd1 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb @@ -4,7 +4,7 @@ class SchemaThing < ActiveRecord::Base end class SchemaAuthorizationTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false TABLE_NAME = 'schema_things' COLUMNS = [ diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 77ff6d01bc..c1be340e7c 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -3,7 +3,7 @@ require 'models/default' require 'support/schema_dumping_helper' class SchemaTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false SCHEMA_NAME = 'test_schema' SCHEMA2_NAME = 'test_schema2' diff --git a/activerecord/test/cases/adapters/postgresql/serial_test.rb b/activerecord/test/cases/adapters/postgresql/serial_test.rb new file mode 100644 index 0000000000..458a8dae6c --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/serial_test.rb @@ -0,0 +1,60 @@ +require "cases/helper" +require 'support/schema_dumping_helper' + +class PostgresqlSerialTest < ActiveRecord::TestCase + include SchemaDumpingHelper + + class PostgresqlSerial < ActiveRecord::Base; end + + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table "postgresql_serials", force: true do |t| + t.serial :seq + end + end + + teardown do + @connection.drop_table "postgresql_serials", if_exists: true + end + + def test_serial_column + column = PostgresqlSerial.columns_hash["seq"] + assert_equal :integer, column.type + assert_equal "integer", column.sql_type + assert column.serial? + end + + def test_schema_dump_with_shorthand + output = dump_table_schema "postgresql_serials" + assert_match %r{t\.serial\s+"seq"}, output + end +end + +class PostgresqlBigSerialTest < ActiveRecord::TestCase + include SchemaDumpingHelper + + class PostgresqlBigSerial < ActiveRecord::Base; end + + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table "postgresql_big_serials", force: true do |t| + t.bigserial :seq + end + end + + teardown do + @connection.drop_table "postgresql_big_serials", if_exists: true + end + + def test_bigserial_column + column = PostgresqlBigSerial.columns_hash["seq"] + assert_equal :integer, column.type + assert_equal "bigint", column.sql_type + assert column.serial? + end + + def test_schema_dump_with_shorthand + output = dump_table_schema "postgresql_big_serials" + assert_match %r{t\.bigserial\s+"seq"}, output + end +end diff --git a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb index da14063e20..a639f98272 100644 --- a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb +++ b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb @@ -5,7 +5,7 @@ require 'models/topic' class PostgresqlTimestampTest < ActiveRecord::TestCase class PostgresqlTimestampWithZone < ActiveRecord::Base; end - self.use_transactional_fixtures = false + self.use_transactional_tests = false setup do @connection = ActiveRecord::Base.connection diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index 1219e197ab..e9379a1019 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -135,26 +135,6 @@ class PostgresqlUUIDTest < ActiveRecord::TestCase end end -class PostgresqlLargeKeysTest < ActiveRecord::TestCase - include PostgresqlUUIDHelper - include SchemaDumpingHelper - - def setup - connection.create_table('big_serials', id: :bigserial) do |t| - t.string 'name' - end - end - - def test_omg - schema = dump_table_schema "big_serials" - assert_match "create_table \"big_serials\", id: :bigserial", schema - end - - def teardown - drop_table "big_serials" - end -end - class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase include PostgresqlUUIDHelper include SchemaDumpingHelper diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 5ca3c92027..27f4ba8eb6 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -8,7 +8,7 @@ module ActiveRecord class SQLite3AdapterTest < ActiveRecord::TestCase include DdlHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false class DualEncoding < ActiveRecord::Base end diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb index f4e8003bc3..9d5327bf35 100644 --- a/activerecord/test/cases/ar_schema_test.rb +++ b/activerecord/test/cases/ar_schema_test.rb @@ -3,7 +3,7 @@ require "cases/helper" if ActiveRecord::Base.connection.supports_migrations? class ActiveRecordSchemaTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false setup do @original_verbose = ActiveRecord::Migration.verbose diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 897c52a49d..290b2a0d6b 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -478,6 +478,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! } end + def test_taking_with_a_number + # taking from unloaded Relation + bob = Author.find(authors(:bob).id) + assert_equal [posts(:misc_by_bob)], bob.posts.take(1) + bob = Author.find(authors(:bob).id) + assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2) + + # taking from loaded Relation + bob.posts.to_a + assert_equal [posts(:misc_by_bob)], authors(:bob).posts.take(1) + assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], authors(:bob).posts.take(2) + end + def test_taking_with_inverse_of interests(:woodsmanship).destroy interests(:survival).destroy @@ -519,9 +532,21 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_update_all_on_association_accessed_before_save firm = Firm.new(name: 'Firm') + clients_proxy_id = firm.clients.object_id + firm.clients << Client.first + firm.save! + assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!') + assert_not_equal clients_proxy_id, firm.clients.object_id + end + + def test_update_all_on_association_accessed_before_save_with_explicit_foreign_key + # We can use the same cached proxy object because the id is available for the scope + firm = Firm.new(name: 'Firm', id: 100) + clients_proxy_id = firm.clients.object_id firm.clients << Client.first firm.save! assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!') + assert_equal clients_proxy_id, firm.clients.object_id end def test_belongs_to_sanity diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 3b6a4038cd..5c2e5e7b43 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -12,7 +12,7 @@ require 'models/image' require 'models/post' class HasOneAssociationsTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates def setup @@ -276,7 +276,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase def test_create_with_inexistent_foreign_key_failing firm = Firm.create(name: 'GlobalMegaCorp') - assert_raises(ActiveModel::AttributeAssignment::UnknownAttributeError) do + assert_raises(ActiveRecord::UnknownAttributeError) do firm.create_account_with_inexistent_foreign_key end end diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 9918601623..213be50e67 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -17,7 +17,7 @@ require 'models/engine' require 'models/car' class AssociationsJoinModelTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books, # Reload edges table from fixtures as otherwise repeated test was failing diff --git a/activerecord/test/cases/associations/required_test.rb b/activerecord/test/cases/associations/required_test.rb index 8b765a2e0c..3e5494e897 100644 --- a/activerecord/test/cases/associations/required_test.rb +++ b/activerecord/test/cases/associations/required_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class RequiredAssociationsTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Parent < ActiveRecord::Base end diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 243c90e945..ea2b94cbf4 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -758,12 +758,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_bulk_update_respects_access_control privatize("title=(value)") - assert_raise(ActiveModel::AttributeAssignment::UnknownAttributeError) { @target.new(:title => "Rants about pants") } - assert_raise(ActiveModel::AttributeAssignment::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } } + assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(:title => "Rants about pants") } + assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } } end def test_bulk_update_raise_unknown_attribute_error - error = assert_raises(ActiveModel::AttributeAssignment::UnknownAttributeError) { + error = assert_raises(ActiveRecord::UnknownAttributeError) { Topic.new(hello: "world") } assert_instance_of Topic, error.record diff --git a/activerecord/test/cases/attributes_test.rb b/activerecord/test/cases/attributes_test.rb index e7b76b1cf9..927d7950a5 100644 --- a/activerecord/test/cases/attributes_test.rb +++ b/activerecord/test/cases/attributes_test.rb @@ -58,7 +58,7 @@ module ActiveRecord data = OverloadedType.new(non_existent_decimal: 1) assert_equal BigDecimal.new(1), data.non_existent_decimal - assert_raise ActiveModel::AttributeAssignment::UnknownAttributeError do + assert_raise ActiveRecord::UnknownAttributeError do UnoverloadedType.new(non_existent_decimal: 1) end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 859afc4553..8f0d7bd037 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -629,7 +629,7 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase end class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false setup do @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -637,7 +637,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase end teardown do - # We are running without transactional fixtures and need to cleanup. + # We are running without transactional tests and need to cleanup. Bird.delete_all Parrot.delete_all @ship.delete @@ -1009,7 +1009,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase end class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1145,7 +1145,7 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase end class TestAutosaveAssociationOnAHasOneThroughAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1166,7 +1166,7 @@ class TestAutosaveAssociationOnAHasOneThroughAssociation < ActiveRecord::TestCas end class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1414,7 +1414,7 @@ module AutosaveAssociationOnACollectionAssociationTests end class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1430,7 +1430,7 @@ class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase end class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1447,7 +1447,7 @@ class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::T end class TestAutosaveAssociationOnAHasAndBelongsToManyAssociationWithAcceptsNestedAttributes < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1464,7 +1464,7 @@ class TestAutosaveAssociationOnAHasAndBelongsToManyAssociationWithAcceptsNestedA end class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1481,7 +1481,7 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te end class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1504,7 +1504,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes end class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1525,7 +1525,7 @@ class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord:: end class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super @@ -1548,7 +1548,7 @@ class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::Test end class TestAutosaveAssociationValidationMethodsGeneration < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup super diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 993350ebd6..4306738670 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- require "cases/helper" require 'active_support/concurrency/latch' @@ -1008,54 +1009,61 @@ class BasicsTest < ActiveRecord::TestCase end def test_switching_between_table_name + k = Class.new(Joke) + assert_difference("GoodJoke.count") do - Joke.table_name = "cold_jokes" - Joke.create + k.table_name = "cold_jokes" + k.create - Joke.table_name = "funny_jokes" - Joke.create + k.table_name = "funny_jokes" + k.create end end def test_clear_cash_when_setting_table_name - Joke.table_name = "cold_jokes" - before_columns = Joke.columns - before_seq = Joke.sequence_name + original_table_name = Joke.table_name Joke.table_name = "funny_jokes" + before_columns = Joke.columns + before_seq = Joke.sequence_name + + Joke.table_name = "cold_jokes" after_columns = Joke.columns - after_seq = Joke.sequence_name + after_seq = Joke.sequence_name assert_not_equal before_columns, after_columns assert_not_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil? + ensure + Joke.table_name = original_table_name end def test_dont_clear_sequence_name_when_setting_explicitly - Joke.sequence_name = "black_jokes_seq" - Joke.table_name = "cold_jokes" - before_seq = Joke.sequence_name + k = Class.new(Joke) + k.sequence_name = "black_jokes_seq" + k.table_name = "cold_jokes" + before_seq = k.sequence_name - Joke.table_name = "funny_jokes" - after_seq = Joke.sequence_name + k.table_name = "funny_jokes" + after_seq = k.sequence_name assert_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil? - ensure - Joke.reset_sequence_name end def test_dont_clear_inheritance_column_when_setting_explicitly - Joke.inheritance_column = "my_type" - before_inherit = Joke.inheritance_column + k = Class.new(Joke) + k.inheritance_column = "my_type" + before_inherit = k.inheritance_column - Joke.reset_column_information - after_inherit = Joke.inheritance_column + k.reset_column_information + after_inherit = k.inheritance_column assert_equal before_inherit, after_inherit unless before_inherit.blank? && after_inherit.blank? end def test_set_table_name_symbol_converted_to_string - Joke.table_name = :cold_jokes - assert_equal 'cold_jokes', Joke.table_name + k = Class.new(Joke) + k.table_name = :cold_jokes + assert_equal 'cold_jokes', k.table_name end def test_quoted_table_name_after_set_table_name diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index f0393aa6b1..8fc996ee74 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -11,6 +11,10 @@ require 'models/minivan' require 'models/speedometer' require 'models/ship_part' require 'models/treasure' +require 'models/developer' +require 'models/comment' +require 'models/rating' +require 'models/post' class NumericData < ActiveRecord::Base self.table_name = 'numeric_data' @@ -636,4 +640,11 @@ class CalculationsTest < ActiveRecord::TestCase Client.update_all(client_of: nil) assert_equal({ nil => Client.count }, Client.group(:firm).count) end + + def test_should_reference_correct_aliases_while_joining_tables_of_has_many_through_association + assert_nothing_raised ActiveRecord::StatementInvalid do + developer = Developer.create!(name: 'developer') + developer.ratings.includes(comment: :post).where(posts: { id: 1 }).count + end + end end diff --git a/activerecord/test/cases/date_time_precision_test.rb b/activerecord/test/cases/date_time_precision_test.rb index 6a4e64b22c..698f1b852e 100644 --- a/activerecord/test/cases/date_time_precision_test.rb +++ b/activerecord/test/cases/date_time_precision_test.rb @@ -4,7 +4,7 @@ require 'support/schema_dumping_helper' if ActiveRecord::Base.connection.supports_datetime_with_precision? class DateTimePrecisionTest < ActiveRecord::TestCase include SchemaDumpingHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Foo < ActiveRecord::Base; end diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index b9db0d0123..67fddebf45 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -90,14 +90,14 @@ end if current_adapter?(:MysqlAdapter, :Mysql2Adapter) class DefaultsTestWithoutTransactionalFixtures < ActiveRecord::TestCase # ActiveRecord::Base#create! (and #save and other related methods) will - # open a new transaction. When in transactional fixtures mode, this will + # open a new transaction. When in transactional tests mode, this will # cause Active Record to create a new savepoint. However, since MySQL doesn't # support DDL transactions, creating a table will result in any created # savepoints to be automatically released. This in turn causes the savepoint # release code in AbstractAdapter#transaction to fail. # - # We don't want that to happen, so we disable transactional fixtures here. - self.use_transactional_fixtures = false + # We don't want that to happen, so we disable transactional tests here. + self.use_transactional_tests = false def using_strict(strict) connection = ActiveRecord::Base.remove_connection diff --git a/activerecord/test/cases/disconnected_test.rb b/activerecord/test/cases/disconnected_test.rb index 94447addc1..55f0e51717 100644 --- a/activerecord/test/cases/disconnected_test.rb +++ b/activerecord/test/cases/disconnected_test.rb @@ -4,7 +4,7 @@ class TestRecord < ActiveRecord::Base end class TestDisconnectedAdapter < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false def setup @connection = ActiveRecord::Base.connection diff --git a/activerecord/test/cases/enum_test.rb b/activerecord/test/cases/enum_test.rb index 3b7bbcf47a..eea184e530 100644 --- a/activerecord/test/cases/enum_test.rb +++ b/activerecord/test/cases/enum_test.rb @@ -341,4 +341,18 @@ class EnumTest < ActiveRecord::TestCase book2.status = :uploaded assert_equal ['drafted', 'uploaded'], book2.status_change end + + test "declare multiple enums at a time" do + klass = Class.new(ActiveRecord::Base) do + self.table_name = "books" + enum status: [:proposed, :written, :published], + nullable_status: [:single, :married] + end + + book1 = klass.proposed.create! + assert book1.proposed? + + book2 = klass.single.create! + assert book2.single? + end end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 39308866ee..4b819a82e8 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -947,7 +947,6 @@ class FinderTest < ActiveRecord::TestCase end end - # http://dev.rubyonrails.org/ticket/6778 def test_find_ignores_previously_inserted_record Post.create!(:title => 'test', :body => 'it out') assert_equal [], Post.where(id: nil) diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 7ef2ebc998..f8acdcb51e 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -28,7 +28,7 @@ require 'tempfile' class FixturesTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true - self.use_transactional_fixtures = false + self.use_transactional_tests = false # other_topics fixture should not be included here fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights @@ -327,7 +327,7 @@ if Account.connection.respond_to?(:reset_pk_sequence!) fixtures :companies def setup - @instances = [Account.new(:credit_limit => 50), Company.new(:name => 'RoR Consulting')] + @instances = [Account.new(:credit_limit => 50), Company.new(:name => 'RoR Consulting'), Course.new(name: 'Test')] ActiveRecord::FixtureSet.reset_cache # make sure tables get reinitialized end @@ -419,7 +419,7 @@ end class TransactionalFixturesTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true - self.use_transactional_fixtures = true + self.use_transactional_tests = true fixtures :topics @@ -511,7 +511,7 @@ class CheckSetTableNameFixturesTest < ActiveRecord::TestCase fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_table_method assert_kind_of Joke, funny_jokes(:a_joke) @@ -523,7 +523,7 @@ class FixtureNameIsNotTableNameFixturesTest < ActiveRecord::TestCase fixtures :items # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_named_accessor assert_kind_of Book, items(:dvd) @@ -535,7 +535,7 @@ class FixtureNameIsNotTableNameMultipleFixturesTest < ActiveRecord::TestCase fixtures :items, :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_named_accessor_of_differently_named_fixture assert_kind_of Book, items(:dvd) @@ -549,7 +549,7 @@ end class CustomConnectionFixturesTest < ActiveRecord::TestCase set_fixture_class :courses => Course fixtures :courses - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_leaky_destroy assert_nothing_raised { courses(:ruby) } @@ -564,7 +564,7 @@ end class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase set_fixture_class :courses => Course fixtures :courses - self.use_transactional_fixtures = true + self.use_transactional_tests = true def test_leaky_destroy assert_nothing_raised { courses(:ruby) } @@ -580,7 +580,7 @@ class InvalidTableNameFixturesTest < ActiveRecord::TestCase fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our lack of set_fixture_class - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_raises_error assert_raise ActiveRecord::FixtureClassNotFound do @@ -594,7 +594,7 @@ class CheckEscapedYamlFixturesTest < ActiveRecord::TestCase fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_proper_escaped_fixture assert_equal "The \\n Aristocrats\nAte the candy\n", funny_jokes(:another_joke).name @@ -664,7 +664,7 @@ class LoadAllFixturesWithPathnameTest < ActiveRecord::TestCase end class FasterFixturesTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false fixtures :categories, :authors def load_extra_fixture(name) diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index f2ba28a32f..12c793c408 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -143,7 +143,7 @@ class ActiveSupport::TestCase self.fixture_path = FIXTURES_ROOT self.use_instantiated_fixtures = false - self.use_transactional_fixtures = true + self.use_transactional_tests = true def create_fixtures(*fixture_set_names, &block) ActiveRecord::FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, fixture_class_names, &block) @@ -203,8 +203,3 @@ module InTimeZone end require 'mocha/setup' # FIXME: stop using mocha - -# FIXME: we have tests that depend on run order, we should fix that and -# remove this method call. -require 'active_support/test_case' -ActiveSupport::TestCase.test_order = :sorted diff --git a/activerecord/test/cases/hot_compatibility_test.rb b/activerecord/test/cases/hot_compatibility_test.rb index b4617cf6f9..5ba9a1029a 100644 --- a/activerecord/test/cases/hot_compatibility_test.rb +++ b/activerecord/test/cases/hot_compatibility_test.rb @@ -1,7 +1,7 @@ require 'cases/helper' class HotCompatibilityTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false setup do @klass = Class.new(ActiveRecord::Base) do diff --git a/activerecord/test/cases/invalid_connection_test.rb b/activerecord/test/cases/invalid_connection_test.rb index 8416c81f45..6523fc29fd 100644 --- a/activerecord/test/cases/invalid_connection_test.rb +++ b/activerecord/test/cases/invalid_connection_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class TestAdapterWithInvalidConnection < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Bird < ActiveRecord::Base end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 848174df06..9e4998a946 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -285,10 +285,10 @@ end class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase fixtures :people, :legacy_things, :references - # need to disable transactional fixtures, because otherwise the sqlite3 + # need to disable transactional tests, because otherwise the sqlite3 # adapter (at least) chokes when we try and change the schema in the middle # of a test (see test_increment_counter_*). - self.use_transactional_fixtures = false + self.use_transactional_tests = false { :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model| define_method("test_increment_counter_updates_#{name}") do @@ -365,7 +365,7 @@ end # (See exec vs. async_exec in the PostgreSQL adapter.) unless in_memory_db? class PessimisticLockingTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false fixtures :people, :readers def setup diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb index 30c91dfdcb..46a62c272f 100644 --- a/activerecord/test/cases/migration/change_schema_test.rb +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -426,7 +426,7 @@ module ActiveRecord if ActiveRecord::Base.connection.supports_foreign_keys? class ChangeSchemaWithDependentObjectsTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false setup do @connection = ActiveRecord::Base.connection diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb index 763aa88f72..8d8e661aa5 100644 --- a/activerecord/test/cases/migration/column_attributes_test.rb +++ b/activerecord/test/cases/migration/column_attributes_test.rb @@ -5,7 +5,7 @@ module ActiveRecord class ColumnAttributesTest < ActiveRecord::TestCase include ActiveRecord::Migration::TestHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_add_column_newline_default string = "foo\nbar" diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb index e5ccfe0f91..5fc7702dfa 100644 --- a/activerecord/test/cases/migration/columns_test.rb +++ b/activerecord/test/cases/migration/columns_test.rb @@ -5,7 +5,7 @@ module ActiveRecord class ColumnsTest < ActiveRecord::TestCase include ActiveRecord::Migration::TestHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false # FIXME: this is more of an integration test with AR::Base and the # schema modifications. Maybe we should move this? diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb index bea9d6b2c9..8fd08fe4ce 100644 --- a/activerecord/test/cases/migration/create_join_table_test.rb +++ b/activerecord/test/cases/migration/create_join_table_test.rb @@ -140,7 +140,7 @@ module ActiveRecord tables_after = connection.tables - tables_before tables_after.each do |table| - connection.execute "DROP TABLE #{table}" + connection.drop_table table end end end diff --git a/activerecord/test/cases/migration/logger_test.rb b/activerecord/test/cases/migration/logger_test.rb index 319d3e1af3..bf6e684887 100644 --- a/activerecord/test/cases/migration/logger_test.rb +++ b/activerecord/test/cases/migration/logger_test.rb @@ -4,7 +4,7 @@ module ActiveRecord class Migration class LoggerTest < ActiveRecord::TestCase # MySQL can't roll back ddl changes - self.use_transactional_fixtures = false + self.use_transactional_tests = false Migration = Struct.new(:name, :version) do def disable_ddl_transaction; false end diff --git a/activerecord/test/cases/migration/references_statements_test.rb b/activerecord/test/cases/migration/references_statements_test.rb index 988bd9c89f..f613fd66c3 100644 --- a/activerecord/test/cases/migration/references_statements_test.rb +++ b/activerecord/test/cases/migration/references_statements_test.rb @@ -5,7 +5,7 @@ module ActiveRecord class ReferencesStatementsTest < ActiveRecord::TestCase include ActiveRecord::Migration::TestHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false def setup super diff --git a/activerecord/test/cases/migration/rename_table_test.rb b/activerecord/test/cases/migration/rename_table_test.rb index 3eef308428..6d742d3f2f 100644 --- a/activerecord/test/cases/migration/rename_table_test.rb +++ b/activerecord/test/cases/migration/rename_table_test.rb @@ -5,7 +5,7 @@ module ActiveRecord class RenameTableTest < ActiveRecord::TestCase include ActiveRecord::Migration::TestHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false def setup super diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 3b73685a2c..b2f209fe97 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -24,7 +24,7 @@ class Reminder < ActiveRecord::Base; end class Thing < ActiveRecord::Base; end class MigrationTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false fixtures :people diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index c0daa83e9c..2ff6938e7b 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -2,7 +2,7 @@ require "cases/helper" require "cases/migration/helper" class MigratorTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false # Use this class to sense if migrations have gone # up or down. @@ -312,7 +312,7 @@ class MigratorTest < ActiveRecord::TestCase def test_migrator_db_has_no_schema_migrations_table _, migrator = migrator_class(3) - ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations") + ActiveRecord::Base.connection.drop_table "schema_migrations", if_exists: true assert_not ActiveRecord::Base.connection.table_exists?('schema_migrations') migrator.migrate("valid", 1) assert ActiveRecord::Base.connection.table_exists?('schema_migrations') diff --git a/activerecord/test/cases/mixin_test.rb b/activerecord/test/cases/mixin_test.rb index 7ddb2bfee1..7ebdcac711 100644 --- a/activerecord/test/cases/mixin_test.rb +++ b/activerecord/test/cases/mixin_test.rb @@ -61,8 +61,6 @@ class TouchTest < ActiveRecord::TestCase # Make sure Mixin.record_timestamps gets reset, even if this test fails, # so that other tests do not fail because Mixin.record_timestamps == false - rescue Exception => e - raise e ensure Mixin.record_timestamps = true end diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index 6f65bf80eb..7f31325f47 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -68,8 +68,7 @@ class ModulesTest < ActiveRecord::TestCase end end - # need to add an eager loading condition to force the eager loading model into - # the old join model, to test that. See http://dev.rubyonrails.org/ticket/9640 + # An eager loading condition to force the eager loading model into the old join model. def test_eager_loading_in_modules clients = [] diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index f9bc266e84..39cdcf5403 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -4,7 +4,7 @@ require 'models/bird' require 'models/course' class MultipleDbTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false def setup @courses = create_fixtures("courses") { Course.retrieve_connection } diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 198cd6f341..6b4addd52f 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -672,7 +672,7 @@ module NestedAttributesOnACollectionAssociationTests end def test_should_not_assign_destroy_key_to_a_record - assert_nothing_raised ActiveModel::AttributeAssignment::UnknownAttributeError do + assert_nothing_raised ActiveRecord::UnknownAttributeError do @pirate.send(association_setter, { 'foo' => { '_destroy' => '0' }}) end end @@ -943,7 +943,7 @@ class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase end class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup @pirate = Pirate.create!(:catchphrase => "My baby takes tha mornin' train!") @@ -983,7 +983,7 @@ class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRe end class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_tests = false unless supports_savepoints? def setup @ship = Ship.create!(:name => "The good ship Dollypop") diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 2803ad2de0..2370077eb0 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -366,6 +366,12 @@ class PersistenceTest < ActiveRecord::TestCase end end + def test_update_does_not_run_sql_if_record_has_not_changed + topic = Topic.create(title: 'Another New Topic') + assert_queries(0) { topic.update(title: 'Another New Topic') } + assert_queries(0) { topic.update_attributes(title: 'Another New Topic') } + end + def test_delete topic = Topic.find(1) assert_equal topic, topic.delete, 'topic.delete did not return self' @@ -892,7 +898,7 @@ class PersistenceTest < ActiveRecord::TestCase end class SaveTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_save_touch_false widget = Class.new(ActiveRecord::Base) do diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 287a3f33ea..daa3271777 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -3,7 +3,7 @@ require "models/project" require "timeout" class PooledConnectionsTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false def setup @per_test_teardown = [] diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb index 1ea1ef5e12..3664a2af70 100644 --- a/activerecord/test/cases/primary_keys_test.rb +++ b/activerecord/test/cases/primary_keys_test.rb @@ -178,7 +178,7 @@ class PrimaryKeysTest < ActiveRecord::TestCase end class PrimaryKeyWithNoConnectionTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false unless in_memory_db? def test_set_primary_key_with_no_connection @@ -199,7 +199,7 @@ end class PrimaryKeyAnyTypeTest < ActiveRecord::TestCase include SchemaDumpingHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Barcode < ActiveRecord::Base end @@ -229,7 +229,7 @@ end if current_adapter?(:MysqlAdapter, :Mysql2Adapter) class PrimaryKeyWithAnsiQuotesTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false def test_primary_key_method_with_ansi_quotes con = ActiveRecord::Base.connection @@ -245,7 +245,7 @@ if current_adapter?(:PostgreSQLAdapter, :MysqlAdapter, :Mysql2Adapter) class PrimaryKeyBigSerialTest < ActiveRecord::TestCase include SchemaDumpingHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Widget < ActiveRecord::Base end diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 67e9bef808..7b47c80331 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -23,6 +23,7 @@ require 'models/chef' require 'models/department' require 'models/cake_designer' require 'models/drink_designer' +require 'models/recipe' class ReflectionTest < ActiveRecord::TestCase include ActiveRecord::Reflection @@ -277,6 +278,22 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal 2, @hotel.chefs.size end + def test_scope_chain_of_polymorphic_association_does_not_leak_into_other_hmt_associations + hotel = Hotel.create! + department = hotel.departments.create! + drink = department.chefs.create!(employable: DrinkDesigner.create!) + Recipe.create!(chef_id: drink.id, hotel_id: hotel.id) + + expected_sql = capture_sql { hotel.recipes.to_a } + + Hotel.reflect_on_association(:recipes).clear_association_scope_cache + hotel.reload + hotel.drink_designers.to_a + loaded_sql = capture_sql { hotel.recipes.to_a } + + assert_equal expected_sql, loaded_sql + end + def test_nested? assert !Author.reflect_on_association(:comments).nested? assert Author.reflect_on_association(:tags).nested? diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 513f65f707..6c099719c0 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -3,7 +3,7 @@ require 'support/schema_dumping_helper' class SchemaDumperTest < ActiveRecord::TestCase include SchemaDumpingHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false setup do ActiveRecord::SchemaMigration.create_table @@ -248,6 +248,11 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r{t\.integer\s+"bigint_default",\s+limit: 8,\s+default: 0}, output end + def test_schema_dump_includes_limit_on_array_type + output = standard_dump + assert_match %r{t\.integer\s+"big_int_data_points\",\s+limit: 8,\s+array: true}, output + end + if ActiveRecord::Base.connection.supports_extensions? def test_schema_dump_includes_extensions connection = ActiveRecord::Base.connection diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index e29f7462c8..7c92453ee3 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -264,4 +264,14 @@ class SerializedAttributeTest < ActiveRecord::TestCase Topic.serialize(:content, Regexp) end end + + def test_newly_emptied_serialized_hash_is_changed + Topic.serialize(:content, Hash) + topic = Topic.create(content: { "things" => "stuff" }) + topic.content.delete("things") + topic.save! + topic.reload + + assert_equal({}, topic.content) + end end diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb index 2fa033ed45..38164b2228 100644 --- a/activerecord/test/cases/tasks/database_tasks_test.rb +++ b/activerecord/test/cases/tasks/database_tasks_test.rb @@ -377,4 +377,20 @@ module ActiveRecord ActiveRecord::Tasks::DatabaseTasks.check_schema_file("awesome-file.sql") end end + + class DatabaseTasksCheckSchemaFileDefaultsTest < ActiveRecord::TestCase + def test_check_schema_file_defaults + ActiveRecord::Tasks::DatabaseTasks.stubs(:db_dir).returns('/tmp') + assert_equal '/tmp/schema.rb', ActiveRecord::Tasks::DatabaseTasks.schema_file + end + end + + class DatabaseTasksCheckSchemaFileSpecifiedFormatsTest < ActiveRecord::TestCase + {ruby: 'schema.rb', sql: 'structure.sql'}.each_pair do |fmt, filename| + define_method("test_check_schema_file_for_#{fmt}_format") do + ActiveRecord::Tasks::DatabaseTasks.stubs(:db_dir).returns('/tmp') + assert_equal "/tmp/#{filename}", ActiveRecord::Tasks::DatabaseTasks.schema_file(fmt) + end + end + end end diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index 0d574d071c..084302cde5 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -195,21 +195,54 @@ module ActiveRecord 'adapter' => 'postgresql', 'database' => 'my-app-db' } + @filename = "awesome-file.sql" ActiveRecord::Base.stubs(:connection).returns(@connection) ActiveRecord::Base.stubs(:establish_connection).returns(true) Kernel.stubs(:system) + File.stubs(:open) end def test_structure_dump - filename = "awesome-file.sql" - Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{filename} my-app-db").returns(true) - @connection.expects(:schema_search_path).returns("foo") + Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{@filename} my-app-db").returns(true) + + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end + + def test_structure_dump_with_schema_search_path + @configuration['schema_search_path'] = 'foo,bar' + + Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{@filename} --schema=foo --schema=bar my-app-db").returns(true) + + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end + + def test_structure_dump_with_schema_search_path_and_dump_schemas_all + @configuration['schema_search_path'] = 'foo,bar' + + Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{@filename} my-app-db").returns(true) + + with_dump_schemas(:all) do + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end + end + + def test_structure_dump_with_dump_schemas_string + Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{@filename} --schema=foo --schema=bar my-app-db").returns(true) + + with_dump_schemas('foo,bar') do + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end + end + + private - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) - assert File.exist?(filename) + def with_dump_schemas(value, &block) + old_dump_schemas = ActiveRecord::Base.dump_schemas + ActiveRecord::Base.dump_schemas = value + yield ensure - FileUtils.rm(filename) + ActiveRecord::Base.dump_schemas = old_dump_schemas end end @@ -228,14 +261,14 @@ module ActiveRecord def test_structure_load filename = "awesome-file.sql" - Kernel.expects(:system).with("psql -q -f #{filename} my-app-db") + Kernel.expects(:system).with("psql -X -q -f #{filename} my-app-db") ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) end def test_structure_load_accepts_path_with_spaces filename = "awesome file.sql" - Kernel.expects(:system).with("psql -q -f awesome\\ file.sql my-app-db") + Kernel.expects(:system).with("psql -X -q -f awesome\\ file.sql my-app-db") ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) end diff --git a/activerecord/test/cases/test_fixtures_test.rb b/activerecord/test/cases/test_fixtures_test.rb new file mode 100644 index 0000000000..3f4baf8378 --- /dev/null +++ b/activerecord/test/cases/test_fixtures_test.rb @@ -0,0 +1,36 @@ +require 'cases/helper' + +class TestFixturesTest < ActiveRecord::TestCase + setup do + @klass = Class.new + @klass.send(:include, ActiveRecord::TestFixtures) + end + + def test_deprecated_use_transactional_fixtures= + assert_deprecated 'use use_transactional_tests= instead' do + @klass.use_transactional_fixtures = true + end + end + + def test_use_transactional_tests_prefers_use_transactional_fixtures + ActiveSupport::Deprecation.silence do + @klass.use_transactional_fixtures = false + end + + assert_equal false, @klass.use_transactional_tests + end + + def test_use_transactional_tests_defaults_to_true + ActiveSupport::Deprecation.silence do + @klass.use_transactional_fixtures = nil + end + + assert_equal true, @klass.use_transactional_tests + end + + def test_use_transactional_tests_can_be_overriden + @klass.use_transactional_tests = "foobar" + + assert_equal "foobar", @klass.use_transactional_tests + end +end diff --git a/activerecord/test/cases/time_precision_test.rb b/activerecord/test/cases/time_precision_test.rb index ff4e5ecec5..ff7a81fe60 100644 --- a/activerecord/test/cases/time_precision_test.rb +++ b/activerecord/test/cases/time_precision_test.rb @@ -4,7 +4,7 @@ require 'support/schema_dumping_helper' if ActiveRecord::Base.connection.supports_datetime_with_precision? class TimePrecisionTest < ActiveRecord::TestCase include SchemaDumpingHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Foo < ActiveRecord::Base; end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index c0c62527df..7c89b4b9e8 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -450,7 +450,7 @@ end class TimestampsWithoutTransactionTest < ActiveRecord::TestCase include DdlHelper - self.use_transactional_fixtures = false + self.use_transactional_tests = false class TimestampAttributePost < ActiveRecord::Base attr_accessor :created_at, :updated_at diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index e868022fed..f2229939c8 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -367,7 +367,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase end class CallbacksOnMultipleActionsTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class TopicWithCallbacksOnMultipleActions < ActiveRecord::Base self.table_name = :topics @@ -376,6 +376,9 @@ class CallbacksOnMultipleActionsTest < ActiveRecord::TestCase after_commit(on: [:create, :update]) { |record| record.history << :create_and_update } after_commit(on: [:update, :destroy]) { |record| record.history << :update_and_destroy } + before_commit(if: :save_before_commit_history) { |record| record.history << :before_commit } + before_commit(if: :update_title) { |record| record.update(title: "before commit title") } + def clear_history @history = [] end @@ -383,6 +386,8 @@ class CallbacksOnMultipleActionsTest < ActiveRecord::TestCase def history @history ||= [] end + + attr_accessor :save_before_commit_history, :update_title end def test_after_commit_on_multiple_actions @@ -399,6 +404,23 @@ class CallbacksOnMultipleActionsTest < ActiveRecord::TestCase topic.destroy assert_equal [:update_and_destroy, :create_and_destroy], topic.history end + + def test_before_commit_actions + topic = TopicWithCallbacksOnMultipleActions.new + topic.save_before_commit_history = true + topic.save + + assert_equal [:before_commit, :create_and_update, :create_and_destroy], topic.history + end + + def test_before_commit_update_in_same_transaction + topic = TopicWithCallbacksOnMultipleActions.new + topic.update_title = true + topic.save + + assert_equal "before commit title", topic.title + assert_equal "before commit title", topic.reload.title + end end diff --git a/activerecord/test/cases/transaction_isolation_test.rb b/activerecord/test/cases/transaction_isolation_test.rb index f89c26532d..2f7d208ed2 100644 --- a/activerecord/test/cases/transaction_isolation_test.rb +++ b/activerecord/test/cases/transaction_isolation_test.rb @@ -2,7 +2,7 @@ require 'cases/helper' unless ActiveRecord::Base.connection.supports_transaction_isolation? class TransactionIsolationUnsupportedTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Tag < ActiveRecord::Base end @@ -17,7 +17,7 @@ end if ActiveRecord::Base.connection.supports_transaction_isolation? class TransactionIsolationTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false class Tag < ActiveRecord::Base self.table_name = 'tags' diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 88e595c39f..2468a91969 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -9,7 +9,7 @@ require 'models/post' require 'models/movie' class TransactionTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false fixtures :topics, :developers, :authors, :posts def setup @@ -584,6 +584,24 @@ class TransactionTest < ActiveRecord::TestCase assert_not topic.frozen? end + def test_rollback_of_frozen_records + topic = Topic.create.freeze + Topic.transaction do + topic.destroy + raise ActiveRecord::Rollback + end + assert topic.frozen?, 'frozen' + end + + def test_rollback_for_freshly_persisted_records + topic = Topic.create + Topic.transaction do + topic.destroy + raise ActiveRecord::Rollback + end + assert topic.persisted?, 'persisted' + end + def test_sqlite_add_column_in_transaction return true unless current_adapter?(:SQLite3Adapter) @@ -685,7 +703,7 @@ class TransactionTest < ActiveRecord::TestCase end class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase - self.use_transactional_fixtures = true + self.use_transactional_tests = true fixtures :topics def test_automatic_savepoint_in_outer_transaction diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index afb893a52c..b210584644 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -4,7 +4,7 @@ class TestRecord < ActiveRecord::Base end class TestUnconnectedAdapter < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_tests = false def setup @underlying = ActiveRecord::Base.connection diff --git a/activerecord/test/cases/validations/length_validation_test.rb b/activerecord/test/cases/validations/length_validation_test.rb index 952e1681a7..f95f8f0b8f 100644 --- a/activerecord/test/cases/validations/length_validation_test.rb +++ b/activerecord/test/cases/validations/length_validation_test.rb @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- require "cases/helper" require 'models/owner' require 'models/pet' @@ -5,49 +6,49 @@ require 'models/person' class LengthValidationTest < ActiveRecord::TestCase fixtures :owners - repair_validations(Owner) - def test_validates_size_of_association - repair_validations Owner do - assert_nothing_raised { Owner.validates_size_of :pets, :minimum => 1 } - o = Owner.new('name' => 'nopets') - assert !o.save - assert o.errors[:pets].any? - o.pets.build('name' => 'apet') - assert o.valid? + setup do + @owner = Class.new(Owner) do + def self.name; 'Owner'; end end end + + def test_validates_size_of_association + assert_nothing_raised { @owner.validates_size_of :pets, minimum: 1 } + o = @owner.new('name' => 'nopets') + assert !o.save + assert o.errors[:pets].any? + o.pets.build('name' => 'apet') + assert o.valid? + end + def test_validates_size_of_association_using_within - repair_validations Owner do - assert_nothing_raised { Owner.validates_size_of :pets, :within => 1..2 } - o = Owner.new('name' => 'nopets') - assert !o.save - assert o.errors[:pets].any? + assert_nothing_raised { @owner.validates_size_of :pets, within: 1..2 } + o = @owner.new('name' => 'nopets') + assert !o.save + assert o.errors[:pets].any? - o.pets.build('name' => 'apet') - assert o.valid? + o.pets.build('name' => 'apet') + assert o.valid? - 2.times { o.pets.build('name' => 'apet') } - assert !o.save - assert o.errors[:pets].any? - end + 2.times { o.pets.build('name' => 'apet') } + assert !o.save + assert o.errors[:pets].any? end def test_validates_size_of_association_utf8 - repair_validations Owner do - Owner.validates_size_of :pets, :minimum => 1 - o = Owner.new('name' => 'あいうえおかきくけこ') - assert !o.save - assert o.errors[:pets].any? - o.pets.build('name' => 'あいうえおかきくけこ') - assert o.valid? - end + @owner.validates_size_of :pets, minimum: 1 + o = @owner.new('name' => 'あいうえおかきくけこ') + assert !o.save + assert o.errors[:pets].any? + o.pets.build('name' => 'あいうえおかきくけこ') + assert o.valid? end def test_validates_size_of_respects_records_marked_for_destruction - Owner.validates_size_of :pets, minimum: 1 - owner = Owner.new + @owner.validates_size_of :pets, minimum: 1 + owner = @owner.new assert_not owner.save assert owner.errors[:pets].any? pet = owner.pets.build @@ -62,8 +63,8 @@ class LengthValidationTest < ActiveRecord::TestCase end def test_does_not_validate_length_of_if_parent_record_is_validate_false - Owner.validates_length_of :name, minimum: 1 - owner = Owner.new + @owner.validates_length_of :name, minimum: 1 + owner = @owner.new owner.save!(validate: false) assert owner.persisted? diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index bce59b4fcd..56909a8630 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -83,4 +83,39 @@ class YamlSerializationTest < ActiveRecord::TestCase assert_equal 5, author.posts_count assert_equal 5, dumped.posts_count end + + def test_a_yaml_version_is_provided_for_future_backwards_compat + coder = {} + Topic.first.encode_with(coder) + + assert coder['active_record_yaml_version'] + end + + def test_deserializing_rails_41_yaml + topic = YAML.load(yaml_fixture("rails_4_1")) + + assert topic.new_record? + assert_equal nil, topic.id + assert_equal "The First Topic", topic.title + assert_equal({ omg: :lol }, topic.content) + end + + def test_deserializing_rails_4_2_0_yaml + topic = YAML.load(yaml_fixture("rails_4_2_0")) + + assert_not topic.new_record? + assert_equal 1, topic.id + assert_equal "The First Topic", topic.title + assert_equal("Have a nice day", topic.content) + end + + private + + def yaml_fixture(file_name) + path = File.expand_path( + "../../support/yaml_compatibility_fixtures/#{file_name}.yml", + __FILE__ + ) + File.read(path) + end end diff --git a/activerecord/test/models/chef.rb b/activerecord/test/models/chef.rb index 67a4e54f06..698a52e045 100644 --- a/activerecord/test/models/chef.rb +++ b/activerecord/test/models/chef.rb @@ -1,3 +1,4 @@ class Chef < ActiveRecord::Base belongs_to :employable, polymorphic: true + has_many :recipes end diff --git a/activerecord/test/models/hotel.rb b/activerecord/test/models/hotel.rb index b352cd22f3..491f8dfde3 100644 --- a/activerecord/test/models/hotel.rb +++ b/activerecord/test/models/hotel.rb @@ -3,4 +3,5 @@ class Hotel < ActiveRecord::Base has_many :chefs, through: :departments has_many :cake_designers, source_type: 'CakeDesigner', source: :employable, through: :chefs has_many :drink_designers, source_type: 'DrinkDesigner', source: :employable, through: :chefs + has_many :recipes, through: :chefs end diff --git a/activerecord/test/models/recipe.rb b/activerecord/test/models/recipe.rb new file mode 100644 index 0000000000..c387230603 --- /dev/null +++ b/activerecord/test/models/recipe.rb @@ -0,0 +1,3 @@ +class Recipe < ActiveRecord::Base + belongs_to :chef +end diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb index a9a6514c9d..d6fd0c4ab0 100644 --- a/activerecord/test/schema/mysql2_specific_schema.rb +++ b/activerecord/test/schema/mysql2_specific_schema.rb @@ -35,9 +35,7 @@ BEGIN END SQL - ActiveRecord::Base.connection.execute <<-SQL -DROP TABLE IF EXISTS collation_tests; -SQL + ActiveRecord::Base.connection.drop_table "collation_tests", if_exists: true ActiveRecord::Base.connection.execute <<-SQL CREATE TABLE collation_tests ( @@ -46,9 +44,7 @@ CREATE TABLE collation_tests ( ) CHARACTER SET utf8 COLLATE utf8_general_ci SQL - ActiveRecord::Base.connection.execute <<-SQL -DROP TABLE IF EXISTS enum_tests; -SQL + ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true ActiveRecord::Base.connection.execute <<-SQL CREATE TABLE enum_tests ( diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb index f2cffca52c..b5378341b5 100644 --- a/activerecord/test/schema/mysql_specific_schema.rb +++ b/activerecord/test/schema/mysql_specific_schema.rb @@ -46,9 +46,7 @@ BEGIN END SQL - ActiveRecord::Base.connection.execute <<-SQL -DROP TABLE IF EXISTS collation_tests; -SQL + ActiveRecord::Base.connection.drop_table "collation_tests", if_exists: true ActiveRecord::Base.connection.execute <<-SQL CREATE TABLE collation_tests ( @@ -57,9 +55,7 @@ CREATE TABLE collation_tests ( ) CHARACTER SET utf8 COLLATE utf8_general_ci SQL - ActiveRecord::Base.connection.execute <<-SQL -DROP TABLE IF EXISTS enum_tests; -SQL + ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true ActiveRecord::Base.connection.execute <<-SQL CREATE TABLE enum_tests ( diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb index f84be0e7f4..008503bc24 100644 --- a/activerecord/test/schema/postgresql_specific_schema.rb +++ b/activerecord/test/schema/postgresql_specific_schema.rb @@ -93,4 +93,8 @@ _SQL t.binary :binary, limit: 100_000 t.text :text, limit: 100_000 end + + create_table :bigint_array, force: true do |t| + t.integer :big_int_data_points, limit: 8, array: true + end end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 5e5f7a798e..7b42f8a4a5 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -886,6 +886,10 @@ ActiveRecord::Schema.define do t.string :employable_type t.integer :department_id end + create_table :recipes, force: true do |t| + t.integer :chef_id + t.integer :hotel_id + end create_table :records, force: true do |t| end diff --git a/activerecord/test/support/yaml_compatibility_fixtures/rails_4_1.yml b/activerecord/test/support/yaml_compatibility_fixtures/rails_4_1.yml new file mode 100644 index 0000000000..20b128db9c --- /dev/null +++ b/activerecord/test/support/yaml_compatibility_fixtures/rails_4_1.yml @@ -0,0 +1,22 @@ +--- !ruby/object:Topic + attributes: + id: + title: The First Topic + author_name: David + author_email_address: david@loudthinking.com + written_on: 2003-07-16 14:28:11.223300000 Z + bonus_time: 2000-01-01 14:28:00.000000000 Z + last_read: 2004-04-15 + content: | + --- + :omg: :lol + important: + approved: false + replies_count: 1 + unique_replies_count: 0 + parent_id: + parent_title: + type: + group: + created_at: 2015-03-10 17:05:42.000000000 Z + updated_at: 2015-03-10 17:05:42.000000000 Z diff --git a/activerecord/test/support/yaml_compatibility_fixtures/rails_4_2_0.yml b/activerecord/test/support/yaml_compatibility_fixtures/rails_4_2_0.yml new file mode 100644 index 0000000000..b3d3b33141 --- /dev/null +++ b/activerecord/test/support/yaml_compatibility_fixtures/rails_4_2_0.yml @@ -0,0 +1,182 @@ +--- !ruby/object:Topic +raw_attributes: + id: 1 + title: The First Topic + author_name: David + author_email_address: david@loudthinking.com + written_on: '2003-07-16 14:28:11.223300' + bonus_time: '2005-01-30 14:28:00.000000' + last_read: '2004-04-15' + content: | + --- Have a nice day + ... + important: + approved: f + replies_count: 1 + unique_replies_count: 0 + parent_id: + parent_title: + type: + group: + created_at: '2015-03-10 17:44:41' + updated_at: '2015-03-10 17:44:41' +attributes: !ruby/object:ActiveRecord::AttributeSet + attributes: !ruby/object:ActiveRecord::LazyAttributeHash + types: + id: &5 !ruby/object:ActiveRecord::Type::Integer + precision: + scale: + limit: + range: !ruby/range + begin: -2147483648 + end: 2147483648 + excl: true + title: &6 !ruby/object:ActiveRecord::Type::String + precision: + scale: + limit: 250 + author_name: &1 !ruby/object:ActiveRecord::Type::String + precision: + scale: + limit: + author_email_address: *1 + written_on: &4 !ruby/object:ActiveRecord::Type::DateTime + precision: + scale: + limit: + bonus_time: &7 !ruby/object:ActiveRecord::Type::Time + precision: + scale: + limit: + last_read: &8 !ruby/object:ActiveRecord::Type::Date + precision: + scale: + limit: + content: !ruby/object:ActiveRecord::Type::Serialized + coder: &9 !ruby/object:ActiveRecord::Coders::YAMLColumn + object_class: !ruby/class 'Object' + subtype: &2 !ruby/object:ActiveRecord::Type::Text + precision: + scale: + limit: + important: *2 + approved: &10 !ruby/object:ActiveRecord::Type::Boolean + precision: + scale: + limit: + replies_count: &3 !ruby/object:ActiveRecord::Type::Integer + precision: + scale: + limit: + range: !ruby/range + begin: -2147483648 + end: 2147483648 + excl: true + unique_replies_count: *3 + parent_id: *3 + parent_title: *1 + type: *1 + group: *1 + created_at: *4 + updated_at: *4 + values: + id: 1 + title: The First Topic + author_name: David + author_email_address: david@loudthinking.com + written_on: '2003-07-16 14:28:11.223300' + bonus_time: '2005-01-30 14:28:00.000000' + last_read: '2004-04-15' + content: | + --- Have a nice day + ... + important: + approved: f + replies_count: 1 + unique_replies_count: 0 + parent_id: + parent_title: + type: + group: + created_at: '2015-03-10 17:44:41' + updated_at: '2015-03-10 17:44:41' + additional_types: {} + materialized: true + delegate_hash: + id: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: id + value_before_type_cast: 1 + type: *5 + title: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: title + value_before_type_cast: The First Topic + type: *6 + author_name: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: author_name + value_before_type_cast: David + type: *1 + author_email_address: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: author_email_address + value_before_type_cast: david@loudthinking.com + type: *1 + written_on: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: written_on + value_before_type_cast: '2003-07-16 14:28:11.223300' + type: *4 + bonus_time: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: bonus_time + value_before_type_cast: '2005-01-30 14:28:00.000000' + type: *7 + last_read: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: last_read + value_before_type_cast: '2004-04-15' + type: *8 + content: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: content + value_before_type_cast: | + --- Have a nice day + ... + type: !ruby/object:ActiveRecord::Type::Serialized + coder: *9 + subtype: *2 + important: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: important + value_before_type_cast: + type: *2 + approved: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: approved + value_before_type_cast: f + type: *10 + replies_count: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: replies_count + value_before_type_cast: 1 + type: *3 + unique_replies_count: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: unique_replies_count + value_before_type_cast: 0 + type: *3 + parent_id: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: parent_id + value_before_type_cast: + type: *3 + parent_title: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: parent_title + value_before_type_cast: + type: *1 + type: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: type + value_before_type_cast: + type: *1 + group: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: group + value_before_type_cast: + type: *1 + created_at: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: created_at + value_before_type_cast: '2015-03-10 17:44:41' + type: *4 + updated_at: !ruby/object:ActiveRecord::Attribute::FromDatabase + name: updated_at + value_before_type_cast: '2015-03-10 17:44:41' + type: *4 +new_record: false |