diff options
Diffstat (limited to 'activerecord')
283 files changed, 17433 insertions, 13088 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG deleted file mode 100644 index a54526dd41..0000000000 --- a/activerecord/CHANGELOG +++ /dev/null @@ -1,6514 +0,0 @@ -Wed Sep 7 15:25:02 2011 Aaron Patterson <aaron@tenderlovemaking.com> - - * lib/active_record/connection_adapters/mysql_adapter.rb: LRU cache - keys are per process id. - * lib/active_record/connection_adapters/sqlite_adapter.rb: ditto - -* Add first_or_create, first_or_create!, first_or_initialize methods to Active Record. This is a - better approach over the old find_or_create_by dynamic methods because it's clearer which - arguments are used to find the record and which are used to create it: - - User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson") - - [Andrés Mejía] - -* Support bulk change_table in mysql2 adapter, as well as the mysql one. [Jon Leighton] - -* If multiple parameters are sent representing a date, and some are blank, the -resulting object is nil. In previous releases those values defaulted to 1. This -only affects existing but blank parameters, missing ones still raise an error. -[Akira Matsuda] - -* ActiveRecord::Base.establish_connection now takes a string that contains -a URI that specifies the connection configuration. For example: - - ActiveRecord::Base.establish_connection 'postgres://localhost/foo' - -* Active Record's dynamic finder will now raise the error if you passing in less number of arguments than what you call in method signature. - - So if you were doing this and expecting the second argument to be nil: - - User.find_by_username_and_group("sikachu") - - You'll now get `ArgumentError: wrong number of arguments (1 for 2).` You'll then have to do this: - - User.find_by_username_and_group("sikachu", nil) - - [Prem Sichanugrist] - -*Rails 3.1.0 (August 30, 2011)* - -* Add a proxy_association method to association proxies, which can be called by association - extensions to access information about the association. This replaces proxy_owner etc with - proxy_association.owner. - - [Jon Leighton] - -* ActiveRecord::MacroReflection::AssociationReflection#build_record has a new method signature. - - Before: def build_association(*options) - After: def build_association(*options, &block) - - Users who are redefining this method to extend functionality should ensure that the block is - passed through to ActiveRecord::Base#new. - - This change is necessary to fix https://github.com/rails/rails/issues/1842. - - [Jon Leighton] - -* AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model: - - class User < ActiveRecord::Base - self.pluralize_table_names = false - end - - Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. [Guillermo Iguaran] - -* Add block setting of attributes to singular associations: - - class User < ActiveRecord::Base - has_one :account - end - - user.build_account{ |a| a.credit_limit => 100.0 } - - The block is called after the instance has been initialized. [Andrew White] - -* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. [Prem Sichanugrist] - -* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0 - -* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you - to specify which role to consider when assigning attributes. This is built on top of ActiveModel's - new mass assignment capabilities: - - class Post < ActiveRecord::Base - attr_accessible :title - attr_accessible :title, :published_at, :as => :admin - end - - Post.new(params[:post], :as => :admin) - - assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated. - - Please note that this changes the method signatures for AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes!. If you have overwritten these methods you should update them accordingly. - - [Josh Kalderimis] - -* default_scope can take a block, lambda, or any other object which responds to `call` for lazy - evaluation: - - default_scope { ... } - default_scope lambda { ... } - default_scope method(:foo) - - This feature was originally implemented by Tim Morgan, but was then removed in favour of - defining a 'default_scope' class method, but has now been added back in by Jon Leighton. - The relevant lighthouse ticket is #1812. - -* Default scopes are now evaluated at the latest possible moment, to avoid problems where - scopes would be created which would implicitly contain the default scope, which would then - be impossible to get rid of via Model.unscoped. - - Note that this means that if you are inspecting the internal structure of an - ActiveRecord::Relation, it will *not* contain the default scope, though the resulting - query will do. You can get a relation containing the default scope by calling - ActiveRecord#with_default_scope, though this is not part of the public API. - - [Jon Leighton] - -* If you wish to merge default scopes in special ways, it is recommended to define your default - scope as a class method and use the standard techniques for sharing code (inheritance, mixins, - etc.): - - class Post < ActiveRecord::Base - def self.default_scope - where(:published => true).where(:hidden => false) - end - end - - [Jon Leighton] - -* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher. - -* ConnectionManagement middleware is changed to clean up the connection pool - after the rack body has been flushed. - -* Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks. - It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of - the updated_at column. It should not be called on new records. - Example: - - User.first.update_column(:name, "sebastian") # => true - - [Sebastian Martinez] - -* Associations with a :through option can now use *any* association as the - through or source association, including other associations which have a - :through option and has_and_belongs_to_many associations - - [Jon Leighton] - -* The configuration for the current database connection is now accessible via - ActiveRecord::Base.connection_config. [fxn] - -* limits and offsets are removed from COUNT queries unless both are supplied. - For example: - - People.limit(1).count # => 'SELECT COUNT(*) FROM people' - People.offset(1).count # => 'SELECT COUNT(*) FROM people' - People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1' - - [lighthouse #6262] - -* ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class - (and subclasses) which are responsible for operating on associations, and then a separate, - thin wrapper called CollectionProxy, which proxies collection associations. - - This prevents namespace pollution, separates concerns, and will allow further refactorings. - - Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return - the associated record or nil. This means that you should not use undocumented methods such - as bob.mother.create - use bob.create_mother instead. - - [Jon Leighton] - -* Make has_many :through associations work correctly when you build a record and then save it. This - requires you to set the :inverse_of option on the source reflection on the join model, like so: - - class Post < ActiveRecord::Base - has_many :taggings - has_many :tags, :through => :taggings - end - - class Tagging < ActiveRecord::Base - belongs_to :post - belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set! - end - - class Tag < ActiveRecord::Base - has_many :taggings - has_many :posts, :through => :taggings - end - - post = Post.first - tag = post.tags.build :name => "ruby" - tag.save # will save a Taggable linking to the post - - [Jon Leighton] - -* Support the :dependent option on has_many :through associations. For historical and practical - reasons, :delete_all is the default deletion strategy employed by association.delete(*records), - despite the fact that the default strategy is :nullify for regular has_many. Also, this only - works at all if the source reflection is a belongs_to. For other situations, you should directly - modify the through association. - - [Jon Leighton] - -* Changed the behaviour of association.destroy for has_and_belongs_to_many and has_many :through. - From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', - not (necessarily) 'get rid of the associated records'. - - Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It - would not delete any records in the join table. Now, it deletes the records in the join table. - - Previously, has_many_through.destroy(*records) would destroy the records themselves, and the - records in the join table. [Note: This has not always been the case; previous version of Rails - only deleted the records themselves.] Now, it destroys only the records in the join table. - - Note that this change is backwards-incompatible to an extent, but there is unfortunately no - way to 'deprecate' it before changing it. The change is being made in order to have - consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. - - If you wish to destroy the records themselves, you can do records.association.each(&:destroy) - - [Jon Leighton] - -* Add :bulk => true option to change_table to make all the schema changes defined in change_table block using a single ALTER statement. [Pratik Naik] - - Example: - - change_table(:users, :bulk => true) do |t| - t.string :company_name - t.change :birthdate, :datetime - end - - This will now result in: - - ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL - -* Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been - documented as deprecated behaviour since April 2006. Please use has_many :through instead. - [Jon Leighton] - -* Added a create_association! method for has_one and belongs_to associations. [Jon Leighton] - -* Migration files generated from model and constructive migration generators - (for example, add_name_to_users) use the reversible migration's `change` - method instead of the ordinary `up` and `down` methods. [Prem Sichanugrist] - -* Removed support for interpolating string SQL conditions on associations. Instead, you should - use a proc, like so: - - Before: - - has_many :things, :conditions => 'foo = #{bar}' - - After: - - has_many :things, :conditions => proc { "foo = #{bar}" } - - Inside the proc, 'self' is the object which is the owner of the association, unless you are - eager loading the association, in which case 'self' is the class which the association is within. - - You can have any "normal" conditions inside the proc, so the following will work too: - - has_many :things, :conditions => proc { ["foo = ?", bar] } - - Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call - 'record' to get the record being inserted or deleted. This is now passed as an argument to - the proc. - -* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example: - - # Schema: User(name:string, password_digest:string, password_salt:string) - class User < ActiveRecord::Base - has_secure_password - end - - user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch") - user.save # => false, password required - user.password = "mUc3m00RsqyRe" - user.save # => false, confirmation doesn't match - user.password_confirmation = "mUc3m00RsqyRe" - user.save # => true - user.authenticate("notright") # => false - user.authenticate("mUc3m00RsqyRe") # => user - User.find_by_name("david").try(:authenticate, "notright") # => nil - User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user - - -* When a model is generated add_index is added by default for belongs_to or references columns - - rails g model post user:belongs_to will generate the following: - - class CreatePosts < ActiveRecord::Migration - def up - create_table :posts do |t| - t.belongs_to :user - t.timestamps - end - - add_index :posts, :user_id - end - - def down - drop_table :posts - end - end - - [Santiago Pastorino] - -* Setting the id of a belongs_to object will update the reference to the -object. [#2989 state:resolved] - -* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed -to closer match normal Ruby dup and clone semantics. - -* Calling ActiveRecord::Base#clone will result in a shallow copy of the record, -including copying the frozen state. No callbacks will be called. - -* Calling ActiveRecord::Base#dup will duplicate the record, including calling -after initialize hooks. Frozen state will not be copied, and all associations -will be cleared. A duped record will return true for new_record?, have a nil -id field, and is saveable. - -* Migrations can be defined as reversible, meaning that the migration system -will figure out how to reverse your migration. To use reversible migrations, -just define the "change" method. For example: - - class MyMigration < ActiveRecord::Migration - def change - create_table(:horses) do - t.column :content, :text - t.column :remind_at, :datetime - end - end - end - -Some things cannot be automatically reversed for you. If you know how to -reverse those things, you should define 'up' and 'down' in your migration. If -you define something in `change` that cannot be reversed, an -IrreversibleMigration exception will be raised when going down. - -* Migrations should use instance methods rather than class methods: - class FooMigration < ActiveRecord::Migration - def up - ... - end - end - - [Aaron Patterson] - -* has_one maintains the association with separate after_create/after_update instead - of a single after_save. [fxn] - -* The following code: - - Model.limit(10).scoping { Model.count } - - now generates the following SQL: - - SELECT COUNT(*) FROM models LIMIT 10 - - This may not return what you want. Instead, you may with to do something - like this: - - Model.limit(10).scoping { Model.all.size } - - [Aaron Patterson] - - -*Rails 3.0.7 (April 18, 2011)* - -* Destroying records via nested attributes works independent of reject_if LH #6006 [Durran Jordan] - -* Delegate any? and many? to Model.scoped for consistency [Andrew White] - -* Quote the ORDER BY clause in batched finds - fixes #6620 [Andrew White] - -* Change exists? so records are not instantiated - fixes #6127. This prevents after_find - and after_initialize callbacks being triggered when checking for record existence. - [Andrew White] - -* Fix performance bug with attribute accessors which only occurred on Ruby 1.8.7, and ensure we - cache type-casted values when the column returned from the db contains non-standard chars. - [Jon Leighton] - -* Fix a performance regression introduced here 86acbf1cc050c8fa8c74a10c735e467fb6fd7df8 - related to read_attribute method [Stian Grytøyr] - - -*Rails 3.0.6 (April 5, 2011)* - -* Un-deprecate reorder method [Sebastian Martinez] - -* Extensions are applied when calling +except+ or +only+ on relations. - Thanks to Iain Hecker. - -* Schemas set in set_table_name are respected by the mysql adapter. LH #5322 - -* Fixed a bug when empty? was called on a grouped Relation that wasn't loaded. - LH #5829 - -* Reapply extensions when using except and only. Thanks Iain Hecker. - -* Binary data is escaped when being inserted to SQLite3 Databases. Thanks - Naruse! - - -*Rails 3.0.5 (February 26, 2011)* - -* Model.where(:column => 1).where(:column => 2) will always produce an AND -query. - - [Aaron Patterson] - -* Deprecated support for interpolated association conditions in the form of :conditions => 'foo = #{bar}'. - - Instead, you should use a proc, like so: - - Before: - - has_many :things, :conditions => 'foo = #{bar}' - - After: - - has_many :things, :conditions => proc { "foo = #{bar}" } - - Inside the proc, 'self' is the object which is the owner of the association, unless you are - eager loading the association, in which case 'self' is the class which the association is within. - - You can have any "normal" conditions inside the proc, so the following will work too: - - has_many :things, :conditions => proc { ["foo = ?", bar] } - - Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call - 'record' to get the record being inserted or deleted. This is now passed as an argument to - the proc. - - [Jon Leighton] - - -*Rails 3.0.4 (February 8, 2011)* - -* Added deprecation warning for has_and_belongs_to_many associations where the join table has - additional attributes other than the keys. Access to these attributes is removed in 3.1. - Please use has_many :through instead. [Jon Leighton] - - -*Rails 3.0.3 (November 16, 2010)* - -* Support find by class like this: Post.where(:name => Post) - - -*Rails 3.0.2 (November 15, 2010)* - -* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) [Aaron Patterson] - -* reorder is deprecated in favor of except(:order).order(...) [Santiago Pastorino] - -* except is now AR public API - - Model.order('name').except(:order).order('salary') - - generates: - - SELECT * FROM models ORDER BY salary - - [Santiago Pastorino] - -* The following code: - - Model.limit(10).scoping { Model.count } - - now generates the following SQL: - - SELECT COUNT(*) FROM models LIMIT 10 - - This may not return what you want. Instead, you may with to do something - like this: - - Model.limit(10).scoping { Model.all.size } - - [Aaron Patterson] - - -*Rails 3.0.1 (October 15, 2010)* - -* Introduce a fix for CVE-2010-3993 - - -*Rails 3.0.0 (August 29, 2010)* - -* Changed update_attribute to not run callbacks and update the record directly in the database [Neeraj Singh] - -* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope [José Valim] - -* New rake task, db:migrate:status, displays status of migrations #4947 [Kevin Skoglund] - -* select and order for ActiveRecord now always concatenate nested calls. Use reorder if you want the original order to be overwritten [Santiago Pastorino] - -* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 [Aaron Patterson] - -* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 [Andrew Bloomgarden, Andrew White] - -* Add index length support for MySQL. #1852 [Emili Parreno, Pratik Naik] - - Example: - - add_index(:accounts, :name, :name => 'by_name', :length => 10) - => CREATE INDEX by_name ON accounts(name(10)) - - add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15}) - => CREATE INDEX by_name_surname ON accounts(name(10), surname(15)) - -* find_or_create_by_attr(value, ...) works when attr is protected. #4457 [Santiago Pastorino, Marc-André Lafortune] - -* New callbacks: after_commit and after_rollback. Do expensive operations like image thumbnailing after_commit instead of after_save. #2991 [Brian Durand] - -* Serialized attributes are not converted to YAML if they are any of the formats that can be serialized to XML (like Hash, Array and Strings). [José Valim] - -* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 [Curtis Hawthorne] - -* PostgreSQL: drop support for old postgres driver. Use pg 0.9.0 or later. [Jeremy Kemper] - -* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 [Mislav Marohnić] - -* Add Relation extensions. [Pratik Naik] - - users = User.where(:admin => true).extending(User::AdminPowers) - - latest_users = User.order('created_at DESC') do - def posts_count - Post.count(:user_id => to_a.map(&:id)) - end - end - -* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 [Andrew White] - -* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development [DHH] - -* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 [Jack Christensen] - -* Allow relations to be used as scope. - - class Item - scope :red, where(:colour => 'red') - end - - Item.red.limit(10) # Ten red items - -* Rename named_scope to scope. [Pratik Naik] - -* Changed ActiveRecord::Base.store_full_sti_class to be true by default reflecting the previously announced Rails 3 default [DHH] - -* Add Relation#except. [Pratik Naik] - - one_red_item = Item.where(:colour => 'red').limit(1) - all_items = one_red_item.except(:where, :limit) - -* Add Relation#delete_all. [Pratik Naik] - - Item.where(:colour => 'red').delete_all - -* Add Model.having and Relation#having. [Pratik Naik] - - Developer.group("salary").having("sum(salary) > 10000").select("salary") - -* Add Relation#count. [Pratik Naik] - - legends = People.where("age > 100") - legends.count - legends.count(:age, :distinct => true) - legends.select('id').count - -* Add Model.readonly and association_collection#readonly finder method. [Pratik Naik] - - Post.readonly.to_a # Load all posts in readonly mode - @user.items.readonly(false).to_a # Load all the user items in writable mode - -* Add .lock finder method [Pratik Naik] - - User.lock.where(:name => 'lifo').to_a - - old_items = Item.where("age > 100") - old_items.lock.each {|i| .. } - -* Add Model.from and association_collection#from finder methods [Pratik Naik] - - user = User.scoped - user.select('*').from('users, items') - -* Add relation.destroy_all [Pratik Naik] - - old_items = Item.where("age > 100") - old_items.destroy_all - -* Add relation.exists? [Pratik Naik] - - red_items = Item.where(:colours => 'red') - red_items.exists? - red_items.exists?(1) - -* Add find(ids) to relations. [Pratik Naik] - - old_users = User.order("age DESC") - old_users.find(1) - old_users.find(1, 2, 3) - -* Add new finder methods to association collection. [Pratik Naik] - - class User < ActiveRecord::Base - has_many :items - end - - user = User.first - user.items.where(:items => {:colour => 'red'}) - user.items.select('items.id') - -* Add relation.reload to force reloading the records. [Pratik Naik] - - topics = Topic.scoped - topics.to_a # force load - topics.first # returns a cached record - topics.reload - topics.first # Fetches a new record from the database - -* Rename Model.conditions and relation.conditions to .where. [Pratik Naik] - - Before : - User.conditions(:name => 'lifo') - User.select('id').conditions(["age > ?", 21]) - - Now : - User.where(:name => 'lifo') - User.select('id').where(["age > ?", 21]) - -* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. [Pratik Naik] - - Examples : - - posts = Post.select('id).order('name') # Returns a lazy relation - posts.each {|p| puts p.id } # Fires "select id from posts order by name" - -* Model.scoped now returns a relation if invoked without any arguments. [Pratik Naik] - - Example : - - posts = Post.scoped - posts.size # Fires "select count(*) from posts" and returns the count - posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects - -* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 [Murray Steele] - - # post.comments sets each comment's post without needing to :include - class Post < ActiveRecord::Base - has_many :comments, :inverse_of => :post - end - -* MySQL: add_ and change_column support positioning. #3286 [Ben Marini] - -* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 [Mike Breen, Gabe da Silveira] - -* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git [Pratik Naik] - -* PostgreSQL: XML datatype support. #1874 [Leonardo Borges] - -* quoted_date converts time-like objects to ActiveRecord::Base.default_timezone before serialization. This allows you to use Time.now in find conditions and have it correctly be serialized as the current time in UTC when default_timezone == :utc. #2946 [Geoff Buesing] - -* SQLite: drop support for 'dbfile' option in favor of 'database.' #2363 [Paul Hinze, Jeremy Kemper] - -* Added :primary_key option to belongs_to associations. #765 [Szymon Nowak, Philip Hallstrom, Noel Rocha] - # employees.company_name references companies.name - Employee.belongs_to :company, :primary_key => 'name', :foreign_key => 'company_name' - -* Implement #many? for NamedScope and AssociationCollection using #size. #1500 [Chris Kampmeier] - -* Added :touch option to belongs_to associations that will touch the parent record when the current record is saved or destroyed [DHH] - -* Added ActiveRecord::Base#touch to update the updated_at/on attributes (or another specified timestamp) with the current time [DHH] - - -*2.3.2 [Final] (March 15, 2009)* - -* Added ActiveRecord::Base.find_each and ActiveRecord::Base.find_in_batches for batch processing [DHH/Jamis Buck] - -* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 [Scott Taylor] - -* Add Support for updating deeply nested models from a single form. #1202 [Eloy Duran] - - class Book < ActiveRecord::Base - has_one :author - has_many :pages - - accepts_nested_attributes_for :author, :pages - end - -* Make after_save callbacks fire only if the record was successfully saved. #1735 [Michael Lovitt] - - Previously the callbacks would fire if a before_save cancelled saving. - -* Support nested transactions using database savepoints. #383 [Jonathan Viney, Hongli Lai] - -* Added dynamic scopes ala dynamic finders #1648 [Yaroslav Markin] - -* Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 [Yaroslav Markin] - -* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 [Akira Matsuda] - -* Add :having as a key to find and the relevant associations. [Emilio Tagua] - -* Added default_scope to Base #1381 [Paweł Kondzior]. Example: - - class Person < ActiveRecord::Base - default_scope :order => 'last_name, first_name' - end - - class Company < ActiveRecord::Base - has_many :people - end - - Person.all # => Person.find(:all, :order => 'last_name, first_name') - Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 }) - - -*2.2.1 [RC2] (November 14th, 2008)* - -* Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster] - -* Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 [Andreas Korth] - - -*2.2.0 [RC1] (October 24th, 2008)* - -* Skip collection ids reader optimization if using :finder_sql [Jeremy Kemper] - -* Add Model#delete instance method, similar to Model.delete class method. #1086 [Hongli Lai (Phusion)] - -* MySQL: cope with quirky default values for not-null text columns. #1043 [Frederick Cheung] - -* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] [Geoff Buesing] - -* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] [Emilio Tagua] - -* Added find_last_by dynamic finder #762 [Emilio Tagua] - -* Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 [Hongli Lai (Phusion)] - -* Changed benchmarks to be reported in milliseconds [David Heinemeier Hansson] - -* Connection pooling. #936 [Nick Sieger] - -* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 [Andrew White] - -* before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 [Xavier Noria] - -* Transactional migrations for databases which support them. #834 [divoxx, Adam Wiggins, Tarmo Tänav] - -* Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp. #446. [Andrew Stone, Nik Wakelin] - -* change_column_default preserves the not-null constraint. #617 [Tarmo Tänav] - -* Fixed that create database statements would always include "DEFAULT NULL" (Nick Sieger) [#334] - -* Add :tokenizer option to validates_length_of to specify how to split up the attribute string. #507. [David Lowenfels] Example : - - # Ensure essay contains at least 100 words. - validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) } - -* Allow conditions on multiple tables to be specified using hash. [Pratik Naik]. Example: - - User.all :joins => :items, :conditions => { :age => 10, :items => { :color => 'black' } } - Item.first :conditions => { :items => { :color => 'red' } } - -* Always treat integer :limit as byte length. #420 [Tarmo Tänav] - -* Partial updates don't update lock_version if nothing changed. #426 [Daniel Morrison] - -* Fix column collision with named_scope and :joins. #46 [Duncan Beevers, Mark Catley] - -* db:migrate:down and :up update schema_migrations. #369 [Michael Raidel, RaceCondition] - -* PostgreSQL: support :conditions => [':foo::integer', { :foo => 1 }] without treating the ::integer typecast as a bind variable. [Tarmo Tänav] - -* MySQL: rename_column preserves column defaults. #466 [Diego Algorta] - -* Add :from option to calculations. #397 [Ben Munat] - -* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. [Jan De Poorter] - -* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. [Jeremy Kemper] - -* Added SQL escaping for :limit and :offset in MySQL [Jonathan Wiess] - - -*2.1.0 (May 31st, 2008)* - -* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. [Rick Olson] - -* Add first/last methods to associations/named_scope. Resolved #226. [Ryan Bates] - -* Added SQL escaping for :limit and :offset #288 [Aaron Bedra, Steven Bristol, Jonathan Wiess] - -* Added first/last methods to associations/named_scope. Resolved #226. [Ryan Bates] - -* Ensure hm:t preloading honours reflection options. Resolves #137. [Frederick Cheung] - -* Added protection against duplicate migration names (Aslak Hellesøy) [#112] - -* Base#instantiate_time_object: eliminate check for Time.zone, since we can assume this is set if time_zone_aware_attributes is set to true [Geoff Buesing] - -* Time zone aware attribute methods use Time.zone.parse instead of #to_time for String arguments, so that offset information in String is respected. Resolves #105. [Scott Fleckenstein, Geoff Buesing] - -* Added change_table for migrations (Jeff Dean) [#71]. Example: - - change_table :videos do |t| - t.timestamps # adds created_at, updated_at - t.belongs_to :goat # adds goat_id integer - t.string :name, :email, :limit => 20 # adds name and email both with a 20 char limit - t.remove :name, :email # removes the name and email columns - end - -* Fixed has_many :through .create with no parameters caused a "can't dup NilClass" error (Steven Soroka) [#85] - -* Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) [#39] - -* Fixed that pessimistic locking you reference the quoted table name (Josh Susser) [#67] - -* Fixed that change_column should be able to use :null => true on a field that formerly had false [Nate Wiger] [#26] - -* Added that the MySQL adapter should map integer to either smallint, int, or bigint depending on the :limit just like PostgreSQL [David Heinemeier Hansson] - -* Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. [Rick Olson] - -* Add support for interleaving migrations by storing which migrations have run in the new schema_migrations table. Closes #11493 [Jordi Bunster] - -* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 [Kamal Fariz Mahyuddin] - -* Ensure that respond_to? considers dynamic finder methods. Closes #11538. [James Mead] - -* Ensure that save on parent object fails for invalid has_one association. Closes #10518. [Pratik Naik] - -* Remove duplicate code from associations. [Pratik Naik] - -* Refactor HasManyThroughAssociation to inherit from HasManyAssociation. Association callbacks and <association>_ids= now work with hm:t. #11516 [Ruy Asan] - -* Ensure HABTM#create and HABTM#build do not load entire association. [Pratik Naik] - -* Improve documentation. [Xavier Noria, Jack Danger Canty, leethal] - -* Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} [Rick Olson] - - Post.find(1).to_json # => {"title": ...} - config.active_record.include_root_in_json = true - Post.find(1).to_json # => {"post": {"title": ...}} - -* Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). [stopdropandrew] - -* PostgreSQL: create_ and drop_database support. #9042 [ez, pedz, Nick Sieger] - -* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. [Nik Wakelin, cavalle] - -* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. [Jeremy Kemper] - -* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled [Geoff Buesing] - -* Fixed that validates_size_of :within works in associations #11295, #10019 [cavalle] - -* Track changes to unsaved attributes. [Jeremy Kemper] - -* Switched to UTC-timebased version numbers for migrations and the schema. This will as good as eliminate the problem of multiple migrations getting the same version assigned in different branches. Also added rake db:migrate:up/down to apply individual migrations that may need to be run when you merge branches #11458 [John Barnette] - -* Fixed that has_many :through would ignore the hash conditions #11447 [Emilio Tagua] - -* Fix issue where the :uniq option of a has_many :through association is ignored when find(:all) is called. Closes #9407 [cavalle] - -* Fix duplicate table alias error when including an association with a has_many :through association on the same join table. Closes #7310 [cavalle] - -* More efficient association preloading code that compacts a through_records array in a central location. Closes #11427 [Jack Danger Canty] - -* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert] - -* Fixed that ActiveRecord#Base.find_or_create/initialize would not honor attr_protected/accessible when used with a hash #11422 [Emilio Tagua] - -* Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:last) #11413 [nkallen, Chris O'Sullivan] - -* Merge the has_finder gem, renamed as 'named_scope'. #11404 [nkallen] - - class Article < ActiveRecord::Base - named_scope :published, :conditions => {:published => true} - named_scope :popular, :conditions => ... - end - - Article.published.paginate(:page => 1) - Article.published.popular.count - Article.popular.find(:first) - Article.popular.find(:all, :conditions => {...}) - - See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries - -* Add has_one :through support. #4756 [Chris O'Sullivan] - -* Migrations: create_table supports primary_key_prefix_type. #10314 [student, Chris O'Sullivan] - -* Added logging for dependency load errors with fixtures #11056 [stuthulhu] - -* Time zone aware attributes use Time#in_time_zone [Geoff Buesing] - -* Fixed that scoped joins would not always be respected #6821 [Theory/Jack Danger Canty] - -* Ensure that ActiveRecord::Calculations disambiguates field names with the table name. #11027 [cavalle] - -* Added add/remove_timestamps to the schema statements for adding the created_at/updated_at columns on existing tables #11129 [jramirez] - -* Added ActiveRecord::Base.find(:last) #11338 [Emilio Tagua] - -* test_native_types expects DateTime.local_offset instead of DateTime.now.offset; fixes test breakage due to dst transition [Geoff Buesing] - -* Add :readonly option to HasManyThrough associations. #11156 [Emilio Tagua] - -* Improve performance on :include/:conditions/:limit queries by selectively joining in the pre-query. #9560 [dasil003] - -* Perf fix: Avoid the use of named block arguments. Closes #11109 [adymo] - -* PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg driver. #11127 [jdavis] - -* Ensure association preloading doesn't break when an association returns nil. ##11145 [GMFlash] - -* Make dynamic finders respect the :include on HasManyThrough associations. #10998. [cpytel] - -* Base#instantiate_time_object only uses Time.zone when Base.time_zone_aware_attributes is true; leverages Time#time_with_datetime_fallback for readability [Geoff Buesing] - -* Refactor ConnectionAdapters::Column.new_time: leverage DateTime failover behavior of Time#time_with_datetime_fallback [Geoff Buesing] - -* Improve associations performance by using symbol callbacks instead of string callbacks. #11108 [adymo] - -* Optimise the BigDecimal conversion code. #11110 [adymo] - -* Introduce the :readonly option to all associations. Records from the association cannot be saved. #11084 [Emilio Tagua] - -* Multiparameter attributes for time columns fail over to DateTime when out of range of Time [Geoff Buesing] - -* Base#instantiate_time_object uses Time.zone.local() [Geoff Buesing] - -* Add timezone-aware attribute readers and writers. #10982 [Geoff Buesing] - -* Instantiating time objects in multiparameter attributes uses Time.zone if available. #10982 [Rick Olson] - -* Add note about how ActiveRecord::Observer classes are initialized in a Rails app. #10980 [Xavier Noria] - -* MySQL: omit text/blob defaults from the schema instead of using an empty string. #10963 [mdeiters] - -* belongs_to supports :dependent => :destroy and :delete. #10592 [Jonathan Viney] - -* Introduce preload query strategy for eager :includes. #9640 [Frederick Cheung, Aliaksey Kandratsenka, codafoo] - -* Support aggregations in finder conditions. #10572 [Ryan Kinderman] - -* Organize and clean up the Active Record test suite. #10742 [John Barnette] - -* Ensure that modifying has_and_belongs_to_many actions clear the query cache. Closes #10840 [john.andrews] - -* Fix issue where Table#references doesn't pass a :null option to a *_type attribute for polymorphic associations. Closes #10753 [railsjitsu] - -* Fixtures: removed support for the ancient pre-YAML file format. #10736 [John Barnette] - -* More thoroughly quote table names. #10698 [dimdenis, lotswholetime, Jeremy Kemper] - -* update_all ignores scoped :order and :limit, so post.comments.update_all doesn't try to include the comment order in the update statement. #10686 [Brendan Ribera] - -* Added ActiveRecord::Base.cache_key to make it easier to cache Active Records in combination with the new ActiveSupport::Cache::* libraries [David Heinemeier Hansson] - -* Make sure CSV fixtures are compatible with ruby 1.9's new csv implementation. [JEG2] - -* Added by parameter to increment, decrement, and their bang varieties so you can do player1.increment!(:points, 5) #10542 [Sam] - -* Optimize ActiveRecord::Base#exists? to use #select_all instead of #find. Closes #10605 [jamesh, Frederick Cheung, protocool] - -* Don't unnecessarily load has_many associations in after_update callbacks. Closes #6822 [stopdropandrew, canadaduane] - -* Eager belongs_to :include infers the foreign key from the association name rather than the class name. #10517 [Jonathan Viney] - -* SQLite: fix rename_ and remove_column for columns with unique indexes. #10576 [Brandon Keepers] - -* Ruby 1.9 compatibility. #10655 [Jeremy Kemper, Dirkjan Bussink] - - -*2.0.2* (December 16th, 2007) - -* Ensure optimistic locking handles nil #lock_version values properly. Closes #10510 [Rick Olson] - -* Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases. Closes #10379 [brynary] - -* Fix that validates_acceptance_of still works for non-existent tables (useful for bootstrapping new databases). Closes #10474 [Josh Susser] - -* Ensure that the :uniq option for has_many :through associations retains the order. #10463 [remvee] - -* Base.exists? doesn't rescue exceptions to avoid hiding SQL errors. #10458 [Michael Klishin] - -* Documentation: Active Record exceptions, destroy_all and delete_all. #10444, #10447 [Michael Klishin] - - -*2.0.1* (December 7th, 2007) - -* Removed query cache rescue as it could cause code to be run twice (closes #10408) [David Heinemeier Hansson] - - -*2.0.0* (December 6th, 2007) - -* Anchor DateTimeTest to fixed DateTime instead of a variable value based on Time.now#advance#to_datetime, so that this test passes on 64-bit platforms running Ruby 1.8.6+ [Geoff Buesing] - -* Fixed that the Query Cache should just be ignored if the database is misconfigured (so that the "About your applications environment" works even before the database has been created) [David Heinemeier Hansson] - -* Fixed that the truncation of strings longer than 50 chars should use inspect -so newlines etc are escaped #10385 [Norbert Crombach] - -* Fixed that habtm associations should be able to set :select as part of their definition and have that honored [David Heinemeier Hansson] - -* Document how the :include option can be used in Calculations::calculate. Closes #7446 [adamwiggins, ultimoamore] - -* Fix typo in documentation for polymorphic associations w/STI. Closes #7461 [johnjosephbachir] - -* Reveal that the type option in migrations can be any supported column type for your database but also include caveat about agnosticism. Closes #7531 [adamwiggins, mikong] - -* More complete documentation for find_by_sql. Closes #7912 [fearoffish] - -* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [David Heinemeier Hansson]. Example: - - render :partial => @client.becomes(Company) # renders companies/company instead of clients/client - -* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 [Cheah Chu Yeow] - -* Fix documentation typo introduced in [8250]. Closes #10339 [Henrik N] - -* Foxy fixtures: support single-table inheritance. #10234 [tom] - -* Foxy fixtures: allow mixed usage to make migration easier and more attractive. #10004 [lotswholetime] - -* Make the record_timestamps class-inheritable so it can be set per model. #10004 [tmacedo] - -* Allow validates_acceptance_of to use a real attribute instead of only virtual (so you can record that the acceptance occured) #7457 [ambethia] - -* DateTimes use Ruby's default calendar reform setting. #10201 [Geoff Buesing] - -* Dynamic finders on association collections respect association :order and :limit. #10211, #10227 [Patrick Joyce, Rick Olson, Jack Danger Canty] - -* Add 'foxy' support for fixtures of polymorphic associations. #10183 [John Barnette, David Lowenfels] - -* validates_inclusion_of and validates_exclusion_of allow formatted :message strings. #8132 [devrieda, Mike Naberezny] - -* attr_readonly behaves well with optimistic locking. #10188 [Nick Bugajski] - -* Base#to_xml supports the nil="true" attribute like Hash#to_xml. #8268 [Jonathan del Strother] - -* Change plings to the more conventional quotes in the documentation. Closes #10104 [Jack Danger Canty] - -* Fix HasManyThrough Association so it uses :conditions on the HasMany Association. Closes #9729 [Jack Danger Canty] - -* Ensure that column names are quoted. Closes #10134 [wesley.moxam] - -* Smattering of grammatical fixes to documentation. Closes #10083 [Bob Silva] - -* Enhance explanation with more examples for attr_accessible macro. Closes #8095 [fearoffish, Marcel Molina Jr.] - -* Update association/method mapping table to refected latest collection methods for has_many :through. Closes #8772 [Pratik Naik] - -* Explain semantics of having several different AR instances in a transaction block. Closes #9036 [jacobat, Marcel Molina Jr.] - -* Update Schema documentation to use updated sexy migration notation. Closes #10086 [Sam Granieri] - -* Make fixtures work with the new test subclasses. [Tarmo Tänav, Michael Koziarski] - -* Introduce finder :joins with associations. Same :include syntax but with inner rather than outer joins. #10012 [RubyRedRick] - # Find users with an avatar - User.find(:all, :joins => :avatar) - - # Find posts with a high-rated comment. - Post.find(:all, :joins => :comments, :conditions => 'comments.rating > 3') - -* Associations: speedup duplicate record check. #10011 [Pratik Naik] - -* Make sure that << works on has_many associations on unsaved records. Closes #9989 [Josh Susser] - -* Allow association redefinition in subclasses. #9346 [wildchild] - -* Fix has_many :through delete with custom foreign keys. #6466 [naffis] - -* Foxy fixtures, from rathole (http://svn.geeksomnia.com/rathole/trunk/README) - - stable, autogenerated IDs - - specify associations (belongs_to, has_one, has_many) by label, not ID - - specify HABTM associations as inline lists - - autofill timestamp columns - - support YAML defaults - - fixture label interpolation - Enabled for fixtures that correspond to a model class and don't specify a primary key value. #9981 [John Barnette] - -* Add docs explaining how to protect all attributes using attr_accessible with no arguments. Closes #9631 [boone, rmm5t] - -* Update add_index documentation to use new options api. Closes #9787 [Kamal Fariz Mahyuddin] - -* Allow find on a has_many association defined with :finder_sql to accept id arguments as strings like regular find does. Closes #9916 [krishna] - -* Use VALID_FIND_OPTIONS when resolving :find scoping rather than hard coding the list of valid find options. Closes #9443 [sur] - -* Limited eager loading no longer ignores scoped :order. Closes #9561 [Jack Danger Canty, Josh Peek] - -* Assigning an instance of a foreign class to a composed_of aggregate calls an optional conversion block. Refactor and simplify composed_of implementation. #6322 [brandon, Chris Cruft] - -* Assigning nil to a composed_of aggregate also sets its immediate value to nil. #9843 [Chris Cruft] - -* Ensure that mysql quotes table names with database names correctly. Closes #9911 [crayz] - - "foo.bar" => "`foo`.`bar`" - -* Complete the assimilation of Sexy Migrations from ErrFree [Chris Wanstrath, PJ Hyett] - http://errtheblog.com/post/2381 - -* Qualified column names work in hash conditions, like :conditions => { 'comments.created_at' => ... }. #9733 [Jack Danger Canty] - -* Fix regression where the association would not construct new finder SQL on save causing bogus queries for "WHERE owner_id = NULL" even after owner was saved. #8713 [Bryan Helmkamp] - -* Refactor association create and build so before & after callbacks behave consistently. #8854 [Pratik Naik, mortent] - -* Quote table names. Defaults to column quoting. #4593 [Justin Lynn, gwcoffey, eadz, Dmitry V. Sabanin, Jeremy Kemper] - -* Alias association #build to #new so it behaves predictably. #8787 [Pratik Naik] - -* Add notes to documentation regarding attr_readonly behavior with counter caches and polymorphic associations. Closes #9835 [saimonmoore, Rick Olson] - -* Observers can observe model names as symbols properly now. Closes #9869 [queso] - -* find_and_(initialize|create)_by methods can now properly initialize protected attributes [Tobias Lütke] - -* belongs_to infers the foreign key from the association name instead of from the class name. [Jeremy Kemper] - -* PostgreSQL: support multiline default values. #7533 [Carl Lerche, aguynamedryan, Rein Henrichs, Tarmo Tänav] - -* MySQL: fix change_column on not-null columns that don't accept dfeault values of ''. #6663 [Jonathan Viney, Tarmo Tänav] - -* validates_uniqueness_of behaves well with abstract superclasses and -single-table inheritance. #3833, #9886 [Gabriel Gironda, rramdas, François Beausoleil, Josh Peek, Tarmo Tänav, pat] - -* Warn about protected attribute assigments in development and test environments when mass-assigning to an attr_protected attribute. #9802 [Henrik N] - -* Speedup database date/time parsing. [Jeremy Kemper, Tarmo Tänav] - -* Fix calling .clear on a has_many :dependent=>:delete_all association. [Tarmo Tänav] - -* Allow change_column to set NOT NULL in the PostgreSQL adapter [Tarmo Tänav] - -* Fix that ActiveRecord would create attribute methods and override custom attribute getters if the method is also defined in Kernel.methods. [Rick Olson] - -* Don't call attr_readonly on polymorphic belongs_to associations, in case it matches the name of some other non-ActiveRecord class/module. [Rick Olson] - -* Try loading activerecord-<adaptername>-adapter gem before trying a plain require so you can use custom gems for the bundled adapters. Also stops gems from requiring an adapter from an old Active Record gem. [Jeremy Kemper, Derrick Spell] - - -*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.14.2 - 1.15.3] - -* Add attr_readonly to specify columns that are skipped during a normal ActiveRecord #save operation. Closes #6896 [Dan Manges] - - class Comment < ActiveRecord::Base - # Automatically sets Article#comments_count as readonly. - belongs_to :article, :counter_cache => :comments_count - end - - class Article < ActiveRecord::Base - attr_readonly :approved_comments_count - end - -* Make size for has_many :through use counter cache if it exists. Closes #9734 [Xavier Shay] - -* Remove DB2 adapter since IBM chooses to maintain their own adapter instead. [Jeremy Kemper] - -* Extract Oracle, SQLServer, and Sybase adapters into gems. [Jeremy Kemper] - -* Added fixture caching that'll speed up a normal fixture-powered test suite between 50% and 100% #9682 [Frederick Cheung] - -* Correctly quote id list for limited eager loading. #7482 [tmacedo] - -* Fixed that using version-targetted migrates would fail on loggers other than the default one #7430 [valeksenko] - -* Fixed rename_column for SQLite when using symbols for the column names #8616 [drodriguez] - -* Added the possibility of using symbols in addition to concrete classes with ActiveRecord::Observer#observe. #3998 [Robby Russell, Tarmo Tänav] - -* Added ActiveRecord::Base#to_json/from_json [David Heinemeier Hansson, Cheah Chu Yeow] - -* Added ActiveRecord::Base#from_xml [David Heinemeier Hansson]. Example: - - xml = "<person><name>David</name></person>" - Person.new.from_xml(xml).name # => "David" - -* Define dynamic finders as real methods after first usage. [bscofield] - -* Deprecation: remove deprecated threaded_connections methods. Use allow_concurrency instead. [Jeremy Kemper] - -* Associations macros accept extension blocks alongside modules. #9346 [Josh Peek] - -* Speed up and simplify query caching. [Jeremy Kemper] - -* connection.select_rows 'sql' returns an array (rows) of arrays (field values). #2329 [Michael Schuerig] - -* Eager loading respects explicit :joins. #9496 [dasil003] - -* Extract Firebird, FrontBase, and OpenBase adapters into gems. #9508, #9509, #9510 [Jeremy Kemper] - -* RubyGem database adapters: expects a gem named activerecord-<database>-adapter with active_record/connection_adapters/<database>_adapter.rb in its load path. [Jeremy Kemper] - -* Fixed that altering join tables in migrations would fail w/ sqlite3 #7453 [TimoMihaljov/brandon] - -* Fix association writer with :dependent => :nullify. #7314 [Jonathan Viney] - -* OpenBase: update for new lib and latest Rails. Support migrations. #8748 [dcsesq] - -* Moved acts_as_tree into a plugin of the same name on the official Rails svn. #9514 [Pratik Naik] - -* Moved acts_as_nested_set into a plugin of the same name on the official Rails svn. #9516 [Josh Peek] - -* Moved acts_as_list into a plugin of the same name on the official Rails svn. [Josh Peek] - -* Explicitly require active_record/query_cache before using it. [Jeremy Kemper] - -* Fix bug where unserializing an attribute attempts to modify a frozen @attributes hash for a deleted record. [Rick Olson, marclove] - -* Performance: absorb instantiate and initialize_with_callbacks into the Base methods. [Jeremy Kemper] - -* Fixed that eager loading queries and with_scope should respect the :group option [David Heinemeier Hansson] - -* Improve performance and functionality of the postgresql adapter. Closes #8049 [roderickvd] - - For more information see: http://dev.rubyonrails.org/ticket/8049 - -* Don't clobber includes passed to has_many.count [Jack Danger Canty] - -* Make sure has_many uses :include when counting [Jack Danger Canty] - -* Change the implementation of ActiveRecord's attribute reader and writer methods [Michael Koziarski] - - Generate Reader and Writer methods which cache attribute values in hashes. This is to avoid repeatedly parsing the same date or integer columns. - - Change exception raised when users use find with :select then try to access a skipped column. Plugins could override missing_attribute() to lazily load the columns. - - Move method definition to the class, instead of the instance - - Always generate the readers, writers and predicate methods. - -* Perform a deep #dup on query cache results so that modifying activerecord attributes does not modify the cached attributes. [Rick Olson] - -# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [Pratik Naik] - -* Added :unless clause to validations #8003 [monki]. Example: - - def using_open_id? - !identity_url.blank? - end - - validates_presence_of :identity_url, :if => using_open_id? - validates_presence_of :username, :unless => using_open_id? - validates_presence_of :password, :unless => using_open_id? - -* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 [Pratik Naik] - -* Fix and properly document/test count(column_name) usage. Closes #8999 [Pratik Naik] - -* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 [Pratik Naik] - -* Change belongs_to so that the foreign_key assumption is taken from the association name, not the class name. Closes #8992 [Josh Susser] - - OLD - belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is user_id - - NEW - belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is visitor_id - -* Remove spurious tests from deprecated_associations_test, most of these aren't deprecated, and are duplicated in associations_test. Closes #8987 [Pratik Naik] - -* Make create! on a has_many :through association return the association object. Not the collection. Closes #8786 [Pratik Naik] - -* Move from select * to select tablename.* to avoid clobbering IDs. Closes #8889 [dasil003] - -* Don't call unsupported methods on associated objects when using :include, :method with to_xml #7307, [Manfred Stienstra, jwilger] - -* Define collection singular ids method for has_many :through associations. #8763 [Pratik Naik] - -* Array attribute conditions work with proxied association collections. #8318 [Kamal Fariz Mahyuddin, theamazingrando] - -* Fix polymorphic has_one associations declared in an abstract class. #8638 [Pratik Naik, Dax Huiberts] - -* Fixed validates_associated should not stop on the first error. #4276 [mrj, Manfred Stienstra, Josh Peek] - -* Rollback if commit raises an exception. #8642 [kik, Jeremy Kemper] - -* Update tests' use of fixtures for the new collections api. #8726 [Kamal Fariz Mahyuddin] - -* Save associated records only if the association is already loaded. #8713 [Blaine] - -* MySQL: fix show_variable. #8448 [matt, Jeremy Kemper] - -* Fixtures: correctly delete and insert fixtures in a single transaction. #8553 [Michael Schuerig] - -* Fixtures: people(:technomancy, :josh) returns both fixtures. #7880 [technomancy, Josh Peek] - -* Calculations support non-numeric foreign keys. #8154 [Kamal Fariz Mahyuddin] - -* with_scope is protected. #8524 [Josh Peek] - -* Quickref for association methods. #7723 [marclove, Mindsweeper] - -* Calculations: return nil average instead of 0 when there are no rows to average. #8298 [davidw] - -* acts_as_nested_set: direct_children is sorted correctly. #4761 [Josh Peek, rails@33lc0.net] - -* Raise an exception if both attr_protected and attr_accessible are declared. #8507 [stellsmi] - -* SQLite, MySQL, PostgreSQL, Oracle: quote column names in column migration SQL statements. #8466 [marclove, lorenjohnson] - -* Allow nil serialized attributes with a set class constraint. #7293 [sandofsky] - -* Oracle: support binary fixtures. #7987 [Michael Schoen] - -* Fixtures: pull fixture insertion into the database adapters. #7987 [Michael Schoen] - -* Announce migration versions as they're performed. [Jeremy Kemper] - -* find gracefully copes with blank :conditions. #7599 [Dan Manges, johnnyb] - -* validates_numericality_of takes :greater_than, :greater_than_or_equal_to, :equal_to, :less_than, :less_than_or_equal_to, :odd, and :even options. #3952 [Bob Silva, Dan Kubb, Josh Peek] - -* MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. #8448 [matt] - -* Find with a list of ids supports limit/offset. #8437 [hrudududu] - -* Optimistic locking: revert the lock version when an update fails. #7840 [plang] - -* Migrations: add_column supports custom column types. #7742 [jsgarvin, Theory] - -* Load database adapters on demand. Eliminates config.connection_adapters and RAILS_CONNECTION_ADAPTERS. Add your lib directory to the $LOAD_PATH and put your custom adapter in lib/active_record/connection_adapters/adaptername_adapter.rb. This way you can provide custom adapters as plugins or gems without modifying Rails. [Jeremy Kemper] - -* Ensure that associations with :dependent => :delete_all respect :conditions option. Closes #8034 [Jack Danger Canty, Josh Peek, Rick Olson] - -* belongs_to assignment creates a new proxy rather than modifying its target in-place. #8412 [mmangino@elevatedrails.com] - -* Fix column type detection while loading fixtures. Closes #7987 [roderickvd] - -* Document deep eager includes. #6267 [Josh Susser, Dan Manges] - -* Document warning that associations names shouldn't be reserved words. #4378 [murphy@cYcnus.de, Josh Susser] - -* Sanitize Base#inspect. #8392, #8623 [Nik Wakelin, jnoon] - -* Replace the transaction {|transaction|..} semantics with a new Exception ActiveRecord::Rollback. [Michael Koziarski] - -* Oracle: extract column length for CHAR also. #7866 [ymendel] - -* Document :allow_nil option for validates_acceptance_of since it defaults to true. [tzaharia] - -* Update documentation for :dependent declaration so that it explicitly uses the non-deprecated API. [Jack Danger Canty] - -* Add documentation caveat about when to use count_by_sql. [fearoffish] - -* Enhance documentation for increment_counter and decrement_counter. [fearoffish] - -* Provide brief introduction to what optimistic locking is. [fearoffish] - -* Add documentation for :encoding option to mysql adapter. [marclove] - -* Added short-hand declaration style to migrations (inspiration from Sexy Migrations, http://errtheblog.com/post/2381) [David Heinemeier Hansson]. Example: - - create_table "products" do |t| - t.column "shop_id", :integer - t.column "creator_id", :integer - t.column "name", :string, :default => "Untitled" - t.column "value", :string, :default => "Untitled" - t.column "created_at", :datetime - t.column "updated_at", :datetime - end - - ...can now be written as: - - create_table :products do |t| - t.integer :shop_id, :creator_id - t.string :name, :value, :default => "Untitled" - t.timestamps - end - -* Use association name for the wrapper element when using .to_xml. Previous behavior lead to non-deterministic situations with STI and polymorphic associations. [Michael Koziarski, jstrachan] - -* Improve performance of calling .create on has_many :through associations. [evan] - -* Improved cloning performance by relying less on exception raising #8159 [Blaine] - -* Added ActiveRecord::Base.inspect to return a column-view like #<Post id:integer, title:string, body:text> [David Heinemeier Hansson] - -* Added yielding of Builder instance for ActiveRecord::Base#to_xml calls [David Heinemeier Hansson] - -* Small additions and fixes for ActiveRecord documentation. Closes #7342 [Jeremy McAnally] - -* Add helpful debugging info to the ActiveRecord::StatementInvalid exception in ActiveRecord::ConnectionAdapters::SqliteAdapter#table_structure. Closes #7925. [court3nay] - -* SQLite: binary escaping works with $KCODE='u'. #7862 [tsuka] - -* Base#to_xml supports serialized attributes. #7502 [jonathan] - -* Base.update_all :order and :limit options. Useful for MySQL updates that must be ordered to avoid violating unique constraints. [Jeremy Kemper] - -* Remove deprecated object transactions. People relying on this functionality should install the object_transactions plugin at http://code.bitsweat.net/svn/object_transactions. Closes #5637 [Michael Koziarski, Jeremy Kemper] - -* PostgreSQL: remove DateTime -> Time downcast. Warning: do not enable translate_results for the C bindings if you have timestamps outside Time's domain. [Jeremy Kemper] - -* find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. For example, Person.find_or_create_by_name(:name => 'Henry', :comments => 'Hi new user!') is equivalent to Person.find_by_name('Henry') || Person.create(:name => 'Henry', :comments => 'Hi new user!'). #7368 [Josh Susser] - -* Make sure with_scope takes both :select and :joins into account when setting :readonly. Allows you to save records you retrieve using method_missing on a has_many :through associations. [Michael Koziarski] - -* Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool] - -* Consistent public/protected/private visibility for chained methods. #7813 [Dan Manges] - -* Oracle: fix quoted primary keys and datetime overflow. #7798 [Michael Schoen] - -* Consistently quote primary key column names. #7763 [toolmantim] - -* Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley] - -* DateTimes assume the default timezone. #7764 [Geoff Buesing] - -* Sybase: hide timestamp columns since they're inherently read-only. #7716 [Mike Joyce] - -* Oracle: overflow Time to DateTime. #7718 [Michael Schoen] - -* PostgreSQL: don't use async_exec and async_query with postgres-pr. #7727, #7762 [flowdelic, toolmantim] - -* Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins] - -* Test DateTime native type in migrations, including an edge case with dates -during calendar reform. #7649, #7724 [fedot, Geoff Buesing] - -* SQLServer: correctly schema-dump tables with no indexes or descending indexes. #7333, #7703 [Jakob Skjerning, Tom Ward] - -* SQLServer: recognize real column type as Ruby float. #7057 [sethladd, Tom Ward] - -* Added fixtures :all as a way of loading all fixtures in the fixture directory at once #7214 [Manfred Stienstra] - -* Added database connection as a yield parameter to ActiveRecord::Base.transaction so you can manually rollback [David Heinemeier Hansson]. Example: - - transaction do |transaction| - david.withdrawal(100) - mary.deposit(100) - transaction.rollback! # rolls back the transaction that was otherwise going to be successful - end - -* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method [Jamis Buck] - -* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however [Tobias Lütke] - Task.cache { Task.find(1); Task.find(1) } # => 1 query - -* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. [Jamis Buck] - -* Oracle: fix lob and text default handling. #7344 [gfriedrich, Michael Schoen] - -* SQLServer: don't choke on strings containing 'null'. #7083 [Jakob Skjerning] - -* MySQL: blob and text columns may not have defaults in 5.x. Update fixtures schema for strict mode. #6695 [Dan Kubb] - -* update_all can take a Hash argument. sanitize_sql splits into two methods for conditions and assignment since NULL values and delimiters are handled differently. #6583, #7365 [sandofsky, Assaf] - -* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 [Jonathan Viney, timc] - -* Use Date#to_s(:db) for quoted dates. #7411 [Michael Schoen] - -* Don't create instance writer methods for class attributes. Closes #7401 [Rick Olson] - -* Docs: validations examples. #7343 [zackchandler] - -* Add missing tests ensuring callbacks work with class inheritance. Closes #7339 [sandofsky] - -* Fixtures use the table name and connection from set_fixture_class. #7330 [Anthony Eden] - -* Remove useless code in #attribute_present? since 0 != blank?. Closes #7249 [Josh Susser] - -* Fix minor doc typos. Closes #7157 [Josh Susser] - -* Fix incorrect usage of #classify when creating the eager loading join statement. Closes #7044 [Josh Susser] - -* SQLServer: quote table name in indexes query. #2928 [keithm@infused.org] - -* Subclasses of an abstract class work with single-table inheritance. #5704, #7284 [BertG, nick+rails@ag.arizona.edu] - -* Make sure sqlite3 driver closes open connections on disconnect [Rob Rasmussen] - -* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 [Jeremy McAnally] - -* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 [Dan Manges, Jeremy Kemper] - -* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 [Jonathan Viney, Manfred Stienstra, altano@bigfoot.com] - -* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 [Michael Schoen] - -* MySQL: retain SSL settings on reconnect. #6976 [randyv2] - -* Apply scoping during initialize instead of create. Fixes setting of foreign key when using find_or_initialize_by with scoping. [Cody Fauser] - -* SQLServer: handle [quoted] table names. #6635 [rrich] - -* acts_as_nested_set works with single-table inheritance. #6030 [Josh Susser] - -* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 [eventualbuddha, Michael Schoen] - -* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 [Dan Manges] - Student.find(:all, :conditions => { :grade => 9..12 }) - -* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 [mschoen, tdfowler] - -* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 [Robby Russell] - -* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 [Caio Chassot] - -* Bring the sybase adapter up to scratch for 1.2 release. [jsheets] - -* Rollback new_record? and id when an exception is raised in a save callback. #6910 [Ben Curren, outerim] - -* Pushing a record on an association collection doesn't unnecessarily load all the associated records. [Obie Fernandez, Jeremy Kemper] - -* Oracle: fix connection reset failure. #6846 [leonlleslie] - -* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 [leei, Jeremy Kemper] - -* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 [protocool] - -* Consolidated different create and create! versions to call through to the base class with scope. This fixes inconsistencies, especially related to protected attribtues. Closes #5847 [Alexander Dymo, Tobias Lütke] - -* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 [vitaly, Jeremy Kemper] - -* Add AssociationCollection#create! to be consistent with AssociationCollection#create when dealing with a foreign key that is a protected attribute [Cody Fauser] - -* Added counter optimization for AssociationCollection#any? so person.friends.any? won't actually load the full association if we have the count in a cheaper form [David Heinemeier Hansson] - -* Change fixture_path to a class inheritable accessor allowing test cases to have their own custom set of fixtures. #6672 [Zach Dennis] - -* Quote ActiveSupport::Multibyte::Chars. #6653 [Julian Tarkhanov] - -* Simplify query_attribute by typecasting the attribute value and checking whether it's nil, false, zero or blank. #6659 [Jonathan Viney] - -* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 [Andreas Schwarz] - -* Run validations in the order they were declared. #6657 [obrie] - -* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 [simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper] - -* Simplify association proxy implementation by factoring construct_scope out of method_missing. #6643 [martin] - -* Oracle: automatically detect the primary key. #6594 [vesaria, Michael Schoen] - -* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 [philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen] - -* Don't inspect unloaded associations. #2905 [lmarlow] - -* SQLite: use AUTOINCREMENT primary key in >= 3.1.0. #6588, #6616 [careo, lukfugl] - -* Cache inheritance_column. #6592 [Stefan Kaes] - -* Firebird: decimal/numeric support. #6408 [macrnic] - -* make add_order a tad faster. #6567 [Stefan Kaes] - -* Find with :include respects scoped :order. #5850 - -* Support nil and Array in :conditions => { attr => value } hashes. #6548 [Assaf, Jeremy Kemper] - find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } - -* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 [Si] - -* SQLite: fix calculations workaround, remove count(distinct) query rewrite, cleanup test connection scripts. [Jeremy Kemper] - -* SQLite: count(distinct) queries supported in >= 3.2.6. #6544 [Bob Silva] - -* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes] - -* Deprecation: object transactions warning. [Jeremy Kemper] - -* has_one :dependent => :nullify ignores nil associates. #4848, #6528 [bellis@deepthought.org, janovetz, Jeremy Kemper] - -* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 [Michael Schoen] - -* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 [obrie] - -* Document other options available to migration's add_column. #6419 [grg] - -* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 [Jeremy Kemper] - -* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. [Jonathan Viney] - -* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters [Rick Olson] - -* Restore eager condition interpolation, document it's differences [Rick Olson] - -* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 [Jacob Fugal, Jeremy Kemper] - -* Add #delete support to has_many :through associations. Closes #6049 [Martin Landers] - -* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 [Rick Olson] - -* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 [turnip@turnipspatch.com] - -* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 [wreese@gmail.com] - -* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 [jonathan] - -* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 [Bob Silva] - -* The has_many create method works with polymorphic associations. #6361 [Dan Peterson] - -* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 [Stefan Kaes] - -* save! shouldn't validate twice. #6324 [maiha, Bob Silva] - -* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 [Michael Schuerig] - -* Add an attribute reader method for ActiveRecord::Base.observers [Rick Olson] - -* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 [Bob Silva] - -* has_one associations with a nil target may be safely marshaled. #6279 [norbauer, Jeremy Kemper] - -* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects [Michael Koziarski] - -* Add a :namespace option to AR::Base#to_xml [Michael Koziarski] - -* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. [Jeremy Kemper] - -* Mock Time.now for more accurate Touch mixin tests. #6213 [Dan Peterson] - -* Improve yaml fixtures error reporting. #6205 [Bruce Williams] - -* Rename AR::Base#quote so people can use that name in their models. #3628 [Michael Koziarski] - -* Add deprecation warning for inferred foreign key. #6029 [Josh Susser] - -* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 [jimw@mysql.com] - -* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 [Josh Susser] - -* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 [Bob Silva] - -* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 [Tom Ward] - -* to_xml: the :methods option works on arrays of records. #5845 [Josh Starcher] - -* Deprecation: update docs. #5998 [Jakob Skjerning, Kevin Clark] - -* Add some XmlSerialization tests for ActiveRecord [Rick Olson] - -* has_many :through conditions are sanitized by the associating class. #5971 [martin.emde@gmail.com] - -* Tighten rescue clauses. #5985 [james@grayproductions.net] - -* Fix spurious newlines and spaces in AR::Base#to_xml output [Jamis Buck] - -* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 [Chris Mear, Jonathan Viney] - -* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 [Jonathan Viney] - -* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 [Tom Ward, kruth@bfpi] - -* SQLServer: fix eager association test. #5901 [Tom Ward] - -* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 [Kevin Clark] - -* Fixtures: correct escaping of \n and \r. #5859 [evgeny.zislis@gmail.com] - -* Migrations: gracefully handle missing migration files. #5857 [eli.gordon@gmail.com] - -* MySQL: update test schema for MySQL 5 strict mode. #5861 [Tom Ward] - -* to_xml: correct naming of included associations. #5831 [Josh Starcher] - -* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 [Josh Susser] - -* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. [Jeremy Kemper] - - # Create a tagging to associate the post and tag. - post.tags << Tag.find_by_name('old') - post.tags.create! :name => 'general' - - # Would have been: - post.taggings.create!(:tag => Tag.find_by_name('finally') - transaction do - post.taggings.create!(:tag => Tag.create!(:name => 'general')) - end - -* Cache nil results for :included has_one associations also. #5787 [Michael Schoen] - -* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Lütke] - -* Nested classes are given table names prefixed by the singular form of the parent's table name. [Jeremy Kemper] - Example: Invoice::Lineitem is given table name invoice_lineitems - -* Migrations: uniquely name multicolumn indexes so you don't have to. [Jeremy Kemper] - # people_active_last_name_index, people_active_deactivated_at_index - add_index :people, [:active, :last_name] - add_index :people, [:active, :deactivated_at] - remove_index :people, [:active, :last_name] - remove_index :people, [:active, :deactivated_at] - - WARNING: backward-incompatibility. Multicolumn indexes created before this - revision were named using the first column name only. Now they're uniquely - named using all indexed columns. - - To remove an old multicolumn index, remove_index :table_name, :first_column - -* Fix for deep includes on the same association. [richcollins@gmail.com] - -* Tweak fixtures so they don't try to use a non-ActiveRecord class. [Kevin Clark] - -* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson] - -* Document find's :from option. Closes #5762. [andrew@redlinesoftware.com] - -* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 [guy.naor@famundo.com] - -* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar] - -* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. [Michael Schoen] - -* Add documentation for how to disable timestamps on a per model basis. Closes #5684. [matt@mattmargolis.net Marcel Molina Jr.] - -* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney] - -* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson] - -* Formally deprecate the deprecated finders. [Michael Koziarski] - -* Formally deprecate rich associations. [Michael Koziarski] - -* Fixed that default timezones for new / initialize should uphold utc setting #5709 [daniluk@yahoo.com] - -* Fix announcement of very long migration names. #5722 [blake@near-time.com] - -* The exists? class method should treat a string argument as an id rather than as conditions. #5698 [jeremy@planetargon.com] - -* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com] - -* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: - - assert (Topic.exists?(:author_name => "David")) - assert (Topic.exists?(:author_name => "Mary", :approved => true)) - assert (Topic.exists?(["parent_id = ?", 1])) - -* Schema dumper quotes date :default values. [Dave Thomas] - -* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson] - -* Factor the attribute#{suffix} methods out of method_missing for easier extension. [Jeremy Kemper] - -* Patch sql injection vulnerability when using integer or float columns. [Jamis Buck] - -* Allow #count through a has_many association to accept :include. [Dan Peterson] - -* create_table rdoc: suggest :id => false for habtm join tables. [Zed Shaw] - -* PostgreSQL: return array fields as strings. #4664 [Robby Russell] - -* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 [Tom Ward] - -* SQLServer: fix db:schema:dump case-sensitivity. #4684 [Will Rogers] - -* Oracle: BigDecimal support. #5667 [Michael Schoen] - -* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 [robbat2@gentoo.org, work@ashleymoran.me.uk] - -* Firebird migrations support. #5337 [Ken Kunz <kennethkunz@gmail.com>] - -* PostgreSQL: create/drop as postgres user. #4790 [mail@matthewpainter.co.uk, mlaster@metavillage.com] - -* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>] - -* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 [tietew@tietew.net] - -* PostgreSQL: correctly quote microseconds in timestamps. #5641 [rick@rickbradley.com] - -* Clearer has_one/belongs_to model names (account has_one :user). #5632 [matt@mattmargolis.net] - -* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 [Michael Schoen] - -* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 [Michael Schoen] - -* Added :group to available options for finds done on associations #5516 [mike@michaeldewey.org] - -* Minor tweak to improve performance of ActiveRecord::Base#to_param. - -* Observers also watch subclasses created after they are declared. #5535 [daniels@pronto.com.au] - -* Removed deprecated timestamps_gmt class methods. [Jeremy Kemper] - -* rake build_mysql_database grants permissions to rails@localhost. #5501 [brianegge@yahoo.com] - -* PostgreSQL: support microsecond time resolution. #5492 [alex@msgpad.com] - -* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. - -* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. [Sam Stephenson] - -* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). [Shugo Maeda] - # Obtain an exclusive lock on person 1 so we can safely increment visits. - Person.transaction do - # select * from people where id=1 for update - person = Person.find(1, :lock => true) - person.visits += 1 - person.save! - end - -* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. [Jeremy Kemper] - -* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. [Jeremy Kemper] - -* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. [Nicholas Seckar] - -* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) - -* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization [David Heinemeier Hansson] - -* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: - - Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) - -...is the same as: - - Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) - - This makes it easier to pass in the options from a form or otherwise outside. - - -* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 [kennethkunz@gmail.com] - -* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 [alex@purefiction.net] - -* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 [greg@lapcominc.com] - -* Fixed problems with eager loading and counting on SQL Server #5212 [kajism@yahoo.com] - -* Fixed that count distinct should use the selected column even when using :include #5251 [anna@wota.jp] - -* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 [alex@purefiction.net] - -* Allow models to override to_xml. #4989 [Blair Zajac <blair@orcaware.com>] - -* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 [shimbo@is.naist.jp] - -* Records and arrays of records are bound as quoted ids. [Jeremy Kemper] - Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) - Foo.find(:first, :conditions => ['bar_id = ?', bar]) - -* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty [David Heinemeier Hansson] - -* Add a list of regexes assert_queries skips in the ActiveRecord test suite. [Rick Olson] - -* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 [Josh Susser] - -* Provide Association Extensions access to the instance that the association is being accessed from. - Closes #4433 [Josh Susser] - -* Update OpenBase adaterp's maintainer's email address. Closes #5176. [Derrick Spell] - -* Add a quick note about :select and eagerly included associations. [Rick Olson] - -* Add docs for the :as option in has_one associations. Closes #5144 [cdcarter@gmail.com] - -* Fixed that has_many collections shouldn't load the entire association to do build or create [David Heinemeier Hansson] - -* Added :allow_nil option for aggregations #5091 [Ian White] - -* Fix Oracle boolean support and tests. Closes #5139. [Michael Schoen] - -* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) [Jeremy Kemper] - -* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 [info@loobmedia.com] - -* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. [pdcawley@bofh.org.uk] - -* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 [keegan@thebasement.org] - -* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 [kajism@yahoo.com] - -* Allow :uniq => true with has_many :through associations. [Jeremy Kemper] - -* Ensure that StringIO is always available for the Schema dumper. [Marcel Molina Jr.] - -* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com] - -* Replace superfluous name_to_class_name variant with camelize. [Marcel Molina Jr.] - -* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.] - -* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.] - -* Remove duplicate fixture entry in comments.yml. Closes #4923. [Blair Zajac <blair@orcaware.com>] - -* Update FrontBase adapter to check binding version. Closes #4920. [mlaster@metavillage.com] - -* New Frontbase connections don't start in auto-commit mode. Closes #4922. [mlaster@metavillage.com] - -* When grouping, use the appropriate option key. [Marcel Molina Jr.] - -* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. [Marcel Molina Jr.] - -* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. [mlaster@metavillage.com] - -* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. [Francois Beausoleil <francois.beausoleil@gmail.com>] - -* Fix syntax error in documentation. Closes #4679. [Mislav Marohnić] - -* Add Oracle support for CLOB inserts. Closes #4748. [schoenm@earthlink.net sandra.metz@duke.edu] - -* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. [kajism@yahoo.com] - -* Add support for :order option to with_scope. Closes #3887. [eric.daspet@survol.net] - -* Prettify output of schema_dumper by making things line up. Closes #4241 [Caio Chassot <caio@v2studio.com>] - -* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. [mlaster@metavillage.com] - -* Sybase Adapter type conversion cleanup. Closes #4736. [dev@metacasa.net] - -* Fix bug where calculations with long alias names return null. [Rick Olson] - -* Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick Olson] - - @post.tags << @tag # BAD - @post.taggings.create(:tag => @tag) # GOOD - -* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick Olson] - -* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com] - -* Add ActiveRecord::Errors#to_xml [Jamis Buck] - -* Properly quote index names in migrations (closes #4764) [John Long] - -* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. [Rick Olson] - -* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson] - -* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson] - -* DRY up association collection reader method generation. [Marcel Molina Jr.] - -* DRY up and tweak style of the validation error object. [Marcel Molina Jr.] - -* Add :case_sensitive option to validates_uniqueness_of (closes #3090) [Rick Olson] - - class Account < ActiveRecord::Base - validates_uniqueness_of :email, :case_sensitive => false - end - -* Allow multiple association extensions with :extend option (closes #4666) [Josh Susser] - - class Account < ActiveRecord::Base - has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] - end - - *1.15.3* (March 12th, 2007) - - * Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool] - - * Consistently quote primary key column names. #7763 [toolmantim] - - * Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley] - - * Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins] - - -*1.15.2* (February 5th, 2007) - -* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 [Dan Manges] - Student.find(:all, :conditions => { :grade => 9..12 }) - -* Don't create instance writer methods for class attributes. [Rick Olson] - -* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. [Jamis Buck] - -* SQLServer: don't choke on strings containing 'null'. #7083 [Jakob Skjerning] - -* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 [Si] - -* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 [Jonathan Viney, timc] - -* Fixtures use the table name and connection from set_fixture_class. #7330 [Anthony Eden] - -* SQLServer: quote table name in indexes query. #2928 [keithm@infused.org] - - -*1.15.1* (January 17th, 2007) - -* Fix nodoc breaking of adapters - - -*1.15.0* (January 16th, 2007) - -* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 [Jeremy McAnally] - -* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 [Dan Manges, Jeremy Kemper] - -* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 [Jonathan Viney, Manfred Stienstra, altano@bigfoot.com] - -* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 [Michael Schoen] - -* MySQL: retain SSL settings on reconnect. #6976 [randyv2] - -* SQLServer: handle [quoted] table names. #6635 [rrich] - -* acts_as_nested_set works with single-table inheritance. #6030 [Josh Susser] - -* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 [eventualbuddha, Michael Schoen] - -* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 [mschoen, tdfowler] - -* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 [Robby Russell] - -* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 [Caio Chassot] - -* Bring the sybase adapter up to scratch for 1.2 release. [jsheets] - -* Oracle: fix connection reset failure. #6846 [leonlleslie] - -* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 [leei, Jeremy Kemper] - -* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 [protocool] - -* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 [vitaly, Jeremy Kemper] - -* Support nil and Array in :conditions => { attr => value } hashes. #6548 [Assaf, Jeremy Kemper] - find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } - -* Quote ActiveSupport::Multibyte::Chars. #6653 [Julian Tarkhanov] - -* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 [simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper] - -* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 [Andreas Schwarz] - -* Oracle: automatically detect the primary key. #6594 [vesaria, Michael Schoen] - -* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 [philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen] - -* Firebird: decimal/numeric support. #6408 [macrnic] - -* Find with :include respects scoped :order. #5850 - -* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes] - -* Deprecation: object transactions warning. [Jeremy Kemper] - -* has_one :dependent => :nullify ignores nil associates. #6528 [janovetz, Jeremy Kemper] - -* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 [Michael Schoen] - -* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 [obrie] - -* Document other options available to migration's add_column. #6419 [grg] - -* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 [Jeremy Kemper] - -* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. [Jonathan Viney] - -* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters [Rick Olson] - -* Restore eager condition interpolation, document it's differences [Rick Olson] - -* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 [Jacob Fugal, Jeremy Kemper] - -* Add #delete support to has_many :through associations. Closes #6049 [Martin Landers] - -* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 [Rick Olson] - -* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 [turnip@turnipspatch.com] - -* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 [wreese@gmail.com] - -* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 [jonathan] - -* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 [Bob Silva] - -* The has_many create method works with polymorphic associations. #6361 [Dan Peterson] - -* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 [Stefan Kaes] - -* save! shouldn't validate twice. #6324 [maiha, Bob Silva] - -* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 [Michael Schuerig] - -* Add an attribute reader method for ActiveRecord::Base.observers [Rick Olson] - -* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 [Bob Silva] - -* has_one associations with a nil target may be safely marshaled. #6279 [norbauer, Jeremy Kemper] - -* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects [Michael Koziarski] - -* Add a :namespace option to AR::Base#to_xml [Michael Koziarski] - -* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. [Jeremy Kemper] - -* Mock Time.now for more accurate Touch mixin tests. #6213 [Dan Peterson] - -* Improve yaml fixtures error reporting. #6205 [Bruce Williams] - -* Rename AR::Base#quote so people can use that name in their models. #3628 [Michael Koziarski] - -* Add deprecation warning for inferred foreign key. #6029 [Josh Susser] - -* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 [jimw@mysql.com] - -* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 [Josh Susser] - -* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 [Tom Ward] - -* to_xml: the :methods option works on arrays of records. #5845 [Josh Starcher] - -* has_many :through conditions are sanitized by the associating class. #5971 [martin.emde@gmail.com] - -* Fix spurious newlines and spaces in AR::Base#to_xml output [Jamis Buck] - -* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 [Chris Mear, Jonathan Viney] - -* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 [Jonathan Viney] - -* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 [Tom Ward, kruth@bfpi] - -* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 [Kevin Clark] - -* Fixtures: correct escaping of \n and \r. #5859 [evgeny.zislis@gmail.com] - -* Migrations: gracefully handle missing migration files. #5857 [eli.gordon@gmail.com] - -* MySQL: update test schema for MySQL 5 strict mode. #5861 [Tom Ward] - -* to_xml: correct naming of included associations. #5831 [Josh Starcher] - -* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 [Josh Susser] - -* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. [Jeremy Kemper] - - # Create a tagging to associate the post and tag. - post.tags << Tag.find_by_name('old') - post.tags.create! :name => 'general' - - # Would have been: - post.taggings.create!(:tag => Tag.find_by_name('finally') - transaction do - post.taggings.create!(:tag => Tag.create!(:name => 'general')) - end - -* Cache nil results for :included has_one associations also. #5787 [Michael Schoen] - -* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Lütke] - -* Nested classes are given table names prefixed by the singular form of the parent's table name. [Jeremy Kemper] - Example: Invoice::Lineitem is given table name invoice_lineitems - -* Migrations: uniquely name multicolumn indexes so you don't have to. [Jeremy Kemper] - # people_active_last_name_index, people_active_deactivated_at_index - add_index :people, [:active, :last_name] - add_index :people, [:active, :deactivated_at] - remove_index :people, [:active, :last_name] - remove_index :people, [:active, :deactivated_at] - - WARNING: backward-incompatibility. Multicolumn indexes created before this - revision were named using the first column name only. Now they're uniquely - named using all indexed columns. - - To remove an old multicolumn index, remove_index :table_name, :first_column - -* Fix for deep includes on the same association. [richcollins@gmail.com] - -* Tweak fixtures so they don't try to use a non-ActiveRecord class. [Kevin Clark] - -* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson] - -* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 [guy.naor@famundo.com] - -* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar] - -* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. [Michael Schoen] - -* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney] - -* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson] - -* Formally deprecate the deprecated finders. [Michael Koziarski] - -* Formally deprecate rich associations. [Michael Koziarski] - -* Fixed that default timezones for new / initialize should uphold utc setting #5709 [daniluk@yahoo.com] - -* Fix announcement of very long migration names. #5722 [blake@near-time.com] - -* The exists? class method should treat a string argument as an id rather than as conditions. #5698 [jeremy@planetargon.com] - -* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com] - -* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: - - assert (Topic.exists?(:author_name => "David")) - assert (Topic.exists?(:author_name => "Mary", :approved => true)) - assert (Topic.exists?(["parent_id = ?", 1])) - -* Schema dumper quotes date :default values. [Dave Thomas] - -* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson] - -* Factor the attribute#{suffix} methods out of method_missing for easier extension. [Jeremy Kemper] - -* Patch sql injection vulnerability when using integer or float columns. [Jamis Buck] - -* Allow #count through a has_many association to accept :include. [Dan Peterson] - -* create_table rdoc: suggest :id => false for habtm join tables. [Zed Shaw] - -* PostgreSQL: return array fields as strings. #4664 [Robby Russell] - -* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 [Tom Ward] - -* SQLServer: fix db:schema:dump case-sensitivity. #4684 [Will Rogers] - -* Oracle: BigDecimal support. #5667 [Michael Schoen] - -* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 [robbat2@gentoo.org, work@ashleymoran.me.uk] - -* Firebird migrations support. #5337 [Ken Kunz <kennethkunz@gmail.com>] - -* PostgreSQL: create/drop as postgres user. #4790 [mail@matthewpainter.co.uk, mlaster@metavillage.com] - -* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 [tietew@tietew.net] - -* PostgreSQL: correctly quote microseconds in timestamps. #5641 [rick@rickbradley.com] - -* Clearer has_one/belongs_to model names (account has_one :user). #5632 [matt@mattmargolis.net] - -* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 [Michael Schoen] - -* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 [Michael Schoen] - -* Added :group to available options for finds done on associations #5516 [mike@michaeldewey.org] - -* Observers also watch subclasses created after they are declared. #5535 [daniels@pronto.com.au] - -* Removed deprecated timestamps_gmt class methods. [Jeremy Kemper] - -* rake build_mysql_database grants permissions to rails@localhost. #5501 [brianegge@yahoo.com] - -* PostgreSQL: support microsecond time resolution. #5492 [alex@msgpad.com] - -* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. - -* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. [Sam Stephenson] - -* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). [Shugo Maeda] - # Obtain an exclusive lock on person 1 so we can safely increment visits. - Person.transaction do - # select * from people where id=1 for update - person = Person.find(1, :lock => true) - person.visits += 1 - person.save! - end - -* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. [Jeremy Kemper] - -* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. [Jeremy Kemper] - -* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. [Nicholas Seckar] - -* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) - -* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization [David Heinemeier Hansson] - -* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: - - Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) - -...is the same as: - - Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) - - This makes it easier to pass in the options from a form or otherwise outside. - - -* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 [kennethkunz@gmail.com] - -* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 [alex@purefiction.net] - -* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 [greg@lapcominc.com] - -* Fixed problems with eager loading and counting on SQL Server #5212 [kajism@yahoo.com] - -* Fixed that count distinct should use the selected column even when using :include #5251 [anna@wota.jp] - -* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 [alex@purefiction.net] - -* Allow models to override to_xml. #4989 [Blair Zajac <blair@orcaware.com>] - -* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 [shimbo@is.naist.jp] - -* Records and arrays of records are bound as quoted ids. [Jeremy Kemper] - Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) - Foo.find(:first, :conditions => ['bar_id = ?', bar]) - -* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty [David Heinemeier Hansson] - -* Add a list of regexes assert_queries skips in the ActiveRecord test suite. [Rick Olson] - -* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 [Josh Susser] - -* Provide Association Extensions access to the instance that the association is being accessed from. - Closes #4433 [Josh Susser] - -* Update OpenBase adaterp's maintainer's email address. Closes #5176. [Derrick Spell] - -* Add a quick note about :select and eagerly included associations. [Rick Olson] - -* Add docs for the :as option in has_one associations. Closes #5144 [cdcarter@gmail.com] - -* Fixed that has_many collections shouldn't load the entire association to do build or create [David Heinemeier Hansson] - -* Added :allow_nil option for aggregations #5091 [Ian White] - -* Fix Oracle boolean support and tests. Closes #5139. [Michael Schoen] - -* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) [Jeremy Kemper] - -* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 [info@loobmedia.com] - -* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. [pdcawley@bofh.org.uk] - -* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 [keegan@thebasement.org] - -* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 [kajism@yahoo.com] - -* Allow :uniq => true with has_many :through associations. [Jeremy Kemper] - -* Ensure that StringIO is always available for the Schema dumper. [Marcel Molina Jr.] - -* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com] - -* Remove duplicate fixture entry in comments.yml. Closes #4923. [Blair Zajac <blair@orcaware.com>] - -* When grouping, use the appropriate option key. [Marcel Molina Jr.] - -* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. [mlaster@metavillage.com] - -* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. [Francois Beausoleil <francois.beausoleil@gmail.com>] - -* Fix syntax error in documentation. Closes #4679. [Mislav Marohnić] - -* Add Oracle support for CLOB inserts. Closes #4748. [schoenm@earthlink.net sandra.metz@duke.edu] - -* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. [kajism@yahoo.com] - -* Add support for :order option to with_scope. Closes #3887. [eric.daspet@survol.net] - -* Prettify output of schema_dumper by making things line up. Closes #4241 [Caio Chassot <caio@v2studio.com>] - -* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. [mlaster@metavillage.com] - -* Sybase Adapter type conversion cleanup. Closes #4736. [dev@metacasa.net] - -* Fix bug where calculations with long alias names return null. [Rick Olson] - -* Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick Olson] - - @post.tags << @tag # BAD - @post.taggings.create(:tag => @tag) # GOOD - -* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick Olson] - -* Add ActiveRecord::Errors#to_xml [Jamis Buck] - -* Properly quote index names in migrations (closes #4764) [John Long] - -* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. [Rick Olson] - -* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson] - -* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson] - -* Add :case_sensitive option to validates_uniqueness_of (closes #3090) [Rick Olson] - - class Account < ActiveRecord::Base - validates_uniqueness_of :email, :case_sensitive => false - end - -* Allow multiple association extensions with :extend option (closes #4666) [Josh Susser] - - class Account < ActiveRecord::Base - has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] - end - - -*1.14.4* (August 8th, 2006) - -* Add warning about the proper way to validate the presence of a foreign key. #4147 [Francois Beausoleil <francois.beausoleil@gmail.com>] - -* Fix syntax error in documentation. #4679 [Mislav Marohnić] - -* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com] - - -*1.14.3* (June 27th, 2006) - -* Fix announcement of very long migration names. #5722 [blake@near-time.com] - -* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>] - -* Properly quote index names in migrations (closes #4764) [John Long] - -* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson] - -* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson] - - -*1.14.2* (April 9th, 2006) - -* Fixed calculations for the Oracle Adapter (closes #4626) [Michael Schoen] - - -*1.14.1* (April 6th, 2006) - -* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. [Nicholas Seckar] - -* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) [Lars Pind] - -* Enable Limit/Offset in Calculations (closes #4558) [lmarlow] - -* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) [Rick Olson] - -* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 [lagroue@free.fr] - -* Allow AR::Base#respond_to? to behave when @attributes is nil [Ryan Davis] - -* Support eager includes when going through a polymorphic has_many association. [Rick Olson] - -* Added support for eagerly including polymorphic has_one associations. (closes #4525) [Rick Olson] - - class Post < ActiveRecord::Base - has_one :tagging, :as => :taggable - end - - Post.find :all, :include => :tagging - -* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many [Rick Olson] - -* Added support for going through a polymorphic has_many association: (closes #4401) [Rick Olson] - - class PhotoCollection < ActiveRecord::Base - has_many :photos, :as => :photographic - belongs_to :firm - end - - class Firm < ActiveRecord::Base - has_many :photo_collections - has_many :photos, :through => :photo_collections - end - -* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. [ruben.nine@gmail.com] - -* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. [Florian Weber] - -* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) [Stefan] - -* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) [Rick Olson] - -* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model [David Heinemeier Hansson] - -* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) [David Heinemeier Hansson] - -* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). [Marcel Mollina Jr.] - -* Fixed broken OCIAdapter #4457 [Michael Schoen] - - -*1.14.0* (March 27th, 2006) - -* Replace 'rescue Object' with a finer grained rescue. Closes #4431. [Nicholas Seckar] - -* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table [Rick Olson] - -* Add support for :include to with_scope [andrew@redlinesoftware.com] - -* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 [Michael Schoen] - -* Change periods (.) in table aliases to _'s. Closes #4251 [jeff@ministrycentered.com] - -* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 [Rick Olson] - -* Fixed issue that kept :select options from being scoped [Rick Olson] - -* Fixed db_schema_import when binary types are present #3101 [David Heinemeier Hansson] - -* Fixed that MySQL enums should always be returned as strings #3501 [David Heinemeier Hansson] - -* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. [Rick Olson] - - class Connection < ActiveRecord::Base - belongs_to :user - belongs_to :channel - end - - class Channel < ActiveRecord::Base - has_many :connections - has_many :contacts, :through => :connections, :class_name => 'User' # OLD - has_many :contacts, :through => :connections, :source => :user # NEW - end - -* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 [contact@maik-schmidt.de] - -* Allow overriding of find parameters in scoped has_many :through calls [Rick Olson] - - In this example, :include => false disables the default eager association from loading. :select changes the standard - select clause. :joins specifies a join that is added to the end of the has_many :through query. - - class Post < ActiveRecord::Base - has_many :tags, :through => :taggings, :include => :tagging do - def add_joins_and_select - find :all, :select => 'tags.*, authors.id as author_id', :include => false, - :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' - end - end - end - -* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson] - -* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney] - -* Quit ignoring default :include options in has_many :through calls [Mark James] - -* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) [Jonathan Viney] - -* Eager Loading support added for has_many :through => :has_many associations (see below). [Rick Olson] - -* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: - - class Firm < ActiveRecord::Base - has_many :clients - has_many :invoices, :through => :clients - end - - class Client < ActiveRecord::Base - belongs_to :firm - has_many :invoices - end - - class Invoice < ActiveRecord::Base - belongs_to :client - end - -* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) [Josh Susser] - -* Fixed has_many :through to include :conditions set on the :through association. closes #4020 [Jonathan Viney] - -* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) [andylien@gmail.com / Rick Olson] - -* SQL Server adapter gets some love #4298 [Ryan Tomayko] - -* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 [derrickspell@cdmplus.com] - -* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): - - Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') - -* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. [Rick Olson] - -* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 [Michael Koziarski] - -* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 [Michael Koziarski] - -* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 [Tom Ward] - -* Fixed that Migration#execute would have the table name prefix appended to its query #4110 [mark.imbriaco@pobox.com] - -* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) [Jamis Buck] - -* Use association's :conditions when eager loading. [Jeremy Evans] #4144 - -* Alias the has_and_belongs_to_many join table on eager includes. #4106 [Jeremy Evans] - - This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. - - Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') - -* Oracle adapter gets some love #4230 [Michael Schoen] - - * Changes :text to CLOB rather than BLOB [Moses Hohman] - * Fixes an issue with nil numeric length/scales (several) - * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] - * Tweaks a unit test to get it all green again - * Adds support for #current_database - -* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 [Rick Olson] - - class CachedModel < ActiveRecord::Base - self.abstract_class = true - end - - class Post < CachedModel - end - - CachedModel.abstract_class? - => true - - Post.abstract_class? - => false - - Post.base_class - => Post - - Post.table_name - => 'posts' - -* Allow :dependent options to be used with polymorphic joins. #3820 [Rick Olson] - - class Foo < ActiveRecord::Base - has_many :attachments, :as => :attachable, :dependent => :delete_all - end - -* Nicer error message on has_many :through when :through reflection can not be found. #4042 [court3nay] - -* Upgrade to Transaction::Simple 1.3 [Jamis Buck] - -* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model [Rick Olson] - -* Allow ordering of calculated results and/or grouped fields in calculations [solo@gatelys.com] - -* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 [johan@johansorensen.com] - -* Dynamically set allow_concurrency. #4044 [Stefan Kaes] - -* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: - - topic.to_xml - - ...returns: - - <?xml version="1.0" encoding="UTF-8"?> - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <id type="integer">1</id> - <approved type="boolean">false</approved> - <replies-count type="integer">0</replies-count> - <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> - <written-on type="datetime">2003-07-16 09:28:00</written-on> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - ...and you can configure with: - - topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) - - ...that'll return: - - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <approved type="boolean">false</approved> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - You can even do load first-level associations as part of the document: - - firm.to_xml :include => [ :account, :clients ] - - ...that'll return something like: - - <?xml version="1.0" encoding="UTF-8"?> - <firm> - <id type="integer">1</id> - <rating type="integer">1</rating> - <name>37signals</name> - <clients> - <client> - <rating type="integer">1</rating> - <name>Summit</name> - </client> - <client> - <rating type="integer">1</rating> - <name>Microsoft</name> - </client> - </clients> - <account> - <id type="integer">1</id> - <credit-limit type="integer">50</credit-limit> - </account> - </firm> - -* Allow :counter_cache to take a column name for custom counter cache columns [Jamis Buck] - -* Documentation fixes for :dependent [robby@planetargon.com] - -* Stop the MySQL adapter crashing when views are present. #3782 [Jonathan Viney] - -* Don't classify the belongs_to class, it is already singular #4117 [keithm@infused.org] - -* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. [Rick Olson] - -* Fix quoting of inheritance column for STI eager loading #4098 [Jonathan Viney <jonathan@bluewire.net.nz>] - -* Added smarter table aliasing for eager associations for multiple self joins #3580 [Rick Olson] - - * The first time a table is referenced in a join, no alias is used. - * After that, the parent class name and the reflection name are used. - - Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... - - * Any additional join references get a numerical suffix like '_2', '_3', etc. - -* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. - -* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: - - # cascaded in two levels - >> Author.find(:all, :include=>{:posts=>:comments}) - => authors - +- posts - +- comments - - # cascaded in two levels and normal association - >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in two levels with two has_many associations - >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in three levels - >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) - => companies - +- groups - +- members - +- favorites - -* Make counter cache work when replacing an association #3245 [eugenol@gmail.com] - -* Make migrations verbose [Jamis Buck] - -* Make counter_cache work with polymorphic belongs_to [Jamis Buck] - -* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 [anna@wota.jp] - -* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: - - * Does not support DATE SQL column types; use DATETIME instead. - * Date columns on HABTM join tables are returned as String, not Time. - * Insertions are potentially broken for :polymorphic join tables - * BLOB column access not yet fully supported - -* Clear stale, cached connections left behind by defunct threads. [Jeremy Kemper] - -* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. [Jeremy Kemper] - -* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 [Michael Schoen] - -* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 [David Heinemeier Hansson] - -* Speed up class -> connection caching and stale connection verification. #3979 [Stefan Kaes] - -* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. [Kevin Clark] - -* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 [dblack@wobblini.net] - -* Define attribute query methods to avoid method_missing calls. #3677 [Jonathan Viney] - -* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 [Simon Stapleton, Tom Ward] - -* Added support for nested scopes #3407 [anna@wota.jp]. Examples: - - Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 - - # inner rule is used. (all previous parameters are ignored) - Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') - end - - # parameters are merged - Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 - end - end - -* Fixed db2 connection with empty user_name and auth options #3622 [phurley@gmail.com] - -* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 [Masao Mutoh] - -* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 [Lars Pind] - -* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: - - Person.average :age - Person.minimum :age - Person.maximum :age - Person.sum :salary, :group => :last_name - -* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 [Luke Redpath] - -* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. [Jeremy Kemper] - -* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 [Aggregated by schoenm@earthlink.net] - -* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 [rubyonrails@atyp.de] - -* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 [Stefan Kaes] - -* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first [Bob Silva] - -* Allow :include to be used with has_many :through associations #3611 [Michael Schoen] - -* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 [Blair Zajac] - -* SQLServer: more compatible limit/offset emulation. #3779 [Tom Ward] - -* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 [Rick Olson] - -* PostgreSQL: correctly parse negative integer column defaults. #3776 [bellis@deepthought.org] - -* Fix problems with count when used with :include [Jeremy Hopple and Kevin Clark] - -* ActiveRecord::RecordInvalid now states which validations failed in its default error message [Tobias Lütke] - -* Using AssociationCollection#build with arrays of hashes should call build, not create [David Heinemeier Hansson] - -* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. [Nicholas Seckar] - -* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 [Maik Schmidt] - -* Support the :column option for remove_index with the PostgreSQL adapter. #3661 [Shugo Maeda] - -* Add documentation for add_index and remove_index. #3600 [Manfred Stienstra <m.stienstra@fngtps.com>] - -* If the OCI library is not available, raise an exception indicating as much. #3593 [Michael Schoen] - -* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. [Rick Olson] - -* Make dynamic finders honor additional passed in :conditions. #3569 [Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.] - -* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. [Nicholas Seckar] - -* Make .count work for has_many associations with multi line finder sql [Michael Schoen] - -* Add AR::Base.base_class for querying the ancestor AR::Base subclass [Jamis Buck] - -* Allow configuration of the column used for optimistic locking [wilsonb@gmail.com] - -* Don't hardcode 'id' in acts as list. [ror@philippeapril.com] - -* Fix date errors for SQLServer in association tests. #3406 [Kevin Clark] - -* Escape database name in MySQL adapter when creating and dropping databases. #3409 [anna@wota.jp] - -* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 [alex.borovsky@gmail.com] - -* .with_scope imposed create parameters now bypass attr_protected [Tobias Lütke] - -* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. [Marcel Molina Jr.] - -* Multiple enhancements and adjustments to DB2 adaptor. #3377 [contact@maik-schmidt.de] - -* Sanitize scoped conditions. [Marcel Molina Jr.] - -* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) [David Heinemeier Hansson] - -* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. [Tobias Lütke] - -* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. [Tobias Lütke] - -* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 [yanowitz-rubyonrails@quantumfoam.org, Florian Weber] - -* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 [wejn@box.cz, Rick Olson, Scott Barron] - -* removed :piggyback in favor of just allowing :select on :through associations. [Tobias Lütke] - -* made method missing delegation to class methods on relation target work on :through associations. [Tobias Lütke] - -* made .find() work on :through relations. [Tobias Lütke] - -* Fix typo in association docs. #3296. [Blair Zajac] - -* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model [Tobias Lütke] - -*1.13.2* (December 13th, 2005) - -* Become part of Rails 1.0 - -* MySQL: allow encoding option for mysql.rb driver. [Jeremy Kemper] - -* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: - - class Post - has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author - end - - post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors - post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors - post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors - -* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson] - -* MySQL: fixes for the bundled mysql.rb driver. #3160 [Justin Forder] - -* SQLServer: fix obscure optimistic locking bug. #3068 [kajism@yahoo.com] - -* SQLServer: support uniqueidentifier columns. #2930 [keithm@infused.org] - -* SQLServer: cope with tables names qualified by owner. #3067 [jeff@ministrycentered.com] - -* SQLServer: cope with columns with "desc" in the name. #1950 [Ron Lusk, Ryan Tomayko] - -* SQLServer: cope with primary keys with "select" in the name. #3057 [rdifrango@captechventures.com] - -* Oracle: active? performs a select instead of a commit. #3133 [Michael Schoen] - -* MySQL: more robust test for nullified result hashes. #3124 [Stefan Kaes] - -* Reloading an instance refreshes its aggregations as well as its associations. #3024 [François Beausoleil] - -* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 [Paul Hammmond] - -* PostgreSQL: more robust sequence name discovery. #3087 [Rick Olson] - -* Oracle: use syntax compatible with Oracle 8. #3131 [Michael Schoen] - -* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. [Jeremy Kemper] - -* Added preliminary support for polymorphic associations [David Heinemeier Hansson] - -* Added preliminary support for join models [David Heinemeier Hansson] - -* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. [jeremy@jthopple.com, Marcel Molina Jr.] - -* Firebird: active? and reconnect! methods for handling stale connections. #428 [Ken Kunz <kennethkunz@gmail.com>] - -* Firebird: updated for FireRuby 0.4.0. #3009 [Ken Kunz <kennethkunz@gmail.com>] - -* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 [Jeremy Kemper] - -* Oracle: active? check pings the database rather than testing the last command status. #428 [Michael Schoen] - -* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 [kajism@yahoo.com] - -* Reloading a model doesn't lose track of its connection. #2996 [junk@miriamtech.com, Jeremy Kemper] - -* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 [colman@rominato.com, Florian Weber, Michael Schoen] - -* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 [Shugo Maeda] - -* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. [Jeremy Kemper] - -* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 [Shugo Maeda] - -* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. [Marcel Molina Jr.] - -* Correct boolean handling in generated reader methods. #2945 [Don Park, Stefan Kaes] - -* Don't generate read methods for columns whose names are not valid ruby method names. #2946 [Stefan Kaes] - -* Document :force option to create_table. #2921 [Blair Zajac <blair@orcaware.com>] - -* Don't add the same conditions twice in has_one finder sql. #2916 [Jeremy Evans] - -* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.] - -* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 [Ken Kunz <kennethkunz@gmail.com>] - -* SQLServer: active? and reconnect! methods for handling stale connections. #428 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 [MarkusQ@reality.com] - -* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 [Michael Schoen <schoenm@earthlink.net>] - -* Correct documentation for Base.delete_all. #1568 [Newhydra] - -* Oracle: test case for column default parsing. #2788 [Michael Schoen <schoenm@earthlink.net>] - -* Update documentation for Migrations. #2861 [Tom Werner <tom@cube6media.com>] - -* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 [Jeremy Kemper] - -* Oracle: Much faster column reflection. #2848 [Michael Schoen <schoenm@earthlink.net>] - -* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. [Jeremy Kemper] - -* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. [Jeremy Kemper] - -* PostgreSQL: correctly discover custom primary key sequences. #2594 [Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper] - -* SQLServer: don't report limits for unsupported field types. #2835 [Ryan Tomayko] - -* Include the Enumerable module in ActiveRecord::Errors. [Rick Bradley <rick@rickbradley.com>] - -* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 [rubyonrails@atyp.de] - -* Don't cast nil or empty strings to a dummy date. #2789 [Rick Bradley <rick@rickbradley.com>] - -* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 [rephorm@rephorm.com] - -* Fix sqlite adaptor's detection of missing dbfile or database declaration. [Nicholas Seckar] - -* Fixed acts_as_list for definitions without an explicit :order #2803 [Jonathan Viney] - -* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. [tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper] - -* Correct handling of complex order clauses with SQL Server limit emulation. #2770 [Tom Ward <tom@popdog.net>, Matt B.] - -* Correct whitespace problem in Oracle default column value parsing. #2788 [rick@rickbradley.com] - -* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 [larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper] - -* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. [Jeremy Kemper] - -* More compatible Oracle column reflection. #2771 [Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>] - - -*1.13.0* (November 7th, 2005) - -* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 [Ryan Tomayko] - -* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: - - has_many :posts, :include => [ :author, :comments ] - -* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: - - Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do - # Find where name = ? and active=true - Comment.find :all, :conditions => ['name = ?', name] - # Create comment associated with :post_id - Comment.create :body => "Hello world" - end - -* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 [Ryan Tomayko] - -* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: - - Comment.constrain(:creation => { :post_id => 5 }) do - # Associated with :post_id - Comment.create :body => "Hello world" - end - - This is rarely used directly, but allows for find_or_create on associations. So you can do: - - # If the tag doesn't exist, a new one is created that's associated with the person - person.tags.find_or_create_by_name("Summer") - -* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: - - # No 'Summer' tag exists - Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") - - # Now the 'Summer' tag does exist - Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") - -* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: - - class Account < ActiveRecord::Base - has_many :people do - def find_or_create_by_name(name) - first_name, *last_name = name.split - last_name = last_name.join " " - - find_or_create_by_first_name_and_last_name(first_name, last_name) - end - end - end - - person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") - person.first_name # => "David" - person.last_name # => "Heinemeier Hansson" - - Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). - -* Omit internal dtproperties table from SQLServer table list. #2729 [Ryan Tomayko] - -* Quote column names in generated SQL. #2728 [Ryan Tomayko] - -* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 [Jeremy Kemper] - -* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). [Jeremy Kemper] - -* Correct fixture behavior when table name pluralization is off. #2719 [Rick Bradley <rick@rickbradley.com>] - -* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 [Dan Peterson] - -* Added migration support for Oracle #2647 [Michael Schoen] - -* Worked around that connection can't be reset if allow_concurrency is off. #2648 [Michael Schoen <schoenm@earthlink.net>] - -* Fixed SQL Server adapter to pass even more tests and do even better #2634 [Ryan Tomayko] - -* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 [Tom Ward] - -* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 [Tom Ward] - -* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 [dansketcher@gmail.com] - -* Constraints are cloned so they can't be inadvertently modified while they're -in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] - -* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 [duane.johnson@gmail.com] - -* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 [Michael Schoen] - -* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 [maik schmidt] - - -*1.12.2* (October 26th, 2005) - -* Allow symbols to rename columns when using SQLite adapter. #2531 [Kevin Clark] - -* Map Active Record time to SQL TIME. #2575, #2576 [Robby Russell <robby@planetargon.com>] - -* Clarify semantics of ActiveRecord::Base#respond_to? #2560 [Stefan Kaes] - -* Fixed Association#clear for associations which have not yet been accessed. #2524 [Patrick Lenz <patrick@lenz.sh>] - -* HABTM finders shouldn't return readonly records. #2525 [Patrick Lenz <patrick@lenz.sh>] - -* Make all tests runnable on their own. #2521. [Blair Zajac <blair@orcaware.com>] - - -*1.12.1* (October 19th, 2005) - -* Always parenthesize :conditions options so they may be safely combined with STI and constraints. - -* Correct PostgreSQL primary key sequence detection. #2507 [tmornini@infomania.com] - -* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations - - -*1.12.0* (October 16th, 2005) - -* Update/clean up documentation (rdoc) - -* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 [Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>] - -* Change default logging colors to work on both white and black backgrounds. [Sam Stephenson] - -* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 [purestorm@ggnore.net] - -* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 [Robby Russell <robby@planetargon.com>] - -* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. - -* Avoid memleak in dev mode when using fcgi - -* Simplified .clear on active record associations by using the existing delete_records method. #1906 [Caleb <me@cpb.ca>] - -* Delegate access to a customized primary key to the conventional id method. #2444. [Blair Zajac <blair@orcaware.com>] - -* Fix errors caused by assigning a has-one or belongs-to property to itself - -* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped [Sam Stephenson] - -* Update DB2 adapter. #2206. [contact@maik-schmidt.de] - -* Corrections to SQLServer native data types. #2267. [rails.20.clarry@spamgourmet.com] - -* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. - -* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. [Blair Zajac <blair@orcaware.com>] - -* Misc doc fixes (typos/grammar/etc.). #2430. [coffee2code] - -* Add test coverage for content_columns. #2432. [coffee2code] - -* Speed up for unthreaded environments. #2431. [Stefan Kaes] - -* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. [Stefan Kaes] - -* Speed up the setting of table_name. #2428. [Stefan Kaes] - -* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. [Stefan Kaes] - -* Fix typo of 'constrains' to 'contraints'. #2069. [Michael Schuerig <michael@schuerig.de>] - -* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. [Stefan Kaes] - -* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. [Michael Schuerig <michael@schuerig.de>] - -* Add geometric type for postgresql adapter. #2233 [Andrew Kaspick] - -* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. [Stefan Kaes] - -* Add convenience predicate methods on Column class. In partial fullfilment of #1236. [Stefan Kaes] - -* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 [Chad Fowler <chad@chadfowler.com>, Nicholas Seckar] - -* Added :force option to create_table that'll try to drop the table if it already exists before creating - -* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. [Nicholas Seckar] - -* Use foreign_key inflection uniformly. #2156 [Blair Zajac <blair@orcaware.com>] - -* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 [joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>] - -* Returning false from before_destroy should cancel the action. #1829 [Jeremy Huffman] - -* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 [mat <mat@absolight.fr>] - -* Extensive documentation for the abstract database adapter. #2250 [François Beausoleil <fbeausoleil@ftml.net>] - -* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 [jay@jay.fm, Blair Zajac <blair@orcaware.com>] - -* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 [Manuel Holtgrewe <purestorm@ggnore.net>] - -* Make update_attribute use the same writer method that update_attributes uses. - #2237 [trevor@protocool.com] - -* Make migrations honor table name prefixes and suffixes. #2298 [Jakob Skjerning, Marcel Molina Jr.] - -* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 [dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org] - -* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 [chris@chrisbrinker.com] - -* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) - -* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: - - ActiveRecord::Base.observers = :cacher, :garbage_collector - -* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 [solo@gatelys.com] - -* Wrap :conditions in parentheses to prevent problems with OR's #1871 [Jamis Buck] - -* Allow the postgresql adapter to work with the SchemaDumper. [Jamis Buck] - -* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. [Jamis Buck] - -* Fixed migrations for Windows when using more than 10 [David Naseby] - -* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 [Florian Weber] - -* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 [Tobias Lütke] - -* Improved migrations' behavior when the schema_info table is empty. [Nicholas Seckar] - -* Fixed that Observers didn't observe sub-classes #627 [Florian Weber] - -* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 [Marcel Molina Jr.] - -* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 [skae] - -* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 [Florian Weber] - -* Added better exception error when unknown column types are used with migrations #1814 [François Beausoleil] - -* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 [kajism@yahoo.com] - -* Fixed comparison of Active Record objects so two new objects are not equal #2099 [deberg] - -* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 [Tom Ward] - -* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 [coffee2code] - -* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 [sd@notso.net] - -* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ - -* Make sure the schema_info table is created before querying the current version #1903 - -* Fixtures ignore table name prefix and suffix #1987 [Jakob Skjerning] - -* Add documentation for index_type argument to add_index method for migrations #2005 [Blaine] - -* Modify read_attribute to allow a symbol argument #2024 [Ken Kunz] - -* Make destroy return self #1913 [Sebastian Kanthak] - -* Fix typo in validations documentation #1938 [court3nay] - -* Make acts_as_list work for insert_at(1) #1966 [hensleyl@papermountain.org] - -* Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky] - -* Allow add_column and create_table to specify NOT NULL #1712 [emptysands@gmail.com] - -* Fix create_table so that id column is implicitly added [Rick Olson] - -* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 - -* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 - -* Fixed the handling of camelCase columns names in Oracle #1798 - -* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 - -* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 - -* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 [Tobias Lütke] - - class Comment < AR:B - def self.search(q) - find(:all, :conditions => ["body = ?", q]) - end - end - - class Post < AR:B - has_many :comments - end - - Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' - - NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as - by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on - details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself - noticed :) - -* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 [Sam Stephenson] - -* Remove extra definition of supports_migrations? from abstract_adaptor.rb [Nicholas Seckar] - -* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions - -* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 [Maik Schmidt] - -* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 [Stefan Kaes] - - -*1.11.1* (11 July, 2005) - -* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 [Rick Olson] - -* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 [tyler@kianta.com] - -* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 [Sam Stephenson] - -* Correct reflected table name for singular associations. #1688 [court3nay] - -* Fixed optimistic locking with SQL Server #1660 [tom@popdog.net] - -* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current - -* Added better error message for "packets out of order" #1630 [court3nay] - -* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 - - -*1.11.0* (6 July, 2005) - -* Fixed that Yaml error message in fixtures hid the real error #1623 [Nicholas Seckar] - -* Changed logging of SQL statements to use the DEBUG level instead of INFO - -* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. - -* Added callback hooks to association collections #1549 [Florian Weber]. Example: - - class Project - has_and_belongs_to_many :developers, :before_add => :evaluate_velocity - - def evaluate_velocity(developer) - ... - end - end - - ..raising an exception will cause the object not to be added (or removed, with before_remove). - - -* Fixed Base.content_columns call for SQL Server adapter #1450 [DeLynn Berry] - -* Fixed Base#write_attribute to work with both symbols and strings #1190 [Paul Legato] - -* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 [Florian Weber] - -* Speed up ActiveRecord#method_missing for the common case (read_attribute). - -* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 [Stefan Kaes] - -* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 [Chris McGrath] - -* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 [raidel@onemail.at] - -* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 [Michael Schuerig] - -* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 [DeLynn Berry] - -* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 [Mark Imbriaco/DeLynn Berry] - -* Fixed that multiparameter posts ignored attr_protected #1532 [alec+rails@veryclever.net] - -* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 [flash@vanklinkenbergsoftware.nl] - -* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: - - Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' - - ...should instead be: - - Developer.find( - :all, - :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', - :conditions => 'project_id=1' - ) - -* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 [Marcel Molina Jr.] - -* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 [cluon] - -* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 - -* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 [Alisdair McDiarmid] - -* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice - -* Allow any Enumerable, not just Array, to work as bind variables #1344 [Jeremy Kemper] - -* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. - Example: - - david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] - david.save - - If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new - project is saved when david.save is called. - - Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: - - david.project_ids = [1, 5, 7] - -* Corrected typo in find SQL for has_and_belongs_to_many. #1312 [ben@bensinclair.com] - -* Fixed sanitized conditions for has_many finder method. #1281 [jackc@hylesanderson.com, pragdave, Tobias Lütke] - -* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 [dave@cherryville.org] - -* Corrected @@configurations typo #1410 [david@ruppconsulting.com] - -* Return PostgreSQL columns in the order they were declared #1374 [perlguy@gmail.com] - -* Allow before/after update hooks to work on models using optimistic locking - -* Eager loading of dependent has_one associations won't delete the association #1212 - -* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. - -* Using transactional fixtures now causes the data to be loaded only once. - -* Added fixture accessor methods that can be used when instantiated fixtures are disabled. - - fixtures :web_sites - - def test_something - assert_equal "Ruby on Rails", web_sites(:rubyonrails).name - end - -* Added DoubleRenderError exception that'll be raised if render* is called twice #518 [Nicholas Seckar] - -* Fixed exceptions occuring after render has been called #1096 [Nicholas Seckar] - -* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 - -* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead - -* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: - - Conditional validations such as the following are made possible: - validates_numericality_of :income, :if => :employed? - - Conditional validations can also solve the salted login generator problem: - validates_confirmation_of :password, :if => :new_password? - - Using blocks: - validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } - -* Fixed use of construct_finder_sql when using :join #1288 [dwlt@dwlt.net] - -* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 [Rick Olson] - -* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 [Jeremy Kemper] - -* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. - -* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. - -* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: - - # SELECT * FROM topics WHERE title IN ('First', 'Second') - Topic.find_all_by_title(["First", "Second"]) - -* Added compatibility with camelCase column names for dynamic finders #533 [Dee Zsombor] - -* Fixed extraneous comma in count() function that made it not work with joins #1156 [Jarkko Laine/Dee Zsombor] - -* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 [Alisdair McDiarmid] - -* Fixed that validate_length_of lost :on option when :within was specified #1195 [jhosteny@mac.com] - -* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: - - development: - adapter: postgresql - database: rails_development - host: localhost - username: postgres - password: - encoding: UTF8 - min_messages: ERROR - -* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 [Jamis Buck] - -* Added validates_exclusion_of as a negative of validates_inclusion_of - -* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls - - -*1.10.1* (20th April, 2005) - -* Fixed frivilous database queries being triggered with eager loading on empty associations and other things - -* Fixed order of loading in eager associations - -* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 - - -*1.10.0* (19th April, 2005) - -* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: - - for post in Post.find(:all, :limit => 100) - puts "Post: " + post.title - puts "Written by: " + post.author.name - puts "Last comment on: " + post.comments.first.created_on - end - - This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: - - for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) - - ...and the number of database queries needed is now 1. - -* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: - - Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(:first, :order => "created_on DESC", :offset => 5) - Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) - Person.find(:all, :offset => 10, :limit => 10) - -* Added acts_as_nested_set #1000 [wschenk]. Introduction: - - This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with - the added feature that you can select the children and all of it's descendants with - a single query. A good use case for this is a threaded post system, where you want - to display every reply to a comment without multiple selects. - -* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid [Dave Thomas] - -* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 [gnuman1@gmail.com] - -* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 [andrew.john.peters@gmail.com] - -* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 [stephenh@chase3000.com] - -* Fixed page caching for non-vhost applications living underneath the root #1004 [Ben Schumacher] - -* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 [adelle] - -* Added the option to specify the acceptance string in validates_acceptance_of #1106 [caleb@aei-tech.com] - -* Added insert_at(position) to acts_as_list #1083 [DeLynnB] - -* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) - -* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 [yon@milliped.com] - -* Fixed boolean saving on Oracle #1093 [mparrish@pearware.org] - -* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 - -* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 [Leon Bredt] - -* Added quoting of column names for fixtures #997 [jcfischer@gmail.com] - -* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 [Caleb Tennis] - -* Fixed that benchmarking times for rendering included db runtimes #987 [Stefan Kaes] - -* Fixed boolean queries for t/f fields in PostgreSQL #995 [dave@cherryville.org] - -* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 [Jeremy Kemper] - -* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 [dave@cherryville.org] - -* Fixed Base.silence/benchmark to only log if a logger has been configured #986 [Stefan Kaes] - -* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 [Stefan Kaes] - -* Fixed bug in Base#hash method that would treat records with the same string-based id as different [Dave Thomas] - -* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) - - -*1.9.1* (27th March, 2005) - -* Fixed that Active Record objects with float attribute could not be cloned #808 - -* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 [Nicholas Seckar] - -* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count - -* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 [Scott Barron] - -* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 [delynnb] - - -*1.9.0* (22th March, 2005) - -* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: - - Developer.find_all nil, 'id ASC', 5 # return the first five developers - Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward - - This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. - -* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 [Nicholas Seckar/Sam Stephenson] - -* Improved the performance of the OCI8 adapter for Oracle #723 [pilx/gjenkins] - -* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 [dave@cherryville.org] - -* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 [mindel] - -* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 [Alisdair McDiarmid] - -* Added the possibility of specifying fixtures in multiple calls #816 [kim@tinker.com] - -* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 [stian@grytoyr.net] - -* Added optionally allow for nil or empty strings with validates_numericality_of #801 [Sebastian Kanthak] - -* Fixed problem with using slashes in validates_format_of regular expressions #801 [Sebastian Kanthak] - -* Fixed that SQLite3 exceptions are caught and reported properly #823 [yerejm] - -* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself - -* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) - - -*1.8.0* (7th March, 2005) - -* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) - -* Added support for timestamp with time zone in PostgreSQL #560 [Scott Barron] - -* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: - - * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the - +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ - objects that should be inspected to determine which attributes triggered the errors. - * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. - You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. - -* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 [rodrigo k] - -* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 [Jeremy Kemper] - -* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: - - class Account < ActiveRecord::Base - has_one :credit_card, :dependent => true - end - class CreditCard < ActiveRecord::Base - belongs_to :account - end - - account.credit_card # => returns existing credit card, lets say id = 12 - account.credit_card = CreditCard.create("number" => "123") - account.save # => CC with id = 12 is destroyed - - -* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: - - Validates whether the value of the specified attribute is numeric by trying to convert it to - a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression - <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). - - class Person < ActiveRecord::Base - validates_numericality_of :value, :on => :create - end - - Configuration options: - * <tt>message</tt> - A custom error message (default is: "is not a number") - * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) - * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) - - -* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 [Scott Barron] - -* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) - -* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 [james@slashetc.com] - - -*1.7.0* (24th February, 2005) - -* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 [Jamis Buck] - -* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: - - 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple - and safe way of passing table-specific sequence information to the adapter.) - 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to - resort to some hacks to get data converted to Date or Time in Ruby. - If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the - hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. - This is nasty - but if you use Duck Typing you'll probably not care very much. - In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is - valid - too many databases use DATE for both. - Timezones and sub-second precision on timestamps are not supported. - 3. Default values that are functions (such as "SYSDATE") are not supported. This is a - restriction of the way active record supports default values. - 4. Referential integrity constraints are not fully supported. Under at least - some circumstances, active record appears to delete parent and child records out of - sequence and out of transaction scope. (Or this may just be a problem of test setup.) - - The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ - -* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 [YuriSchimke] - -* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 [yerejm] - -* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 [tonka] - -* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 [Nicholas Seckar] - -* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 [daniel@nightrunner.com] - -* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 [adelle@bullet.net.au] - -* Fixed that find_by_* would fail when column names had numbers #670 [demetrius] - -* Fixed the SQL Server adapter on a bunch of issues #667 [DeLynn] - - 1. Created a new columns method that is much cleaner. - 2. Corrected a problem with the select and select_all methods - that didn't account for the LIMIT clause being passed into raw SQL statements. - 3. Implemented the string_to_time method in order to create proper instances of the time class. - 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. - 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. - -* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 [lmarlow] - -* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: - - class Person < ActiveRecord::Base - validates_each :first_name, :last_name do |record, attr| - record.errors.add attr, 'starts with z.' if attr[0] == ?z - end - end - -* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 [Jeremy Kemper] - -* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: - - class Person < ActiveRecord::Base - validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } - end - -* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 [Tim Bates] - -* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: - - class Project < ActiveRecord::Base - primary_key "sysid" - table_name "XYZ_PROJECT" - inheritance_column { original_inheritance_column + "_id" } - end - -* Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu] - - -*1.6.0* (January 25th, 2005) - -* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. - -* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 - -* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. - -* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example - - people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } - Person.update(people.keys, people.values) - -* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 [Scott Baron] - -* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 [notahat] - -* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 [Demetrius] - -* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 [Jeremy Kemper] - -* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 [Eric Anderson] - -* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 [Eric Anderson] - -* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not - -* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription - -* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 [Demetrius] - -* Fixed that find_all would produce invalid sql when called sequentialy #490 [Scott Baron] - - -*1.5.1* (January 18th, 2005) - -* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 [Tim Bates] - -* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 [Pelle] - - -*1.5.0* (January 17th, 2005) - -* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 [Eric Hodel] - -* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: - - class Book < ActiveRecord::Base - has_many :pages - belongs_to :library - - validates_associated :pages, :library - end - -* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: - - == Unsaved objects and associations - - You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be - aware of, mostly involving the saving of associated objects. - - === One-to-one associations - - * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in - order to update their primary keys - except if the parent object is unsaved (new_record? == true). - * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment - is cancelled. - * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). - * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does - not save the parent either. - - === Collections - - * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object - (the owner of the collection) is not yet stored in the database. - * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. - * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). - * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. - -* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 [Tim Bates] - -* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 [Tim Bates] - -* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 [Tim Bates] - -* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 [Tim Bates] - -* Fixed binary support for PostgreSQL #444 [alex@byzantine.no] - -* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the - collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If - it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, - it'll take one less SELECT query if you use length. - -* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 [atyp.de] - -* Fixed that foreign keys named the same as the association would cause stack overflow #437 [Eric Anderson] - -* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 [Alexey] - -* Added Base#reload that reloads the attributes of an object from the database #422 [Andreas Schwarz] - -* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 [Jeremy Kemper] - -* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 [Matt Mower] - -* Added that Observers can use the observes class method instead of overwriting self.observed_class(). - - Before: - class ListSweeper < ActiveRecord::Base - def self.observed_class() [ List, Item ] - end - - After: - class ListSweeper < ActiveRecord::Base - observes List, Item - end - -* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is - -* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name - -* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. - - Before: topic.update_attribute(:approved, !approved?) - After : topic.toggle!(:approved) - -* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: - - page.views # => 1 - page.increment!(:views) # executes an UPDATE statement - page.views # => 2 - - page.increment(:views).increment!(:views) - page.views # => 4 - -* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. - - - - -*1.14.2* (April 9th, 2005) - -* Fixed calculations for the Oracle Adapter (closes #4626) [Michael Schoen] - - -*1.14.1* (April 6th, 2006) - -* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. [Nicholas Seckar] - -* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) [Lars Pind] - -* Enable Limit/Offset in Calculations (closes #4558) [lmarlow] - -* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) [Rick Olson] - -* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 [lagroue@free.fr] - -* Allow AR::Base#respond_to? to behave when @attributes is nil [Ryan Davis] - -* Support eager includes when going through a polymorphic has_many association. [Rick Olson] - -* Added support for eagerly including polymorphic has_one associations. (closes #4525) [Rick Olson] - - class Post < ActiveRecord::Base - has_one :tagging, :as => :taggable - end - - Post.find :all, :include => :tagging - -* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many [Rick Olson] - -* Added support for going through a polymorphic has_many association: (closes #4401) [Rick Olson] - - class PhotoCollection < ActiveRecord::Base - has_many :photos, :as => :photographic - belongs_to :firm - end - - class Firm < ActiveRecord::Base - has_many :photo_collections - has_many :photos, :through => :photo_collections - end - -* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. [ruben.nine@gmail.com] - -* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. [Florian Weber] - -* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) [Stefan] - -* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) [Rick Olson] - -* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model [David Heinemeier Hansson] - -* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) [David Heinemeier Hansson] - -* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). [Marcel Mollina Jr.] - -* Fixed broken OCIAdapter #4457 [Michael Schoen] - - -*1.14.0* (March 27th, 2006) - -* Replace 'rescue Object' with a finer grained rescue. Closes #4431. [Nicholas Seckar] - -* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table [Rick Olson] - -* Add support for :include to with_scope [andrew@redlinesoftware.com] - -* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 [Michael Schoen] - -* Change periods (.) in table aliases to _'s. Closes #4251 [jeff@ministrycentered.com] - -* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 [Rick Olson] - -* Fixed issue that kept :select options from being scoped [Rick Olson] - -* Fixed db_schema_import when binary types are present #3101 [David Heinemeier Hansson] - -* Fixed that MySQL enums should always be returned as strings #3501 [David Heinemeier Hansson] - -* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. [Rick Olson] - - class Connection < ActiveRecord::Base - belongs_to :user - belongs_to :channel - end - - class Channel < ActiveRecord::Base - has_many :connections - has_many :contacts, :through => :connections, :class_name => 'User' # OLD - has_many :contacts, :through => :connections, :source => :user # NEW - end - -* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 [contact@maik-schmidt.de] - -* Allow overriding of find parameters in scoped has_many :through calls [Rick Olson] - - In this example, :include => false disables the default eager association from loading. :select changes the standard - select clause. :joins specifies a join that is added to the end of the has_many :through query. - - class Post < ActiveRecord::Base - has_many :tags, :through => :taggings, :include => :tagging do - def add_joins_and_select - find :all, :select => 'tags.*, authors.id as author_id', :include => false, - :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' - end - end - end - -* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson] - -* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney] - -* Quit ignoring default :include options in has_many :through calls [Mark James] - -* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) [Jonathan Viney] - -* Eager Loading support added for has_many :through => :has_many associations (see below). [Rick Olson] - -* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: - - class Firm < ActiveRecord::Base - has_many :clients - has_many :invoices, :through => :clients - end - - class Client < ActiveRecord::Base - belongs_to :firm - has_many :invoices - end - - class Invoice < ActiveRecord::Base - belongs_to :client - end - -* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) [Josh Susser] - -* Fixed has_many :through to include :conditions set on the :through association. closes #4020 [Jonathan Viney] - -* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) [andylien@gmail.com / Rick Olson] - -* SQL Server adapter gets some love #4298 [Ryan Tomayko] - -* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 [derrickspell@cdmplus.com] - -* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): - - Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') - -* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. [Rick Olson] - -* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 [Michael Koziarski] - -* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 [Michael Koziarski] - -* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 [Tom Ward] - -* Fixed that Migration#execute would have the table name prefix appended to its query #4110 [mark.imbriaco@pobox.com] - -* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) [Jamis Buck] - -* Use association's :conditions when eager loading. [Jeremy Evans] #4144 - -* Alias the has_and_belongs_to_many join table on eager includes. #4106 [Jeremy Evans] - - This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. - - Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') - -* Oracle adapter gets some love #4230 [Michael Schoen] - - * Changes :text to CLOB rather than BLOB [Moses Hohman] - * Fixes an issue with nil numeric length/scales (several) - * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] - * Tweaks a unit test to get it all green again - * Adds support for #current_database - -* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 [Rick Olson] - - class CachedModel < ActiveRecord::Base - self.abstract_class = true - end - - class Post < CachedModel - end - - CachedModel.abstract_class? - => true - - Post.abstract_class? - => false - - Post.base_class - => Post - - Post.table_name - => 'posts' - -* Allow :dependent options to be used with polymorphic joins. #3820 [Rick Olson] - - class Foo < ActiveRecord::Base - has_many :attachments, :as => :attachable, :dependent => :delete_all - end - -* Nicer error message on has_many :through when :through reflection can not be found. #4042 [court3nay] - -* Upgrade to Transaction::Simple 1.3 [Jamis Buck] - -* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model [Rick Olson] - -* Allow ordering of calculated results and/or grouped fields in calculations [solo@gatelys.com] - -* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 [johan@johansorensen.com] - -* Dynamically set allow_concurrency. #4044 [Stefan Kaes] - -* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: - - topic.to_xml - - ...returns: - - <?xml version="1.0" encoding="UTF-8"?> - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <id type="integer">1</id> - <approved type="boolean">false</approved> - <replies-count type="integer">0</replies-count> - <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> - <written-on type="datetime">2003-07-16 09:28:00</written-on> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - ...and you can configure with: - - topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) - - ...that'll return: - - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <approved type="boolean">false</approved> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - You can even do load first-level associations as part of the document: - - firm.to_xml :include => [ :account, :clients ] - - ...that'll return something like: - - <?xml version="1.0" encoding="UTF-8"?> - <firm> - <id type="integer">1</id> - <rating type="integer">1</rating> - <name>37signals</name> - <clients> - <client> - <rating type="integer">1</rating> - <name>Summit</name> - </client> - <client> - <rating type="integer">1</rating> - <name>Microsoft</name> - </client> - </clients> - <account> - <id type="integer">1</id> - <credit-limit type="integer">50</credit-limit> - </account> - </firm> - -* Allow :counter_cache to take a column name for custom counter cache columns [Jamis Buck] - -* Documentation fixes for :dependent [robby@planetargon.com] - -* Stop the MySQL adapter crashing when views are present. #3782 [Jonathan Viney] - -* Don't classify the belongs_to class, it is already singular #4117 [keithm@infused.org] - -* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. [Rick Olson] - -* Fix quoting of inheritance column for STI eager loading #4098 [Jonathan Viney <jonathan@bluewire.net.nz>] - -* Added smarter table aliasing for eager associations for multiple self joins #3580 [Rick Olson] - - * The first time a table is referenced in a join, no alias is used. - * After that, the parent class name and the reflection name are used. - - Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... - - * Any additional join references get a numerical suffix like '_2', '_3', etc. - -* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. - -* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: - - # cascaded in two levels - >> Author.find(:all, :include=>{:posts=>:comments}) - => authors - +- posts - +- comments - - # cascaded in two levels and normal association - >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in two levels with two has_many associations - >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in three levels - >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) - => companies - +- groups - +- members - +- favorites - -* Make counter cache work when replacing an association #3245 [eugenol@gmail.com] - -* Make migrations verbose [Jamis Buck] - -* Make counter_cache work with polymorphic belongs_to [Jamis Buck] - -* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 [anna@wota.jp] - -* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: - - * Does not support DATE SQL column types; use DATETIME instead. - * Date columns on HABTM join tables are returned as String, not Time. - * Insertions are potentially broken for :polymorphic join tables - * BLOB column access not yet fully supported - -* Clear stale, cached connections left behind by defunct threads. [Jeremy Kemper] - -* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. [Jeremy Kemper] - -* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 [Michael Schoen] - -* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 [David Heinemeier Hansson] - -* Speed up class -> connection caching and stale connection verification. #3979 [Stefan Kaes] - -* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. [Kevin Clark] - -* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 [dblack@wobblini.net] - -* Define attribute query methods to avoid method_missing calls. #3677 [Jonathan Viney] - -* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 [Simon Stapleton, Tom Ward] - -* Added support for nested scopes #3407 [anna@wota.jp]. Examples: - - Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 - - # inner rule is used. (all previous parameters are ignored) - Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') - end - - # parameters are merged - Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 - end - end - -* Fixed db2 connection with empty user_name and auth options #3622 [phurley@gmail.com] - -* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 [Masao Mutoh] - -* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 [Lars Pind] - -* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: - - Person.average :age - Person.minimum :age - Person.maximum :age - Person.sum :salary, :group => :last_name - -* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 [Luke Redpath] - -* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. [Jeremy Kemper] - -* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 [Aggregated by schoenm@earthlink.net] - -* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 [rubyonrails@atyp.de] - -* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 [Stefan Kaes] - -* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first [Bob Silva] - -* Allow :include to be used with has_many :through associations #3611 [Michael Schoen] - -* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 [Blair Zajac] - -* SQLServer: more compatible limit/offset emulation. #3779 [Tom Ward] - -* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 [Rick Olson] - -* PostgreSQL: correctly parse negative integer column defaults. #3776 [bellis@deepthought.org] - -* Fix problems with count when used with :include [Jeremy Hopple and Kevin Clark] - -* ActiveRecord::RecordInvalid now states which validations failed in its default error message [Tobias Lütke] - -* Using AssociationCollection#build with arrays of hashes should call build, not create [David Heinemeier Hansson] - -* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. [Nicholas Seckar] - -* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 [Maik Schmidt] - -* Support the :column option for remove_index with the PostgreSQL adapter. #3661 [Shugo Maeda] - -* Add documentation for add_index and remove_index. #3600 [Manfred Stienstra <m.stienstra@fngtps.com>] - -* If the OCI library is not available, raise an exception indicating as much. #3593 [Michael Schoen] - -* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. [Rick Olson] - -* Make dynamic finders honor additional passed in :conditions. #3569 [Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.] - -* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. [Nicholas Seckar] - -* Make .count work for has_many associations with multi line finder sql [Michael Schoen] - -* Add AR::Base.base_class for querying the ancestor AR::Base subclass [Jamis Buck] - -* Allow configuration of the column used for optimistic locking [wilsonb@gmail.com] - -* Don't hardcode 'id' in acts as list. [ror@philippeapril.com] - -* Fix date errors for SQLServer in association tests. #3406 [Kevin Clark] - -* Escape database name in MySQL adapter when creating and dropping databases. #3409 [anna@wota.jp] - -* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 [alex.borovsky@gmail.com] - -* .with_scope imposed create parameters now bypass attr_protected [Tobias Lütke] - -* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. [Marcel Molina Jr.] - -* Multiple enhancements and adjustments to DB2 adaptor. #3377 [contact@maik-schmidt.de] - -* Sanitize scoped conditions. [Marcel Molina Jr.] - -* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) [David Heinemeier Hansson] - -* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. [Tobias Lütke] - -* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. [Tobias Lütke] - -* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 [yanowitz-rubyonrails@quantumfoam.org, Florian Weber] - -* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 [wejn@box.cz, Rick Olson, Scott Barron] - -* removed :piggyback in favor of just allowing :select on :through associations. [Tobias Lütke] - -* made method missing delegation to class methods on relation target work on :through associations. [Tobias Lütke] - -* made .find() work on :through relations. [Tobias Lütke] - -* Fix typo in association docs. #3296. [Blair Zajac] - -* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model [Tobias Lütke] - -*1.13.2* (December 13th, 2005) - -* Become part of Rails 1.0 - -* MySQL: allow encoding option for mysql.rb driver. [Jeremy Kemper] - -* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: - - class Post - has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author - end - - post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors - post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors - post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors - -* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson] - -* MySQL: fixes for the bundled mysql.rb driver. #3160 [Justin Forder] - -* SQLServer: fix obscure optimistic locking bug. #3068 [kajism@yahoo.com] - -* SQLServer: support uniqueidentifier columns. #2930 [keithm@infused.org] - -* SQLServer: cope with tables names qualified by owner. #3067 [jeff@ministrycentered.com] - -* SQLServer: cope with columns with "desc" in the name. #1950 [Ron Lusk, Ryan Tomayko] - -* SQLServer: cope with primary keys with "select" in the name. #3057 [rdifrango@captechventures.com] - -* Oracle: active? performs a select instead of a commit. #3133 [Michael Schoen] - -* MySQL: more robust test for nullified result hashes. #3124 [Stefan Kaes] - -* Reloading an instance refreshes its aggregations as well as its associations. #3024 [François Beausoleil] - -* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 [Paul Hammmond] - -* PostgreSQL: more robust sequence name discovery. #3087 [Rick Olson] - -* Oracle: use syntax compatible with Oracle 8. #3131 [Michael Schoen] - -* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. [Jeremy Kemper] - -* Added preliminary support for polymorphic associations [David Heinemeier Hansson] - -* Added preliminary support for join models [David Heinemeier Hansson] - -* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. [jeremy@jthopple.com, Marcel Molina Jr.] - -* Firebird: active? and reconnect! methods for handling stale connections. #428 [Ken Kunz <kennethkunz@gmail.com>] - -* Firebird: updated for FireRuby 0.4.0. #3009 [Ken Kunz <kennethkunz@gmail.com>] - -* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 [Jeremy Kemper] - -* Oracle: active? check pings the database rather than testing the last command status. #428 [Michael Schoen] - -* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 [kajism@yahoo.com] - -* Reloading a model doesn't lose track of its connection. #2996 [junk@miriamtech.com, Jeremy Kemper] - -* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 [colman@rominato.com, Florian Weber, Michael Schoen] - -* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 [Shugo Maeda] - -* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. [Jeremy Kemper] - -* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 [Shugo Maeda] - -* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. [Marcel Molina Jr.] - -* Correct boolean handling in generated reader methods. #2945 [Don Park, Stefan Kaes] - -* Don't generate read methods for columns whose names are not valid ruby method names. #2946 [Stefan Kaes] - -* Document :force option to create_table. #2921 [Blair Zajac <blair@orcaware.com>] - -* Don't add the same conditions twice in has_one finder sql. #2916 [Jeremy Evans] - -* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.] - -* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 [Ken Kunz <kennethkunz@gmail.com>] - -* SQLServer: active? and reconnect! methods for handling stale connections. #428 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 [MarkusQ@reality.com] - -* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 [Michael Schoen <schoenm@earthlink.net>] - -* Correct documentation for Base.delete_all. #1568 [Newhydra] - -* Oracle: test case for column default parsing. #2788 [Michael Schoen <schoenm@earthlink.net>] - -* Update documentation for Migrations. #2861 [Tom Werner <tom@cube6media.com>] - -* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 [Jeremy Kemper] - -* Oracle: Much faster column reflection. #2848 [Michael Schoen <schoenm@earthlink.net>] - -* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. [Jeremy Kemper] - -* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. [Jeremy Kemper] - -* PostgreSQL: correctly discover custom primary key sequences. #2594 [Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper] - -* SQLServer: don't report limits for unsupported field types. #2835 [Ryan Tomayko] - -* Include the Enumerable module in ActiveRecord::Errors. [Rick Bradley <rick@rickbradley.com>] - -* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 [rubyonrails@atyp.de] - -* Don't cast nil or empty strings to a dummy date. #2789 [Rick Bradley <rick@rickbradley.com>] - -* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 [rephorm@rephorm.com] - -* Fix sqlite adaptor's detection of missing dbfile or database declaration. [Nicholas Seckar] - -* Fixed acts_as_list for definitions without an explicit :order #2803 [Jonathan Viney] - -* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. [tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper] - -* Correct handling of complex order clauses with SQL Server limit emulation. #2770 [Tom Ward <tom@popdog.net>, Matt B.] - -* Correct whitespace problem in Oracle default column value parsing. #2788 [rick@rickbradley.com] - -* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 [larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper] - -* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. [Jeremy Kemper] - -* More compatible Oracle column reflection. #2771 [Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>] - - -*1.13.0* (November 7th, 2005) - -* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 [Ryan Tomayko] - -* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: - - has_many :posts, :include => [ :author, :comments ] - -* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: - - Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do - # Find where name = ? and active=true - Comment.find :all, :conditions => ['name = ?', name] - # Create comment associated with :post_id - Comment.create :body => "Hello world" - end - -* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 [Ryan Tomayko] - -* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: - - Comment.constrain(:creation => { :post_id => 5 }) do - # Associated with :post_id - Comment.create :body => "Hello world" - end - - This is rarely used directly, but allows for find_or_create on associations. So you can do: - - # If the tag doesn't exist, a new one is created that's associated with the person - person.tags.find_or_create_by_name("Summer") - -* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: - - # No 'Summer' tag exists - Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") - - # Now the 'Summer' tag does exist - Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") - -* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: - - class Account < ActiveRecord::Base - has_many :people do - def find_or_create_by_name(name) - first_name, *last_name = name.split - last_name = last_name.join " " - - find_or_create_by_first_name_and_last_name(first_name, last_name) - end - end - end - - person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") - person.first_name # => "David" - person.last_name # => "Heinemeier Hansson" - - Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). - -* Omit internal dtproperties table from SQLServer table list. #2729 [Ryan Tomayko] - -* Quote column names in generated SQL. #2728 [Ryan Tomayko] - -* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 [Jeremy Kemper] - -* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). [Jeremy Kemper] - -* Correct fixture behavior when table name pluralization is off. #2719 [Rick Bradley <rick@rickbradley.com>] - -* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 [Dan Peterson] - -* Added migration support for Oracle #2647 [Michael Schoen] - -* Worked around that connection can't be reset if allow_concurrency is off. #2648 [Michael Schoen <schoenm@earthlink.net>] - -* Fixed SQL Server adapter to pass even more tests and do even better #2634 [Ryan Tomayko] - -* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 [Tom Ward] - -* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 [Tom Ward] - -* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 [dansketcher@gmail.com] - -* Constraints are cloned so they can't be inadvertently modified while they're -in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] - -* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 [duane.johnson@gmail.com] - -* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 [Michael Schoen] - -* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 [maik schmidt] - - -*1.12.2* (October 26th, 2005) - -* Allow symbols to rename columns when using SQLite adapter. #2531 [Kevin Clark] - -* Map Active Record time to SQL TIME. #2575, #2576 [Robby Russell <robby@planetargon.com>] - -* Clarify semantics of ActiveRecord::Base#respond_to? #2560 [Stefan Kaes] - -* Fixed Association#clear for associations which have not yet been accessed. #2524 [Patrick Lenz <patrick@lenz.sh>] - -* HABTM finders shouldn't return readonly records. #2525 [Patrick Lenz <patrick@lenz.sh>] - -* Make all tests runnable on their own. #2521. [Blair Zajac <blair@orcaware.com>] - - -*1.12.1* (October 19th, 2005) - -* Always parenthesize :conditions options so they may be safely combined with STI and constraints. - -* Correct PostgreSQL primary key sequence detection. #2507 [tmornini@infomania.com] - -* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations - - -*1.12.0* (October 16th, 2005) - -* Update/clean up documentation (rdoc) - -* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 [Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>] - -* Change default logging colors to work on both white and black backgrounds. [Sam Stephenson] - -* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 [purestorm@ggnore.net] - -* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 [Robby Russell <robby@planetargon.com>] - -* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. - -* Avoid memleak in dev mode when using fcgi - -* Simplified .clear on active record associations by using the existing delete_records method. #1906 [Caleb <me@cpb.ca>] - -* Delegate access to a customized primary key to the conventional id method. #2444. [Blair Zajac <blair@orcaware.com>] - -* Fix errors caused by assigning a has-one or belongs-to property to itself - -* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped [Sam Stephenson] - -* Update DB2 adapter. #2206. [contact@maik-schmidt.de] - -* Corrections to SQLServer native data types. #2267. [rails.20.clarry@spamgourmet.com] - -* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. - -* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. [Blair Zajac <blair@orcaware.com>] - -* Misc doc fixes (typos/grammar/etc.). #2430. [coffee2code] - -* Add test coverage for content_columns. #2432. [coffee2code] - -* Speed up for unthreaded environments. #2431. [Stefan Kaes] - -* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. [Stefan Kaes] - -* Speed up the setting of table_name. #2428. [Stefan Kaes] - -* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. [Stefan Kaes] - -* Fix typo of 'constrains' to 'contraints'. #2069. [Michael Schuerig <michael@schuerig.de>] - -* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. [Stefan Kaes] - -* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. [Michael Schuerig <michael@schuerig.de>] - -* Add geometric type for postgresql adapter. #2233 [Andrew Kaspick] - -* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. [Stefan Kaes] - -* Add convenience predicate methods on Column class. In partial fullfilment of #1236. [Stefan Kaes] - -* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 [Chad Fowler <chad@chadfowler.com>, Nicholas Seckar] - -* Added :force option to create_table that'll try to drop the table if it already exists before creating - -* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. [Nicholas Seckar] - -* Use foreign_key inflection uniformly. #2156 [Blair Zajac <blair@orcaware.com>] - -* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 [joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>] - -* Returning false from before_destroy should cancel the action. #1829 [Jeremy Huffman] - -* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 [mat <mat@absolight.fr>] - -* Extensive documentation for the abstract database adapter. #2250 [François Beausoleil <fbeausoleil@ftml.net>] - -* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 [jay@jay.fm, Blair Zajac <blair@orcaware.com>] - -* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 [Manuel Holtgrewe <purestorm@ggnore.net>] - -* Make update_attribute use the same writer method that update_attributes uses. - #2237 [trevor@protocool.com] - -* Make migrations honor table name prefixes and suffixes. #2298 [Jakob Skjerning, Marcel Molina Jr.] - -* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 [dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org] - -* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 [chris@chrisbrinker.com] - -* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) - -* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: - - ActiveRecord::Base.observers = :cacher, :garbage_collector - -* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 [solo@gatelys.com] - -* Wrap :conditions in parentheses to prevent problems with OR's #1871 [Jamis Buck] - -* Allow the postgresql adapter to work with the SchemaDumper. [Jamis Buck] - -* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. [Jamis Buck] - -* Fixed migrations for Windows when using more than 10 [David Naseby] - -* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 [Florian Weber] - -* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 [Tobias Lütke] - -* Improved migrations' behavior when the schema_info table is empty. [Nicholas Seckar] - -* Fixed that Observers didn't observe sub-classes #627 [Florian Weber] - -* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 [Marcel Molina Jr.] - -* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 [skae] - -* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 [Florian Weber] - -* Added better exception error when unknown column types are used with migrations #1814 [François Beausoleil] - -* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 [kajism@yahoo.com] - -* Fixed comparison of Active Record objects so two new objects are not equal #2099 [deberg] - -* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 [Tom Ward] - -* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 [coffee2code] - -* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 [sd@notso.net] - -* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ - -* Make sure the schema_info table is created before querying the current version #1903 - -* Fixtures ignore table name prefix and suffix #1987 [Jakob Skjerning] - -* Add documentation for index_type argument to add_index method for migrations #2005 [Blaine] - -* Modify read_attribute to allow a symbol argument #2024 [Ken Kunz] - -* Make destroy return self #1913 [Sebastian Kanthak] - -* Fix typo in validations documentation #1938 [court3nay] - -* Make acts_as_list work for insert_at(1) #1966 [hensleyl@papermountain.org] - -* Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky] - -* Allow add_column and create_table to specify NOT NULL #1712 [emptysands@gmail.com] - -* Fix create_table so that id column is implicitly added [Rick Olson] - -* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 - -* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 - -* Fixed the handling of camelCase columns names in Oracle #1798 - -* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 - -* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 - -* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 [Tobias Lütke] - - class Comment < AR:B - def self.search(q) - find(:all, :conditions => ["body = ?", q]) - end - end - - class Post < AR:B - has_many :comments - end - - Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' - - NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as - by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on - details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself - noticed :) - -* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 [Sam Stephenson] - -* Remove extra definition of supports_migrations? from abstract_adaptor.rb [Nicholas Seckar] - -* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions - -* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 [Maik Schmidt] - -* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 [Stefan Kaes] - - -*1.11.1* (11 July, 2005) - -* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 [Rick Olson] - -* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 [tyler@kianta.com] - -* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 [Sam Stephenson] - -* Correct reflected table name for singular associations. #1688 [court3nay] - -* Fixed optimistic locking with SQL Server #1660 [tom@popdog.net] - -* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current - -* Added better error message for "packets out of order" #1630 [court3nay] - -* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 - - -*1.11.0* (6 July, 2005) - -* Fixed that Yaml error message in fixtures hid the real error #1623 [Nicholas Seckar] - -* Changed logging of SQL statements to use the DEBUG level instead of INFO - -* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. - -* Added callback hooks to association collections #1549 [Florian Weber]. Example: - - class Project - has_and_belongs_to_many :developers, :before_add => :evaluate_velocity - - def evaluate_velocity(developer) - ... - end - end - - ..raising an exception will cause the object not to be added (or removed, with before_remove). - - -* Fixed Base.content_columns call for SQL Server adapter #1450 [DeLynn Berry] - -* Fixed Base#write_attribute to work with both symbols and strings #1190 [Paul Legato] - -* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 [Florian Weber] - -* Speed up ActiveRecord#method_missing for the common case (read_attribute). - -* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 [Stefan Kaes] - -* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 [Chris McGrath] - -* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 [raidel@onemail.at] - -* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 [Michael Schuerig] - -* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 [DeLynn Berry] - -* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 [Mark Imbriaco/DeLynn Berry] - -* Fixed that multiparameter posts ignored attr_protected #1532 [alec+rails@veryclever.net] - -* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 [flash@vanklinkenbergsoftware.nl] - -* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: - - Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' - - ...should instead be: - - Developer.find( - :all, - :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', - :conditions => 'project_id=1' - ) - -* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 [Marcel Molina Jr.] - -* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 [cluon] - -* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 - -* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 [Alisdair McDiarmid] - -* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice - -* Allow any Enumerable, not just Array, to work as bind variables #1344 [Jeremy Kemper] - -* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. - Example: - - david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] - david.save - - If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new - project is saved when david.save is called. - - Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: - - david.project_ids = [1, 5, 7] - -* Corrected typo in find SQL for has_and_belongs_to_many. #1312 [ben@bensinclair.com] - -* Fixed sanitized conditions for has_many finder method. #1281 [jackc@hylesanderson.com, pragdave, Tobias Lütke] - -* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 [dave@cherryville.org] - -* Corrected @@configurations typo #1410 [david@ruppconsulting.com] - -* Return PostgreSQL columns in the order they were declared #1374 [perlguy@gmail.com] - -* Allow before/after update hooks to work on models using optimistic locking - -* Eager loading of dependent has_one associations won't delete the association #1212 - -* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. - -* Using transactional fixtures now causes the data to be loaded only once. - -* Added fixture accessor methods that can be used when instantiated fixtures are disabled. - - fixtures :web_sites - - def test_something - assert_equal "Ruby on Rails", web_sites(:rubyonrails).name - end - -* Added DoubleRenderError exception that'll be raised if render* is called twice #518 [Nicholas Seckar] - -* Fixed exceptions occuring after render has been called #1096 [Nicholas Seckar] - -* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 - -* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead - -* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: - - Conditional validations such as the following are made possible: - validates_numericality_of :income, :if => :employed? - - Conditional validations can also solve the salted login generator problem: - validates_confirmation_of :password, :if => :new_password? - - Using blocks: - validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } - -* Fixed use of construct_finder_sql when using :join #1288 [dwlt@dwlt.net] - -* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 [Rick Olson] - -* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 [Jeremy Kemper] - -* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. - -* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. - -* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: - - # SELECT * FROM topics WHERE title IN ('First', 'Second') - Topic.find_all_by_title(["First", "Second"]) - -* Added compatibility with camelCase column names for dynamic finders #533 [Dee Zsombor] - -* Fixed extraneous comma in count() function that made it not work with joins #1156 [Jarkko Laine/Dee Zsombor] - -* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 [Alisdair McDiarmid] - -* Fixed that validate_length_of lost :on option when :within was specified #1195 [jhosteny@mac.com] - -* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: - - development: - adapter: postgresql - database: rails_development - host: localhost - username: postgres - password: - encoding: UTF8 - min_messages: ERROR - -* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 [Jamis Buck] - -* Added validates_exclusion_of as a negative of validates_inclusion_of - -* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls - - -*1.10.1* (20th April, 2005) - -* Fixed frivilous database queries being triggered with eager loading on empty associations and other things - -* Fixed order of loading in eager associations - -* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 - - -*1.10.0* (19th April, 2005) - -* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: - - for post in Post.find(:all, :limit => 100) - puts "Post: " + post.title - puts "Written by: " + post.author.name - puts "Last comment on: " + post.comments.first.created_on - end - - This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: - - for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) - - ...and the number of database queries needed is now 1. - -* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: - - Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(:first, :order => "created_on DESC", :offset => 5) - Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) - Person.find(:all, :offset => 10, :limit => 10) - -* Added acts_as_nested_set #1000 [wschenk]. Introduction: - - This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with - the added feature that you can select the children and all of it's descendants with - a single query. A good use case for this is a threaded post system, where you want - to display every reply to a comment without multiple selects. - -* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid [Dave Thomas] - -* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 [gnuman1@gmail.com] - -* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 [andrew.john.peters@gmail.com] - -* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 [stephenh@chase3000.com] - -* Fixed page caching for non-vhost applications living underneath the root #1004 [Ben Schumacher] - -* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 [adelle] - -* Added the option to specify the acceptance string in validates_acceptance_of #1106 [caleb@aei-tech.com] - -* Added insert_at(position) to acts_as_list #1083 [DeLynnB] - -* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) - -* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 [yon@milliped.com] - -* Fixed boolean saving on Oracle #1093 [mparrish@pearware.org] - -* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 - -* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 [Leon Bredt] - -* Added quoting of column names for fixtures #997 [jcfischer@gmail.com] - -* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 [Caleb Tennis] - -* Fixed that benchmarking times for rendering included db runtimes #987 [Stefan Kaes] - -* Fixed boolean queries for t/f fields in PostgreSQL #995 [dave@cherryville.org] - -* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 [Jeremy Kemper] - -* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 [dave@cherryville.org] - -* Fixed Base.silence/benchmark to only log if a logger has been configured #986 [Stefan Kaes] - -* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 [Stefan Kaes] - -* Fixed bug in Base#hash method that would treat records with the same string-based id as different [Dave Thomas] - -* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) - - -*1.9.1* (27th March, 2005) - -* Fixed that Active Record objects with float attribute could not be cloned #808 - -* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 [Nicholas Seckar] - -* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count - -* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 [Scott Barron] - -* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 [delynnb] - - -*1.9.0* (22th March, 2005) - -* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: - - Developer.find_all nil, 'id ASC', 5 # return the first five developers - Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward - - This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. - -* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 [Nicholas Seckar/Sam Stephenson] - -* Improved the performance of the OCI8 adapter for Oracle #723 [pilx/gjenkins] - -* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 [dave@cherryville.org] - -* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 [mindel] - -* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 [Alisdair McDiarmid] - -* Added the possibility of specifying fixtures in multiple calls #816 [kim@tinker.com] - -* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 [stian@grytoyr.net] - -* Added optionally allow for nil or empty strings with validates_numericality_of #801 [Sebastian Kanthak] - -* Fixed problem with using slashes in validates_format_of regular expressions #801 [Sebastian Kanthak] - -* Fixed that SQLite3 exceptions are caught and reported properly #823 [yerejm] - -* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself - -* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) - - -*1.8.0* (7th March, 2005) - -* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) - -* Added support for timestamp with time zone in PostgreSQL #560 [Scott Barron] - -* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: - - * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the - +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ - objects that should be inspected to determine which attributes triggered the errors. - * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. - You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. - -* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 [rodrigo k] - -* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 [Jeremy Kemper] - -* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: - - class Account < ActiveRecord::Base - has_one :credit_card, :dependent => true - end - class CreditCard < ActiveRecord::Base - belongs_to :account - end - - account.credit_card # => returns existing credit card, lets say id = 12 - account.credit_card = CreditCard.create("number" => "123") - account.save # => CC with id = 12 is destroyed - - -* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: - - Validates whether the value of the specified attribute is numeric by trying to convert it to - a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression - <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). - - class Person < ActiveRecord::Base - validates_numericality_of :value, :on => :create - end - - Configuration options: - * <tt>message</tt> - A custom error message (default is: "is not a number") - * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) - * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) - - -* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 [Scott Barron] - -* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) - -* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 [james@slashetc.com] - - -*1.7.0* (24th February, 2005) - -* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 [Jamis Buck] - -* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: - - 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple - and safe way of passing table-specific sequence information to the adapter.) - 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to - resort to some hacks to get data converted to Date or Time in Ruby. - If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the - hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. - This is nasty - but if you use Duck Typing you'll probably not care very much. - In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is - valid - too many databases use DATE for both. - Timezones and sub-second precision on timestamps are not supported. - 3. Default values that are functions (such as "SYSDATE") are not supported. This is a - restriction of the way active record supports default values. - 4. Referential integrity constraints are not fully supported. Under at least - some circumstances, active record appears to delete parent and child records out of - sequence and out of transaction scope. (Or this may just be a problem of test setup.) - - The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ - -* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 [YuriSchimke] - -* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 [yerejm] - -* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 [tonka] - -* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 [Nicholas Seckar] - -* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 [daniel@nightrunner.com] - -* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 [adelle@bullet.net.au] - -* Fixed that find_by_* would fail when column names had numbers #670 [demetrius] - -* Fixed the SQL Server adapter on a bunch of issues #667 [DeLynn] - - 1. Created a new columns method that is much cleaner. - 2. Corrected a problem with the select and select_all methods - that didn't account for the LIMIT clause being passed into raw SQL statements. - 3. Implemented the string_to_time method in order to create proper instances of the time class. - 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. - 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. - -* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 [lmarlow] - -* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: - - class Person < ActiveRecord::Base - validates_each :first_name, :last_name do |record, attr| - record.errors.add attr, 'starts with z.' if attr[0] == ?z - end - end - -* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 [Jeremy Kemper] - -* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: - - class Person < ActiveRecord::Base - validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } - end - -* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 [Tim Bates] - -* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: - - class Project < ActiveRecord::Base - primary_key "sysid" - table_name "XYZ_PROJECT" - inheritance_column { original_inheritance_column + "_id" } - end - -* Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu] - - -*1.6.0* (January 25th, 2005) - -* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. - -* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 - -* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. - -* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example - - people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } - Person.update(people.keys, people.values) - -* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 [Scott Baron] - -* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 [notahat] - -* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 [Demetrius] - -* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 [Jeremy Kemper] - -* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 [Eric Anderson] - -* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 [Eric Anderson] - -* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not - -* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription - -* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 [Demetrius] - -* Fixed that find_all would produce invalid sql when called sequentialy #490 [Scott Baron] - - -*1.5.1* (January 18th, 2005) - -* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 [Tim Bates] - -* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 [Pelle] - - -*1.5.0* (January 17th, 2005) - -* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 [Eric Hodel] - -* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: - - class Book < ActiveRecord::Base - has_many :pages - belongs_to :library - - validates_associated :pages, :library - end - -* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: - - == Unsaved objects and associations - - You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be - aware of, mostly involving the saving of associated objects. - - === One-to-one associations - - * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in - order to update their primary keys - except if the parent object is unsaved (new_record? == true). - * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment - is cancelled. - * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). - * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does - not save the parent either. - - === Collections - - * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object - (the owner of the collection) is not yet stored in the database. - * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. - * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). - * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. - -* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 [Tim Bates] - -* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 [Tim Bates] - -* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 [Tim Bates] - -* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 [Tim Bates] - -* Fixed binary support for PostgreSQL #444 [alex@byzantine.no] - -* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the - collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If - it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, - it'll take one less SELECT query if you use length. - -* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 [atyp.de] - -* Fixed that foreign keys named the same as the association would cause stack overflow #437 [Eric Anderson] - -* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 [Alexey] - -* Added Base#reload that reloads the attributes of an object from the database #422 [Andreas Schwarz] - -* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 [Jeremy Kemper] - -* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 [Matt Mower] - -* Added that Observers can use the observes class method instead of overwriting self.observed_class(). - - Before: - class ListSweeper < ActiveRecord::Base - def self.observed_class() [ List, Item ] - end - - After: - class ListSweeper < ActiveRecord::Base - observes List, Item - end - -* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is - -* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name - -* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. - - Before: topic.update_attribute(:approved, !approved?) - After : topic.toggle!(:approved) - -* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: - - page.views # => 1 - page.increment!(:views) # executes an UPDATE statement - page.views # => 2 - - page.increment(:views).increment!(:views) - page.views # => 4 - -* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. - - -*1.4.0* (January 4th, 2005) - -* Added automated optimistic locking if the field <tt>lock_version</tt> is present. Each update to the - record increments the lock_version column and the locking facilities ensure that records instantiated twice - will let the last one saved raise a StaleObjectError if the first was also updated. Example: - - p1 = Person.find(1) - p2 = Person.find(1) - - p1.first_name = "Michael" - p1.save - - p2.first_name = "should fail" - p2.save # Raises a ActiveRecord::StaleObjectError - - You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, - or otherwise apply the business logic needed to resolve the conflict. - - #384 [Michael Koziarski] - -* Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL. - They work by appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name, - Payment.find_by_transaction_id</tt>. So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do - <tt>Person.find_by_user_name(user_name)</tt>. - - It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like - <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing - <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do - <tt>Person.find_by_user_name_and_password(user_name, password)</tt>. - - While primarily a construct for easier find_firsts, it can also be used as a construct for find_all by using calls like - <tt>Payment.find_all_by_amount(50)</tt> that is turned into <tt>Payment.find_all(["amount = ?", 50])</tt>. This is something not as equally useful, - though, as it's not possible to specify the order in which the objects are returned. - -* Added block-style for callbacks #332 [Jeremy Kemper]. - - Before: - before_destroy(Proc.new{ |record| Person.destroy_all "firm_id = #{record.id}" }) - - After: - before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" } - -* Added :counter_cache option to acts_as_tree that works just like the one you can define on belongs_to #371 [Josh Peek] - -* Added Base.default_timezone accessor that determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates - and times from the database. This is set to :local by default. - -* Added the possibility for adapters to overwrite add_limit! to implement a different limiting scheme than "LIMIT X" used by MySQL, PostgreSQL, and SQLite. - -* Added the possibility of having objects with acts_as_list created before their scope is available or... - -* Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://raa.ruby-lang.org/project/ruby-db2/) #386 [Maik Schmidt] - -* Added the final touches to the Microsoft SQL Server adapter by Joey Gibson that makes it suitable for actual use #394 [DeLynn Barry] - -* Added that Base#find takes an optional options hash, including :conditions. Base#find_on_conditions deprecated in favor of #find with :conditions #407 [Jeremy Kemper] - -* Added HasManyAssociation#count that works like Base#count #413 [intinig] - -* Fixed handling of binary content in blobs and similar fields for Ruby/MySQL and SQLite #409 [xal] - -* Fixed a bug in the Ruby/MySQL that caused binary content to be escaped badly and come back mangled #405 [Tobias Lütke] - -* Fixed that the const_missing autoload assumes the requested constant is set by require_association and calls const_get to retrieve it. - If require_association did not set the constant then const_get will call const_missing, resulting in an infinite loop #380 [Jeremy Kemper] - -* Fixed broken transactions that were actually only running object-level and not db level transactions [andreas] - -* Fixed that validates_uniqueness_of used 'id' instead of defined primary key #406 - -* Fixed that the overwritten respond_to? method didn't take two parameters like the original #391 - -* Fixed quoting in validates_format_of that would allow some rules to pass regardless of input #390 [Dmitry V. Sabanin] - - -*1.3.0* (December 23, 2004) - -* Added a require_association hook on const_missing that makes it possible to use any model class without requiring it first. This makes STI look like: - - before: - require_association 'person' - class Employee < Person - end - - after: - class Employee < Person - end - - This also reduces the usefulness of Controller.model in Action Pack to currently only being for documentation purposes. - -* Added that Base.update_all and Base.delete_all return an integer of the number of affected rows #341 - -* Added scope option to validation_uniqueness #349 [Kent Sibilev] - -* Added respondence to *_before_type_cast for all attributes to return their string-state before they were type casted by the column type. - This is helpful for getting "100,000" back on a integer-based validation where the value would normally be "100". - -* Added allow_nil options to validates_inclusion_of so that validation is only triggered if the attribute is not nil [what-a-day] - -* Added work-around for PostgreSQL and the problem of getting fixtures to be created from id 1 on each test case. - This only works for auto-incrementing primary keys called "id" for now #359 [Scott Baron] - -* Added Base#clear_association_cache to empty all the cached associations #347 [Tobias Lütke] - -* Added more informative exceptions in establish_connection #356 [Jeremy Kemper] - -* Added Base#update_attributes that'll accept a hash of attributes and save the record (returning true if it passed validation, false otherwise). - - Before: - person.attributes = @params["person"] - person.save - - Now: - person.update_attributes(@params["person"]) - -* Added Base.destroy and Base.delete to remove records without holding a reference to them first. - -* Added that query benchmarking will only happen if its going to be logged anyway #344 - -* Added higher_item and lower_item as public methods for acts_as_list #342 [Tobias Lütke] - -* Fixed that options[:counter_sql] was overwritten with interpolated sql rather than original sql #355 [Jeremy Kemper] - -* Fixed that overriding an attribute's accessor would be disregarded by add_on_empty and add_on_boundary_breaking because they simply used - the attributes[] hash instead of checking for @base.respond_to?(attr.to_s). [Marten] - -* Fixed that Base.table_name would expect a parameter when used in has_and_belongs_to_many joins [Anna Lissa Cruz] - -* Fixed that nested transactions now work by letting the outer most transaction have the responsibilty of starting and rolling back the transaction. - If any of the inner transactions swallow the exception raised, though, the transaction will not be rolled back. So always let the transaction - bubble up even when you've dealt with local issues. Closes #231 and #340. - -* Fixed validates_{confirmation,acceptance}_of to only happen when the virtual attributes are not nil #348 [dpiddy@gmail.com] - -* Changed the interface on AbstractAdapter to require that adapters return the number of affected rows on delete and update operations. - -* Fixed the automated timestamping feature when running under Rails' development environment that resets the inheritable attributes on each request. - - - -*1.2.0* - -* Added Base.validates_inclusion_of that validates whether the value of the specified attribute is available in a particular enumerable - object. [what-a-day] - - class Person < ActiveRecord::Base - validates_inclusion_of :gender, :in=>%w( m f ), :message=>"woah! what are you then!??!!" - validates_inclusion_of :age, :in=>0..99 - end - -* Added acts_as_list that can decorates an existing class with methods like move_higher/lower, move_to_top/bottom. [Tobias Lütke] Example: - - class TodoItem < ActiveRecord::Base - acts_as_list :scope => :todo_list_id - belongs_to :todo_list - end - -* Added acts_as_tree that can decorates an existing class with a many to many relationship with itself. Perfect for categories in - categories and the likes. [Tobias Lütke] - -* Added that Active Records will automatically record creation and/or update timestamps of database objects if fields of the names - created_at/created_on or updated_at/updated_on are present. [Tobias Lütke] - -* Added Base.default_error_messages as a hash of all the error messages used in the validates_*_of so they can be changed in one place [Tobias Lütke] - -* Added automatic transaction block around AssociationCollection.<<, AssociationCollection.delete, and AssociationCollection.destroy_all - -* Fixed that Base#find will return an array if given an array -- regardless of the number of elements #270 [Marten] - -* Fixed that has_and_belongs_to_many would generate bad sql when naming conventions differed from using vanilla "id" everywhere [RedTerror] - -* Added a better exception for when a type column is used in a table without the intention of triggering single-table inheritance. Example: - - ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'bad_class!'. - This error is raised because the column 'type' is reserved for storing the class in case of inheritance. - Please rename this column if you didn't intend it to be used for storing the inheritance class or - overwrite Company.inheritance_column to use another column for that information. - -* Added that single-table inheritance will only kick in if the inheritance_column (by default "type") is present. Otherwise, inheritance won't - have any magic side effects. - -* Added the possibility of marking fields as being in error without adding a message (using nil) to it that'll get displayed wth full_messages #208 [mjobin] - -* Fixed Base.errors to be indifferent as to whether strings or symbols are used. Examples: - - Before: - errors.add(:name, "must be shorter") if name.size > 10 - errors.on(:name) # => "must be shorter" - errors.on("name") # => nil - - After: - errors.add(:name, "must be shorter") if name.size > 10 - errors.on(:name) # => "must be shorter" - errors.on("name") # => "must be shorter" - -* Added Base.validates_format_of that Validates whether the value of the specified attribute is of the correct form by matching - it against the regular expression provided. [Marcel Molina Jr.] - - class Person < ActiveRecord::Base - validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :on => :create - end - -* Added Base.validates_length_of that delegates to add_on_boundary_breaking #312 [Tobias Lütke]. Example: - - Validates that the specified attribute matches the length restrictions supplied in either: - - - configuration[:minimum] - - configuration[:maximum] - - configuration[:is] - - configuration[:within] (aka. configuration[:in]) - - Only one option can be used at a time. - - class Person < ActiveRecord::Base - validates_length_of :first_name, :maximum=>30 - validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind" - validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name" - validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character" - validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me." - end - -* Added Base.validate_presence as an alternative to implementing validate and doing errors.add_on_empty yourself. - -* Added Base.validates_uniqueness_of that alidates whether the value of the specified attributes are unique across the system. - Useful for making sure that only one user can be named "davidhh". - - class Person < ActiveRecord::Base - validates_uniqueness_of :user_name - end - - When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified - attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself. - - -* Added Base.validates_confirmation_of that encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example: - - Model: - class Person < ActiveRecord::Base - validates_confirmation_of :password - end - - View: - <%= password_field "person", "password" %> - <%= password_field "person", "password_confirmation" %> - - The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual. - It exists only as an in-memory variable for validating the password. This check is performed both on create and update. - - -* Added Base.validates_acceptance_of that encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example: - - class Person < ActiveRecord::Base - validates_acceptance_of :terms_of_service - end - - The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed both on create and update. - - NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox. - - -* Added validation macros to make the stackable just like the life cycle callbacks. Examples: - - class Person < ActiveRecord::Base - validate { |record| record.errors.add("name", "too short") unless name.size > 10 } - validate { |record| record.errors.add("name", "too long") unless name.size < 20 } - validate_on_create :validate_password - - private - def validate_password - errors.add("password", "too short") unless password.size > 6 - end - end - -* Added the option for sanitizing find_by_sql and the offset parts in regular finds [Sam Stephenson]. Examples: - - Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20] - Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date] - -* Fixed value quoting in all generated SQL statements, so that integers are not surrounded in quotes and that all sanitation are happening - through the database's own quoting routine. This should hopefully make it lots easier for new adapters that doesn't accept '1' for integer - columns. - -* Fixed has_and_belongs_to_many guessing of foreign key so that keys are generated correctly for models like SomeVerySpecialClient - [Florian Weber] - -* Added counter_sql option for has_many associations [Jeremy Kemper]. Documentation: - - <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is - specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM. - -* Fixed that methods wrapped in callbacks still return their original result #260 [Jeremy Kemper] - -* Fixed the Inflector to handle the movie/movies pair correctly #261 [Scott Baron] - -* Added named bind-style variable interpolation #281 [Michael Koziarski]. Example: - - Person.find(["id = :id and first_name = :first_name", { :id => 5, :first_name = "bob' or 1=1" }]) - -* Added bind-style variable interpolation for the condition arrays that uses the adapter's quote method [Michael Koziarski] - - Before: - find_first([ "user_name = '%s' AND password = '%s'", user_name, password ])] - find_first([ "firm_id = %s", firm_id ])] # unsafe! - - After: - find_first([ "user_name = ? AND password = ?", user_name, password ])] - find_first([ "firm_id = ?", firm_id ])] - -* Added CSV format for fixtures #272 [what-a-day]. (See the new and expanded documentation on fixtures for more information) - -* Fixed fixtures using primary key fields called something else than "id" [dave] - -* Added proper handling of time fields that are turned into Time objects with the dummy date of 2000/1/1 [HariSeldon] - -* Added reverse order of deleting fixtures, so referential keys can be maintained #247 [Tim Bates] - -* Added relative path search for sqlite dbfiles in database.yml (if RAILS_ROOT is defined) #233 [Jeremy Kemper] - -* Added option to establish_connection where you'll be able to leave out the parameter to have it use the RAILS_ENV environment variable - -* Fixed problems with primary keys and postgresql sequences (#230) [Tim Bates] - -* Added reloading for associations under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development. - This is turned on by default, but can be turned off with ActiveRecord::Base.reload_dependencies = false in production environments. - - NOTE: This will only have an effect if you let the associations manage the requiring of model classes. All libraries loaded through - require will be "forever" cached. You can, however, use ActiveRecord::Base.load_or_require("library") to get this behavior outside of the - auto-loading associations. - -* Added ERB capabilities to the fixture files for dynamic fixture generation. You don't need to do anything, just include ERB blocks like: - - david: - id: 1 - name: David - - jamis: - id: 2 - name: Jamis - - <% for digit in 3..10 %> - dev_<%= digit %>: - id: <%= digit %> - name: fixture_<%= digit %> - <% end %> - -* Changed the yaml fixture searcher to look in the root of the fixtures directory, so when you before could have something like: - - fixtures/developers/fixtures.yaml - fixtures/accounts/fixtures.yaml - - ...you now need to do: - - fixtures/developers.yaml - fixtures/accounts.yaml - -* Changed the fixture format from: - - name: david - data: - id: 1 - name: David Heinemeier Hansson - birthday: 1979-10-15 - profession: Systems development - --- - name: steve - data: - id: 2 - name: Steve Ross Kellock - birthday: 1974-09-27 - profession: guy with keyboard - - ...to: - - david: - id: 1 - name: David Heinemeier Hansson - birthday: 1979-10-15 - profession: Systems development - - steve: - id: 2 - name: Steve Ross Kellock - birthday: 1974-09-27 - profession: guy with keyboard - - The change is NOT backwards compatible. Fixtures written in the old YAML style needs to be rewritten! - -* All associations will now attempt to require the classes that they associate to. Relieving the need for most explicit 'require' statements. - - -*1.1.0* (34) - -* Added automatic fixture setup and instance variable availability. Fixtures can also be automatically - instantiated in instance variables relating to their names using the following style: - - class FixturesTest < Test::Unit::TestCase - fixtures :developers # you can add more with comma separation - - def test_developers - assert_equal 3, @developers.size # the container for all the fixtures is automatically set - assert_kind_of Developer, @david # works like @developers["david"].find - assert_equal "David Heinemeier Hansson", @david.name - end - end - -* Added HasAndBelongsToManyAssociation#push_with_attributes(object, join_attributes) that can create associations in the join table with additional - attributes. This is really useful when you have information that's only relevant to the join itself, such as a "added_on" column for an association - between post and category. The added attributes will automatically be injected into objects retrieved through the association similar to the piggy-back - approach: - - post.categories.push_with_attributes(category, :added_on => Date.today) - post.categories.first.added_on # => Date.today - - NOTE: The categories table doesn't have a added_on column, it's the categories_post join table that does! - -* Fixed that :exclusively_dependent and :dependent can't be activated at the same time on has_many associations [Jeremy Kemper] - -* Fixed that database passwords couldn't be all numeric [Jeremy Kemper] - -* Fixed that calling id would create the instance variable for new_records preventing them from being saved correctly [Jeremy Kemper] - -* Added sanitization feature to HasManyAssociation#find_all so it works just like Base.find_all [Sam Stephenson/Jeremy Kemper] - -* Added that you can pass overlapping ids to find without getting duplicated records back [Jeremy Kemper] - -* Added that Base.benchmark returns the result of the block [Jeremy Kemper] - -* Fixed problem with unit tests on Windows with SQLite [paterno] - -* Fixed that quotes would break regular non-yaml fixtures [Dmitry Sabanin/daft] - -* Fixed fixtures on windows with line endings cause problems under unix / mac [Tobias Lütke] - -* Added HasAndBelongsToManyAssociation#find(id) that'll search inside the collection and find the object or record with that id - -* Added :conditions option to has_and_belongs_to_many that works just like the one on all the other associations - -* Added AssociationCollection#clear to remove all associations from has_many and has_and_belongs_to_many associations without destroying the records [geech] - -* Added type-checking and remove in 1-instead-of-N sql statements to AssociationCollection#delete [geech] - -* Added a return of self to AssociationCollection#<< so appending can be chained, like project << Milestone.create << Milestone.create [geech] - -* Added Base#hash and Base#eql? which means that all of the equality using features of array and other containers now works: - - [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] - -* Added :uniq as an option to has_and_belongs_to_many which will automatically ensure that AssociateCollection#uniq is called - before pulling records out of the association. This is especially useful for three-way (and above) has_and_belongs_to_many associations. - -* Added AssociateCollection#uniq which is especially useful for has_and_belongs_to_many associations that can include duplicates, - which is common on associations that also use metadata. Usage: post.categories.uniq - -* Fixed respond_to? to use a subclass specific hash instead of an Active Record-wide one - -* Fixed has_and_belongs_to_many to treat associations between classes in modules properly [Florian Weber] - -* Added a NoMethod exception to be raised when query and writer methods are called for attributes that doesn't exist [geech] - -* Added a more robust version of Fixtures that throws meaningful errors when on formatting issues [geech] - -* Added Base#transaction as a compliment to Base.transaction for prettier use in instance methods [geech] - -* Improved the speed of respond_to? by placing the dynamic methods lookup table in a hash [geech] - -* Added that any additional fields added to the join table in a has_and_belongs_to_many association - will be placed as attributes when pulling records out through has_and_belongs_to_many associations. - This is helpful when have information about the association itself that you want available on retrival. - -* Added better loading exception catching and RubyGems retries to the database adapters [alexeyv] - -* Fixed bug with per-model transactions [daniel] - -* Fixed Base#transaction so that it returns the result of the last expression in the transaction block [alexeyv] - -* Added Fixture#find to find the record corresponding to the fixture id. The record - class name is guessed by using Inflector#classify (also new) on the fixture directory name. - - Before: Document.find(@documents["first"]["id"]) - After : @documents["first"].find - -* Fixed that the table name part of column names ("TABLE.COLUMN") wasn't removed properly [Andreas Schwarz] - -* Fixed a bug with Base#size when a finder_sql was used that didn't capitalize SELECT and FROM [geech] - -* Fixed quoting problems on SQLite by adding quote_string to the AbstractAdapter that can be overwritten by the concrete - adapters for a call to the dbm. [Andreas Schwarz] - -* Removed RubyGems backup strategy for requiring SQLite-adapter -- if people want to use gems, they're already doing it with AR. - - -*1.0.0 (35)* - -* Added OO-style associations methods [Florian Weber]. Examples: - - Project#milestones_count => Project#milestones.size - Project#build_to_milestones => Project#milestones.build - Project#create_for_milestones => Project#milestones.create - Project#find_in_milestones => Project#milestones.find - Project#find_all_in_milestones => Project#milestones.find_all - -* Added serialize as a new class method to control when text attributes should be YAMLized or not. This means that automated - serialization of hashes, arrays, and so on WILL NO LONGER HAPPEN (#10). You need to do something like this: - - class User < ActiveRecord::Base - serialize :settings - end - - This will assume that settings is a text column and will now YAMLize any object put in that attribute. You can also specify - an optional :class_name option that'll raise an exception if a serialized object is retrieved as a descendant of a class not in - the hierarchy. Example: - - class User < ActiveRecord::Base - serialize :settings, :class_name => "Hash" - end - - user = User.create("settings" => %w( one two three )) - User.find(user.id).settings # => raises SerializationTypeMismatch - -* Added the option to connect to a different database for one model at a time. Just call establish_connection on the class - you want to have connected to another database than Base. This will automatically also connect decendents of that class - to the different database [Renald Buter]. - -* Added transactional protection for Base#save. Validations can now check for values knowing that it happens in a transaction and callbacks - can raise exceptions knowing that the save will be rolled back. [Suggested by Alexey Verkhovsky] - -* Added column name quoting so reserved words, such as "references", can be used as column names [Ryan Platte] - -* Added the possibility to chain the return of what happened inside a logged block [geech]: - - This now works: - log { ... }.map { ... } - - Instead of doing: - result = [] - log { result = ... } - result.map { ... } - -* Added "socket" option for the MySQL adapter, so you can change it to something else than "/tmp/mysql.sock" [Anna Lissa Cruz] - -* Added respond_to? answers for all the attribute methods. So if Person has a name attribute retrieved from the table schema, - person.respond_to? "name" will return true. - -* Added Base.benchmark which can be used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block. - Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all): - - Project.benchmark("Creating project") do - project = Project.create("name" => "stuff") - project.create_manager("name" => "David") - project.milestones << Milestone.find_all - end - -* Added logging of invalid SQL statements [Daniel Von Fange] - -* Added alias Errors#[] for Errors#on, so you can now say person.errors["name"] to retrieve the errors for name [Andreas Schwarz] - -* Added RubyGems require attempt if sqlite-ruby is not available through regular methods. - -* Added compatibility with 2.x series of sqlite-ruby drivers. [Jamis Buck] - -* Added type safety for association assignments, so a ActiveRecord::AssociationTypeMismatch will be raised if you attempt to - assign an object that's not of the associated class. This cures the problem with nil giving id = 4 and fixnums giving id = 1 on - mistaken association assignments. [Reported by Andreas Schwarz] - -* Added the option to keep many fixtures in one single YAML document [what-a-day] - -* Added the class method "inheritance_column" that can be overwritten to return the name of an alternative column than "type" for storing - the type for inheritance hierarchies. [Dave Steinberg] - -* Added [] and []= as an alternative way to access attributes when the regular methods have been overwritten [Dave Steinberg] - -* Added the option to observer more than one class at the time by specifying observed_class as an array - -* Added auto-id propagation support for tables with arbitrary primary keys that have autogenerated sequences associated with them - on PostgreSQL. [Dave Steinberg] - -* Changed that integer and floats set to "" through attributes= remain as NULL. This was especially a problem for scaffolding and postgresql. (#49) - -* Changed the MySQL Adapter to rely on MySQL for its defaults for socket, host, and port [Andreas Schwarz] - -* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue. - -* Changed class inheritable attributes to not use eval [Caio Chassot] - -* Changed Errors#add to now use "invalid" as the default message instead of true, which means full_messages work with those [Marcel Molina Jr.] - -* Fixed spelling on Base#add_on_boundry_breaking to Base#add_on_boundary_breaking (old naming still works) [Marcel Molina Jr.] - -* Fixed that entries in the has_and_belongs_to_many join table didn't get removed when an associated object was destroyed. - -* Fixed unnecessary calls to SET AUTOCOMMIT=0/1 for MySQL adapter [Andreas Schwarz] - -* Fixed PostgreSQL defaults are now handled gracefully [Dave Steinberg] - -* Fixed increment/decrement_counter are now atomic updates [Andreas Schwarz] - -* Fixed the problems the Inflector had turning Attachment into attuchments and Cases into Casis [radsaq/Florian Gross] - -* Fixed that cloned records would point attribute references on the parent object [Andreas Schwarz] - -* Fixed SQL for type call on inheritance hierarchies [Caio Chassot] - -* Fixed bug with typed inheritance [Florian Weber] - -* Fixed a bug where has_many collection_count wouldn't use the conditions specified for that association - - -*0.9.5* - -* Expanded the table_name guessing rules immensely [Florian Green]. Documentation: - - Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending - directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used - to guess the table name from even when called on Reply. The guessing rules are as follows: - * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table. - * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies", - so a Category class becomes a categories table. - * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table. - * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table. - * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table. - * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table. - * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table. - * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table. - * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table. - * Class name ends in an "s": No additional characters are added or removed. - * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table. - * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table. - Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended. - So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts". - - You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a - "mice" table. Example: - - class Mouse < ActiveRecord::Base - def self.table_name() "mice" end - end - - This conversion is now done through an external class called Inflector residing in lib/active_record/support/inflector.rb. - -* Added find_all_in_collection to has_many defined collections. Works like this: - - class Firm < ActiveRecord::Base - has_many :clients - end - - firm.id # => 1 - firm.find_all_in_clients "revenue > 1000" # SELECT * FROM clients WHERE firm_id = 1 AND revenue > 1000 - - [Requested by Dave Thomas] - -* Fixed finders for inheritance hierarchies deeper than one level [Florian Weber] - -* Added add_on_boundry_breaking to errors to accompany add_on_empty as a default validation method. It's used like this: - - class Person < ActiveRecord::Base - protected - def validation - errors.add_on_boundry_breaking "password", 3..20 - end - end - - This will add an error to the tune of "is too short (minimum is 3 characters)" or "is too long (minimum is 20 characters)" if - the password is outside the boundry. The messages can be changed by passing a third and forth parameter as message strings. - -* Implemented a clone method that works properly with AR. It returns a clone of the record that - hasn't been assigned an id yet and is treated as a new record. - -* Allow for domain sockets in PostgreSQL by not assuming localhost when no host is specified [Scott Barron] - -* Fixed that bignums are saved properly instead of attempted to be YAMLized [Andreas Schwartz] - -* Fixed a bug in the GEM where the rdoc options weren't being passed according to spec [Chad Fowler] - -* Fixed a bug with the exclusively_dependent option for has_many - - -*0.9.4* - -* Correctly guesses the primary key when the class is inside a module [Dave Steinberg]. - -* Added [] and []= as alternatives to read_attribute and write_attribute [Dave Steinberg] - -* has_and_belongs_to_many now accepts an :order key to determine in which order the collection is returned [radsaq]. - -* The ids passed to find and find_on_conditions are now automatically sanitized. - -* Added escaping of plings in YAML content. - -* Multi-parameter assigns where all the parameters are empty will now be set to nil instead of a new instance of their class. - -* Proper type within an inheritance hierarchy is now ensured already at object initialization (instead of first at create) - - -*0.9.3* - -* Fixed bug with using a different primary key name together with has_and_belongs_to_many [Investigation by Scott] - -* Added :exclusively_dependent option to the has_many association macro. The doc reads: - - If set to true all the associated object are deleted in one SQL statement without having their - before_destroy callback run. This should only be used on associations that depend solely on - this class and don't need to do any clean-up in before_destroy. The upside is that it's much - faster, especially if there's a counter_cache involved. - -* Added :port key to connection options, so the PostgreSQL and MySQL adapters can connect to a database server - running on another port than the default. - -* Converted the new natural singleton methods that prevented AR objects from being saved by PStore - (and hence be placed in a Rails session) to a module. [Florian Weber] - -* Fixed the use of floats (was broken since 0.9.0+) - -* Fixed PostgreSQL adapter so default values are displayed properly when used in conjunction with - Action Pack scaffolding. - -* Fixed booleans support for PostgreSQL (use real true/false on boolean fields instead of 0/1 on tinyints) [radsaq] - - -*0.9.2* - -* Added static method for instantly updating a record - -* Treat decimal and numeric as Ruby floats [Andreas Schwartz] - -* Treat chars as Ruby strings (fixes problem for Action Pack form helpers too) - -* Removed debugging output accidently left in (which would screw web applications) - - -*0.9.1* - -* Added MIT license - -* Added natural object-style assignment for has_and_belongs_to_many associations. Consider the following model: - - class Event < ActiveRecord::Base - has_one_and_belongs_to_many :sponsors - end - - class Sponsor < ActiveRecord::Base - has_one_and_belongs_to_many :sponsors - end - - Earlier, you'd have to use synthetic methods for creating associations between two objects of the above class: - - roskilde_festival.add_to_sponsors(carlsberg) - roskilde_festival.remove_from_sponsors(carlsberg) - - nike.add_to_events(world_cup) - nike.remove_from_events(world_cup) - - Now you can use regular array-styled methods: - - roskilde_festival.sponsors << carlsberg - roskilde_festival.sponsors.delete(carlsberg) - - nike.events << world_cup - nike.events.delete(world_cup) - -* Added delete method for has_many associations. Using this will nullify an association between the has_many and the belonging - object by setting the foreign key to null. Consider this model: - - class Post < ActiveRecord::Base - has_many :comments - end - - class Comment < ActiveRecord::Base - belongs_to :post - end - - You could do something like: - - funny_comment.has_post? # => true - announcement.comments.delete(funny_comment) - funny_comment.has_post? # => false - - -*0.9.0* - -* Active Record is now thread safe! (So you can use it with Cerise and WEBrick applications) - [Implementation idea by Michael Neumann, debugging assistance by Jamis Buck] - -* Improved performance by roughly 400% on a basic test case of pulling 100 records and querying one attribute. - This brings the tax for using Active Record instead of "riding on the metal" (using MySQL-ruby C-driver directly) down to ~50%. - Done by doing lazy type conversions and caching column information on the class-level. - -* Added callback objects and procs as options for implementing the target for callback macros. - -* Added "counter_cache" option to belongs_to that automates the usage of increment_counter and decrement_counter. Consider: - - class Post < ActiveRecord::Base - has_many :comments - end - - class Comment < ActiveRecord::Base - belongs_to :post - end - - Iterating over 100 posts like this: - - <% for post in @posts %> - <%= post.title %> has <%= post.comments_count %> comments - <% end %> - - Will generate 100 SQL count queries -- one for each call to post.comments_count. If you instead add a "comments_count" int column - to the posts table and rewrite the comments association macro with: - - class Comment < ActiveRecord::Base - belongs_to :post, :counter_cache => true - end - - Those 100 SQL count queries will be reduced to zero. Beware that counter caching is only appropriate for objects that begin life - with the object it's specified to belong with and is destroyed like that as well. Typically objects where you would also specify - :dependent => true. If your objects switch from one belonging to another (like a post that can be move from one category to another), - you'll have to manage the counter yourself. - -* Added natural object-style assignment for has_one and belongs_to associations. Consider the following model: - - class Project < ActiveRecord::Base - has_one :manager - end - - class Manager < ActiveRecord::Base - belongs_to :project - end - - Earlier, assignments would work like following regardless of which way the assignment told the best story: - - active_record.manager_id = david.id - - Now you can do it either from the belonging side: - - david.project = active_record - - ...or from the having side: - - active_record.manager = david - - If the assignment happens from the having side, the assigned object is automatically saved. So in the example above, the - project_id attribute on david would be set to the id of active_record, then david would be saved. - -* Added natural object-style assignment for has_many associations [Florian Weber]. Consider the following model: - - class Project < ActiveRecord::Base - has_many :milestones - end - - class Milestone < ActiveRecord::Base - belongs_to :project - end - - Earlier, assignments would work like following regardless of which way the assignment told the best story: - - deadline.project_id = active_record.id - - Now you can do it either from the belonging side: - - deadline.project = active_record - - ...or from the having side: - - active_record.milestones << deadline - - The milestone is automatically saved with the new foreign key. - -* API CHANGE: Attributes for text (or blob or similar) columns will now have unknown classes stored using YAML instead of using - to_s. (Known classes that won't be yamelized are: String, NilClass, TrueClass, FalseClass, Fixnum, Date, and Time). - Likewise, data pulled out of text-based attributes will be attempted converged using Yaml if they have the "--- " header. - This was primarily done to be enable the storage of hashes and arrays without wrapping them in aggregations, so now you can do: - - user = User.find(1) - user.preferences = { "background" => "black", "display" => large } - user.save - - User.find(1).preferences # => { "background" => "black", "display" => large } - - Please note that this method should only be used when you don't care about representing the object in proper columns in - the database. A money object consisting of an amount and a currency is still a much better fit for a value object done through - aggregations than this new option. - -* POSSIBLE CODE BREAKAGE: As a consequence of the lazy type conversions, it's a bad idea to reference the @attributes hash - directly (it always was, but now it's paramount that you don't). If you do, you won't get the type conversion. So to implement - new accessors for existing attributes, use read_attribute(attr_name) and write_attribute(attr_name, value) instead. Like this: - - class Song < ActiveRecord::Base - # Uses an integer of seconds to hold the length of the song - - def length=(minutes) - write_attribute("length", minutes * 60) - end - - def length - read_attribute("length") / 60 - end - end - - The clever kid will notice that this opens a door to sidestep the automated type conversion by using @attributes directly. - This is not recommended as read/write_attribute may be granted additional responsibilities in the future, but if you think - you know what you're doing and aren't afraid of future consequences, this is an option. - -* Applied a few minor bug fixes reported by Daniel Von Fange. - - -*0.8.4* - -_Reflection_ - -* Added ActiveRecord::Reflection with a bunch of methods and classes for reflecting in aggregations and associations. - -* Added Base.columns and Base.content_columns which returns arrays of column description (type, default, etc) objects. - -* Added Base#attribute_names which returns an array of names for the attributes available on the object. - -* Added Base#column_for_attribute(name) which returns the column description object for the named attribute. - - -_Misc_ - -* Added multi-parameter assignment: - - # Instantiate objects for all attribute classes that needs more than one constructor parameter. This is done - # by calling new on the column type or aggregation type (through composed_of) object with these parameters. - # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate - # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the - # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float, - # s for String, and a for Array. - - This is incredibly useful for assigning dates from HTML drop-downs of month, year, and day. - -* Fixed bug with custom primary key column name and Base.find on multiple parameters. - -* Fixed bug with dependent option on has_one associations if there was no associated object. - - -*0.8.3* - -_Transactions_ - -* Added transactional protection for destroy (important for the new :dependent option) [Suggested by Carl Youngblood] - -* Fixed so transactions are ignored on MyISAM tables for MySQL (use InnoDB to get transactions) - -* Changed transactions so only exceptions will cause a rollback, not returned false. - - -_Mapping_ - -* Added support for non-integer primary keys [Aredridel/earlier work by Michael Neumann] - - User.find "jdoe" - Product.find "PDKEY-INT-12" - -* Added option to specify naming method for primary key column. ActiveRecord::Base.primary_key_prefix_type can either - be set to nil, :table_name, or :table_name_with_underscore. :table_name will assume that Product class has a primary key - of "productid" and :table_name_with_underscore will assume "product_id". The default nil will just give "id". - -* Added an overwriteable primary_key method that'll instruct AR to the name of the - id column [Aredridele/earlier work by Guan Yang] - - class Project < ActiveRecord::Base - def self.primary_key() "project_id" end - end - -* Fixed that Active Records can safely associate inside and out of modules. - - class MyApplication::Account < ActiveRecord::Base - has_many :clients # will look for MyApplication::Client - has_many :interests, :class_name => "Business::Interest" # will look for Business::Interest - end - -* Fixed that Active Records can safely live inside modules [Aredridel] - - class MyApplication::Account < ActiveRecord::Base - end - - -_Misc_ - -* Added freeze call to value object assignments to ensure they remain immutable [Spotted by Gavin Sinclair] - -* Changed interface for specifying observed class in observers. Was OBSERVED_CLASS constant, now is - observed_class() class method. This is more consistant with things like self.table_name(). Works like this: - - class AuditObserver < ActiveRecord::Observer - def self.observed_class() Account end - def after_update(account) - AuditTrail.new(account, "UPDATED") - end - end - - [Suggested by Gavin Sinclair] - -* Create new Active Record objects by setting the attributes through a block. Like this: - - person = Person.new do |p| - p.name = 'Freddy' - p.age = 19 - end - - [Suggested by Gavin Sinclair] - - -*0.8.2* - -* Added inheritable callback queues that can ensure that certain callback methods or inline fragments are - run throughout the entire inheritance hierarchy. Regardless of whether a descendant overwrites the callback - method: - - class Topic < ActiveRecord::Base - before_destroy :destroy_author, 'puts "I'm an inline fragment"' - end - - Learn more in link:classes/ActiveRecord/Callbacks.html - -* Added :dependent option to has_many and has_one, which will automatically destroy associated objects when - the holder is destroyed: - - class Album < ActiveRecord::Base - has_many :tracks, :dependent => true - end - - All the associated tracks are destroyed when the album is. - -* Added Base.create as a factory that'll create, save, and return a new object in one step. - -* Automatically convert strings in config hashes to symbols for the _connection methods. This allows you - to pass the argument hashes directly from yaml. (Luke) - -* Fixed the install.rb to include simple.rb [Spotted by Kevin Bullock] - -* Modified block syntax to better follow our code standards outlined in - http://www.rubyonrails.org/CodingStandards - - -*0.8.1* - -* Added object-level transactions [Austin Ziegler] - -* Changed adapter-specific connection methods to use centralized ActiveRecord::Base.establish_connection, - which is parametized through a config hash with symbol keys instead of a regular parameter list. - This will allow for database connections to be opened in a more generic fashion. (Luke) - - NOTE: This requires all *_connections to be updated! Read more in: - http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000081 - -* Fixed SQLite adapter so objects fetched from has_and_belongs_to_many have proper attributes - (t.name is now name). [Spotted by Garrett Rooney] - -* Fixed SQLite adapter so dates are returned as Date objects, not Time objects [Spotted by Gavin Sinclair] - -* Fixed requirement of date class, so date conversions are succesful regardless of whether you - manually require date or not. - - -*0.8.0* - -* Added transactions - -* Changed Base.find to also accept either a list (1, 5, 6) or an array of ids ([5, 7]) - as parameter and then return an array of objects instead of just an object - -* Fixed method has_collection? for has_and_belongs_to_many macro to behave as a - collection, not an association - -* Fixed SQLite adapter so empty or nil values in columns of datetime, date, or time type - aren't treated as current time [Spotted by Gavin Sinclair] - - -*0.7.6* - -* Fixed the install.rb to create the lib/active_record/support directory [Spotted by Gavin Sinclair] -* Fixed that has_association? would always return true [Daniel Von Fange] diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md new file mode 100644 index 0000000000..69cf1193b6 --- /dev/null +++ b/activerecord/CHANGELOG.md @@ -0,0 +1,6861 @@ +## Rails 4.0.0 (unreleased) ## + +* Implemented ActiveRecord::Relation#none method + + The `none` method returns a chainable relation with zero records + (an instance of the NullRelation class). + + Any subsequent condition chained to the returned relation will continue + generating an empty relation and will not fire any query to the database. + + *Juanjo Bazán* + +* Added the `ActiveRecord::NullRelation` class implementing the null + object pattern for the Relation class. *Juanjo Bazán* + +* Added deprecation for the `:dependent => :restrict` association option. + + Please note: + + * Up until now `has_many` and `has_one`, `:dependent => :restrict` + option raised a `DeleteRestrictionError` at the time of destroying + the object. Instead, it will add an error on the model. + + * To fix this warning, make sure your code isn't relying on a + `DeleteRestrictionError` and then add + `config.active_record.dependent_restrict_raises = false` to your + application config. + + * New rails application would be generated with the + `config.active_record.dependent_restrict_raises = false` in the + application config. + + *Manoj Kumar* + +* Added `create_join_table` migration helper to create HABTM join tables + + create_join_table :products, :categories + # => + # create_table :categories_products, :id => false do |td| + # td.integer :product_id, :null => false + # td.integer :category_id, :null => false + # end + + *Rafael Mendonça França* + +* The primary key is always initialized in the @attributes hash to nil (unless + another value has been specified). + +* In previous releases, the following would generate a single query with + an `OUTER JOIN comments`, rather than two separate queries: + + Post.includes(:comments) + .where("comments.name = 'foo'") + + This behaviour relies on matching SQL string, which is an inherently + flawed idea unless we write an SQL parser, which we do not wish to + do. + + Therefore, it is now deprecated. + + To avoid deprecation warnings and for future compatibility, you must + explicitly state which tables you reference, when using SQL snippets: + + Post.includes(:comments) + .where("comments.name = 'foo'") + .references(:comments) + + Note that you do not need to explicitly specify references in the + following cases, as they can be automatically inferred: + + Post.where(comments: { name: 'foo' }) + Post.where('comments.name' => 'foo') + Post.order('comments.name') + + You also do not need to worry about this unless you are doing eager + loading. Basically, don't worry unless you see a deprecation warning + or (in future releases) an SQL error due to a missing JOIN. + + [Jon Leighton] + +* Support for the `schema_info` table has been dropped. Please + switch to `schema_migrations`. + +* Connections *must* be closed at the end of a thread. If not, your + connection pool can fill and an exception will be raised. + +* Added the `ActiveRecord::Model` module which can be included in a + class as an alternative to inheriting from `ActiveRecord::Base`: + + class Post + include ActiveRecord::Model + end + + Please note: + + * Up until now it has been safe to assume that all AR models are + descendants of `ActiveRecord::Base`. This is no longer a safe + assumption, but it may transpire that there are areas of the + code which still make this assumption. So there may be + 'teething difficulties' with this feature. (But please do try it + and report bugs.) + + * Plugins & libraries etc that add methods to `ActiveRecord::Base` + will not be compatible with `ActiveRecord::Model`. Those libraries + should add to `ActiveRecord::Model` instead (which is included in + `Base`), or better still, avoid monkey-patching AR and instead + provide a module that users can include where they need it. + + * To minimise the risk of conflicts with other code, it is + advisable to include `ActiveRecord::Model` early in your class + definition. + + *Jon Leighton* + +* PostgreSQL hstore records can be created. + +* PostgreSQL hstore types are automatically deserialized from the database. + + +## Rails 3.2.1 (unreleased) ## + +* The threshold for auto EXPLAIN is ignored if there's no logger. *fxn* + +* Fix possible race condition when two threads try to define attribute + methods for the same class. + + +## Rails 3.2.0 (January 20, 2012) ## + +* Added a `with_lock` method to ActiveRecord objects, which starts + a transaction, locks the object (pessimistically) and yields to the block. + The method takes one (optional) parameter and passes it to `lock!`. + + Before: + + class Order < ActiveRecord::Base + def cancel! + transaction do + lock! + # ... cancelling logic + end + end + end + + After: + + class Order < ActiveRecord::Base + def cancel! + with_lock do + # ... cancelling logic + end + end + end + + *Olek Janiszewski* + +* 'on' and 'ON' boolean columns values are type casted to true + *Santiago Pastorino* + +* Added ability to run migrations only for given scope, which allows + to run migrations only from one engine (for example to revert changes + from engine that you want to remove). + + Example: + rake db:migrate SCOPE=blog + + *Piotr Sarnacki* + +* Migrations copied from engines are now scoped with engine's name, + for example 01_create_posts.blog.rb. *Piotr Sarnacki* + +* Implements `AR::Base.silence_auto_explain`. This method allows the user to + selectively disable automatic EXPLAINs within a block. *fxn* + +* Implements automatic EXPLAIN logging for slow queries. + + A new configuration parameter `config.active_record.auto_explain_threshold_in_seconds` + determines what's to be considered a slow query. Setting that to `nil` disables + this feature. Defaults are 0.5 in development mode, and `nil` in test and production + modes. + + As of this writing there's support for SQLite, MySQL (mysql2 adapter), and + PostgreSQL. + + *fxn* + +* Implemented ActiveRecord::Relation#pluck method + + Method returns Array of column value from table under ActiveRecord model + + Client.pluck(:id) + + *Bogdan Gusiev* + +* Automatic closure of connections in threads is deprecated. For example + the following code is deprecated: + + Thread.new { Post.find(1) }.join + + It should be changed to close the database connection at the end of + the thread: + + Thread.new { + Post.find(1) + Post.connection.close + }.join + + Only people who spawn threads in their application code need to worry + about this change. + +* Deprecated: + + * `set_table_name` + * `set_inheritance_column` + * `set_sequence_name` + * `set_primary_key` + * `set_locking_column` + + Use an assignment method instead. For example, instead of `set_table_name`, use `self.table_name=`: + + class Project < ActiveRecord::Base + self.table_name = "project" + end + + Or define your own `self.table_name` method: + + class Post < ActiveRecord::Base + def self.table_name + "special_" + super + end + end + Post.table_name # => "special_posts" + + *Jon Leighton* + +* Generated association methods are created within a separate module to allow overriding and + composition using `super`. For a class named `MyModel`, the module is named + `MyModel::GeneratedFeatureMethods`. It is included into the model class immediately after + the `generated_attributes_methods` module defined in ActiveModel, so association methods + override attribute methods of the same name. *Josh Susser* + +* Implemented ActiveRecord::Relation#explain. *fxn* + +* Add ActiveRecord::Relation#uniq for generating unique queries. + + Before: + + Client.select('DISTINCT name') + + After: + + Client.select(:name).uniq + + This also allows you to revert the uniqueness in a relation: + + Client.select(:name).uniq.uniq(false) + + *Jon Leighton* + +* Support index sort order in sqlite, mysql and postgres adapters. *Vlad Jebelev* + +* Allow the :class_name option for associations to take a symbol (:Client) in addition to + a string ('Client'). + + This is to avoid confusing newbies, and to be consistent with the fact that other options + like :foreign_key already allow a symbol or a string. + + *Jon Leighton* + +* In development mode the db:drop task also drops the test database. For symmetry with + the db:create task. *Dmitriy Kiriyenko* + +* Added ActiveRecord::Base.store for declaring simple single-column key/value stores *DHH* + + class User < ActiveRecord::Base + store :settings, accessors: [ :color, :homepage ] + end + + u = User.new(color: 'black', homepage: '37signals.com') + u.color # Accessor stored attribute + u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor + + +* MySQL: case-insensitive uniqueness validation avoids calling LOWER when + the column already uses a case-insensitive collation. Fixes #561. + + *Joseph Palermo* + +* Transactional fixtures enlist all active database connections. You can test + models on different connections without disabling transactional fixtures. + + *Jeremy Kemper* + +* Add first_or_create, first_or_create!, first_or_initialize methods to Active Record. This is a + better approach over the old find_or_create_by dynamic methods because it's clearer which + arguments are used to find the record and which are used to create it: + + User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson") + + *Andrés Mejía* + +* Fix nested attributes bug where _destroy parameter is taken into account + during :reject_if => :all_blank (fixes #2937) + + *Aaron Christy* + +## Rails 3.1.3 (November 20, 2011) ## + +* Perf fix: If we're deleting all records in an association, don't add a IN(..) clause + to the query. *GH 3672* + + *Jon Leighton* + +* Fix bug with referencing other mysql databases in set_table_name. *GH 3690* + +* Fix performance bug with mysql databases on a server with lots of other databses. *GH 3678* + + *Christos Zisopoulos and Kenny J* + +## Rails 3.1.2 (November 18, 2011) ## + +* Fix bug with PostgreSQLAdapter#indexes. When the search path has multiple schemas, spaces + were not being stripped from the schema names after the first. + + *Sean Kirby* + +* Preserve SELECT columns on the COUNT for finder_sql when possible. *GH 3503* + + *Justin Mazzi* + +* Reset prepared statement cache when schema changes impact statement results. *GH 3335* + + *Aaron Patterson* + +* Postgres: Do not attempt to deallocate a statement if the connection is no longer active. + + *Ian Leitch* + +* Prevent QueryCache leaking database connections. *GH 3243* + + *Mark J. Titorenko* + +* Fix bug where building the conditions of a nested through association could potentially + modify the conditions of the through and/or source association. If you have experienced + bugs with conditions appearing in the wrong queries when using nested through associations, + this probably solves your problems. *GH #3271* + + *Jon Leighton* + +* If a record is removed from a has_many :through, all of the join records relating to that + record should also be removed from the through association's target. + + *Jon Leighton* + +* Fix adding multiple instances of the same record to a has_many :through. *GH #3425* + + *Jon Leighton* + +* Fix creating records in a through association with a polymorphic source type. *GH #3247* + + *Jon Leighton* + +* MySQL: use the information_schema than the describe command when we look for a primary key. *GH #3440* + + *Kenny J* + +## Rails 3.1.1 (October 7, 2011) ## + +* Add deprecation for the preload_associations method. Fixes #3022. + + *Jon Leighton* + +* Don't require a DB connection when loading a model that uses set_primary_key. GH #2807. + + *Jon Leighton* + +* Fix using select() with a habtm association, e.g. Person.friends.select(:name). GH #3030 and + \#2923. + + *Hendy Tanata* + +* Fix belongs_to polymorphic with custom primary key on target. GH #3104. + + *Jon Leighton* + +* CollectionProxy#replace should change the DB records rather than just mutating the array. + Fixes #3020. + + *Jon Leighton* + +* LRU cache in mysql and sqlite are now per-process caches. + + * lib/active_record/connection_adapters/mysql_adapter.rb: LRU cache keys are per process id. + * lib/active_record/connection_adapters/sqlite_adapter.rb: ditto + *Aaron Patterson* + +* Support bulk change_table in mysql2 adapter, as well as the mysql one. *Jon Leighton* + +* If multiple parameters are sent representing a date, and some are blank, the + resulting object is nil. In previous releases those values defaulted to 1. This only affects existing but blank parameters, missing ones still raise an error. [Akira Matsuda] +* ActiveRecord::Base.establish_connection now takes a string that contains + a URI that specifies the connection configuration. For example: + ActiveRecord::Base.establish_connection 'postgres://localhost/foo' + +* Active Record's dynamic finder will now raise the error if you passing in less number of arguments than what you call in method signature. + + So if you were doing this and expecting the second argument to be nil: + + User.find_by_username_and_group("sikachu") + + You'll now get `ArgumentError: wrong number of arguments (1 for 2).` You'll then have to do this: + + User.find_by_username_and_group("sikachu", nil) + + *Prem Sichanugrist* + + +## Rails 3.1.0 (August 30, 2011) ## + +* Add a proxy_association method to association proxies, which can be called by association + extensions to access information about the association. This replaces proxy_owner etc with + proxy_association.owner. + + *Jon Leighton* + +* ActiveRecord::MacroReflection::AssociationReflection#build_record has a new method signature. + + Before: def build_association(*options) + After: def build_association(*options, &block) + + Users who are redefining this method to extend functionality should ensure that the block is + passed through to ActiveRecord::Base#new. + + This change is necessary to fix https://github.com/rails/rails/issues/1842. + + *Jon Leighton* + +* AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model: + + class User < ActiveRecord::Base + self.pluralize_table_names = false + end + + Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. *Guillermo Iguaran* + +* Add block setting of attributes to singular associations: + + class User < ActiveRecord::Base + has_one :account + end + + user.build_account{ |a| a.credit_limit => 100.0 } + + The block is called after the instance has been initialized. *Andrew White* + +* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. *Prem Sichanugrist* + +* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0 + +* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you + to specify which role to consider when assigning attributes. This is built on top of ActiveModel's + new mass assignment capabilities: + + class Post < ActiveRecord::Base + attr_accessible :title + attr_accessible :title, :published_at, :as => :admin + end + + Post.new(params[:post], :as => :admin) + + assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated. + + Please note that this changes the method signatures for AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes!. If you have overwritten these methods you should update them accordingly. + + *Josh Kalderimis* + +* default_scope can take a block, lambda, or any other object which responds to `call` for lazy + evaluation: + + default_scope { ... } + default_scope lambda { ... } + default_scope method(:foo) + + This feature was originally implemented by Tim Morgan, but was then removed in favour of + defining a 'default_scope' class method, but has now been added back in by Jon Leighton. + The relevant lighthouse ticket is #1812. + +* Default scopes are now evaluated at the latest possible moment, to avoid problems where + scopes would be created which would implicitly contain the default scope, which would then + be impossible to get rid of via Model.unscoped. + + Note that this means that if you are inspecting the internal structure of an + ActiveRecord::Relation, it will *not* contain the default scope, though the resulting + query will do. You can get a relation containing the default scope by calling + ActiveRecord#with_default_scope, though this is not part of the public API. + + *Jon Leighton* + +* If you wish to merge default scopes in special ways, it is recommended to define your default + scope as a class method and use the standard techniques for sharing code (inheritance, mixins, + etc.): + + class Post < ActiveRecord::Base + def self.default_scope + where(:published => true).where(:hidden => false) + end + end + + *Jon Leighton* + +* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher. + +* ConnectionManagement middleware is changed to clean up the connection pool + after the rack body has been flushed. + +* Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks. + It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of + the updated_at column. It should not be called on new records. + Example: + + User.first.update_column(:name, "sebastian") # => true + + *Sebastian Martinez* + +* Associations with a :through option can now use *any* association as the + through or source association, including other associations which have a + :through option and has_and_belongs_to_many associations + + *Jon Leighton* + +* The configuration for the current database connection is now accessible via + ActiveRecord::Base.connection_config. *fxn* + +* limits and offsets are removed from COUNT queries unless both are supplied. + For example: + + People.limit(1).count # => 'SELECT COUNT(*) FROM people' + People.offset(1).count # => 'SELECT COUNT(*) FROM people' + People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1' + + *lighthouse #6262* + +* ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class + (and subclasses) which are responsible for operating on associations, and then a separate, + thin wrapper called CollectionProxy, which proxies collection associations. + + This prevents namespace pollution, separates concerns, and will allow further refactorings. + + Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return + the associated record or nil. This means that you should not use undocumented methods such + as bob.mother.create - use bob.create_mother instead. + + *Jon Leighton* + +* Make has_many :through associations work correctly when you build a record and then save it. This + requires you to set the :inverse_of option on the source reflection on the join model, like so: + + class Post < ActiveRecord::Base + has_many :taggings + has_many :tags, :through => :taggings + end + + class Tagging < ActiveRecord::Base + belongs_to :post + belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set! + end + + class Tag < ActiveRecord::Base + has_many :taggings + has_many :posts, :through => :taggings + end + + post = Post.first + tag = post.tags.build :name => "ruby" + tag.save # will save a Taggable linking to the post + + *Jon Leighton* + +* Support the :dependent option on has_many :through associations. For historical and practical + reasons, :delete_all is the default deletion strategy employed by association.delete(*records), + despite the fact that the default strategy is :nullify for regular has_many. Also, this only + works at all if the source reflection is a belongs_to. For other situations, you should directly + modify the through association. + + *Jon Leighton* + +* Changed the behaviour of association.destroy for has_and_belongs_to_many and has_many :through. + From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', + not (necessarily) 'get rid of the associated records'. + + Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It + would not delete any records in the join table. Now, it deletes the records in the join table. + + Previously, has_many_through.destroy(*records) would destroy the records themselves, and the + records in the join table. [Note: This has not always been the case; previous version of Rails + only deleted the records themselves.] Now, it destroys only the records in the join table. + + Note that this change is backwards-incompatible to an extent, but there is unfortunately no + way to 'deprecate' it before changing it. The change is being made in order to have + consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. + + If you wish to destroy the records themselves, you can do records.association.each(&:destroy) + + *Jon Leighton* + +* Add :bulk => true option to change_table to make all the schema changes defined in change_table block using a single ALTER statement. *Pratik Naik* + + Example: + + change_table(:users, :bulk => true) do |t| + t.string :company_name + t.change :birthdate, :datetime + end + + This will now result in: + + ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL + +* Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been + documented as deprecated behaviour since April 2006. Please use has_many :through instead. + *Jon Leighton* + +* Added a create_association! method for has_one and belongs_to associations. *Jon Leighton* + +* Migration files generated from model and constructive migration generators + (for example, add_name_to_users) use the reversible migration's `change` + method instead of the ordinary `up` and `down` methods. *Prem Sichanugrist* + +* Removed support for interpolating string SQL conditions on associations. Instead, you should + use a proc, like so: + + Before: + + has_many :things, :conditions => 'foo = #{bar}' + + After: + + has_many :things, :conditions => proc { "foo = #{bar}" } + + Inside the proc, 'self' is the object which is the owner of the association, unless you are + eager loading the association, in which case 'self' is the class which the association is within. + + You can have any "normal" conditions inside the proc, so the following will work too: + + has_many :things, :conditions => proc { ["foo = ?", bar] } + + Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call + 'record' to get the record being inserted or deleted. This is now passed as an argument to + the proc. + +* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example: + + # Schema: User(name:string, password_digest:string, password_salt:string) + class User < ActiveRecord::Base + has_secure_password + end + + user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch") + user.save # => false, password required + user.password = "mUc3m00RsqyRe" + user.save # => false, confirmation doesn't match + user.password_confirmation = "mUc3m00RsqyRe" + user.save # => true + user.authenticate("notright") # => false + user.authenticate("mUc3m00RsqyRe") # => user + User.find_by_name("david").try(:authenticate, "notright") # => nil + User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user + + +* When a model is generated add_index is added by default for belongs_to or references columns + + rails g model post user:belongs_to will generate the following: + + class CreatePosts < ActiveRecord::Migration + def up + create_table :posts do |t| + t.belongs_to :user + t.timestamps + end + + add_index :posts, :user_id + end + + def down + drop_table :posts + end + end + + *Santiago Pastorino* + +* Setting the id of a belongs_to object will update the reference to the + object. [#2989 state:resolved] +* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed + to closer match normal Ruby dup and clone semantics. +* Calling ActiveRecord::Base#clone will result in a shallow copy of the record, + including copying the frozen state. No callbacks will be called. +* Calling ActiveRecord::Base#dup will duplicate the record, including calling + after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable. +* Migrations can be defined as reversible, meaning that the migration system + will figure out how to reverse your migration. To use reversible migrations, just define the "change" method. For example: + class MyMigration < ActiveRecord::Migration + def change + create_table(:horses) do + t.column :content, :text + t.column :remind_at, :datetime + end + end + end + + Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define 'up' and 'down' in your migration. If you define something in `change` that cannot be reversed, an IrreversibleMigration exception will be raised when going down. +* Migrations should use instance methods rather than class methods: + class FooMigration < ActiveRecord::Migration + def up + ... + end + end + + *Aaron Patterson* + +* has_one maintains the association with separate after_create/after_update instead + of a single after_save. *fxn* + +* The following code: + + Model.limit(10).scoping { Model.count } + + now generates the following SQL: + + SELECT COUNT(*) FROM models LIMIT 10 + + This may not return what you want. Instead, you may with to do something + like this: + + Model.limit(10).scoping { Model.all.size } + + *Aaron Patterson* + + +## Rails 3.0.7 (April 18, 2011) ## + +* Destroying records via nested attributes works independent of reject_if LH #6006 *Durran Jordan* + +* Delegate any? and many? to Model.scoped for consistency *Andrew White* + +* Quote the ORDER BY clause in batched finds - fixes #6620 *Andrew White* + +* Change exists? so records are not instantiated - fixes #6127. This prevents after_find + and after_initialize callbacks being triggered when checking for record existence. + *Andrew White* + +* Fix performance bug with attribute accessors which only occurred on Ruby 1.8.7, and ensure we + cache type-casted values when the column returned from the db contains non-standard chars. + *Jon Leighton* + +* Fix a performance regression introduced here 86acbf1cc050c8fa8c74a10c735e467fb6fd7df8 + related to read_attribute method *Stian Grytøyr* + + +## Rails 3.0.6 (April 5, 2011) ## + +* Un-deprecate reorder method *Sebastian Martinez* + +* Extensions are applied when calling +except+ or +only+ on relations. + Thanks to Iain Hecker. + +* Schemas set in set_table_name are respected by the mysql adapter. LH #5322 + +* Fixed a bug when empty? was called on a grouped Relation that wasn't loaded. + LH #5829 + +* Reapply extensions when using except and only. Thanks Iain Hecker. + +* Binary data is escaped when being inserted to SQLite3 Databases. Thanks + Naruse! + + +## Rails 3.0.5 (February 26, 2011) ## + +* Model.where(:column => 1).where(:column => 2) will always produce an AND + query. + *Aaron Patterson* + +* Deprecated support for interpolated association conditions in the form of :conditions => 'foo = #{bar}'. + + Instead, you should use a proc, like so: + + Before: + + has_many :things, :conditions => 'foo = #{bar}' + + After: + + has_many :things, :conditions => proc { "foo = #{bar}" } + + Inside the proc, 'self' is the object which is the owner of the association, unless you are + eager loading the association, in which case 'self' is the class which the association is within. + + You can have any "normal" conditions inside the proc, so the following will work too: + + has_many :things, :conditions => proc { ["foo = ?", bar] } + + Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call + 'record' to get the record being inserted or deleted. This is now passed as an argument to + the proc. + + *Jon Leighton* + + +## Rails 3.0.4 (February 8, 2011) ## + +* Added deprecation warning for has_and_belongs_to_many associations where the join table has + additional attributes other than the keys. Access to these attributes is removed in 3.1. + Please use has_many :through instead. *Jon Leighton* + + +## Rails 3.0.3 (November 16, 2010) ## + +* Support find by class like this: Post.where(:name => Post) + + +## Rails 3.0.2 (November 15, 2010) ## + +* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) *Aaron Patterson* + +* reorder is deprecated in favor of except(:order).order(...) *Santiago Pastorino* + +* except is now AR public API + + Model.order('name').except(:order).order('salary') + + generates: + + SELECT * FROM models ORDER BY salary + + *Santiago Pastorino* + +* The following code: + + Model.limit(10).scoping { Model.count } + + now generates the following SQL: + + SELECT COUNT(*) FROM models LIMIT 10 + + This may not return what you want. Instead, you may with to do something + like this: + + Model.limit(10).scoping { Model.all.size } + + *Aaron Patterson* + + +## Rails 3.0.1 (October 15, 2010) ## + +* Introduce a fix for CVE-2010-3993 + + +## Rails 3.0.0 (August 29, 2010) ## + +* Changed update_attribute to not run callbacks and update the record directly in the database *Neeraj Singh* + +* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope *José Valim* + +* New rake task, db:migrate:status, displays status of migrations #4947 *Kevin Skoglund* + +* select and order for ActiveRecord now always concatenate nested calls. Use reorder if you want the original order to be overwritten *Santiago Pastorino* + +* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 *Aaron Patterson* + +* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 *Andrew Bloomgarden, Andrew White* + +* Add index length support for MySQL. #1852 *Emili Parreno, Pratik Naik* + + Example: + + add_index(:accounts, :name, :name => 'by_name', :length => 10) + => CREATE INDEX by_name ON accounts(name(10)) + + add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15}) + => CREATE INDEX by_name_surname ON accounts(name(10), surname(15)) + +* find_or_create_by_attr(value, ...) works when attr is protected. #4457 *Santiago Pastorino, Marc-André Lafortune* + +* New callbacks: after_commit and after_rollback. Do expensive operations like image thumbnailing after_commit instead of after_save. #2991 *Brian Durand* + +* Serialized attributes are not converted to YAML if they are any of the formats that can be serialized to XML (like Hash, Array and Strings). *José Valim* + +* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 *Curtis Hawthorne* + +* PostgreSQL: drop support for old postgres driver. Use pg 0.9.0 or later. *Jeremy Kemper* + +* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 *Mislav Marohnić* + +* Add Relation extensions. *Pratik Naik* + + users = User.where(:admin => true).extending(User::AdminPowers) + + latest_users = User.order('created_at DESC') do + def posts_count + Post.count(:user_id => to_a.map(&:id)) + end + end + +* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 *Andrew White* + +* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development *DHH* + +* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 *Jack Christensen* + +* Allow relations to be used as scope. + + class Item + scope :red, where(:colour => 'red') + end + + Item.red.limit(10) # Ten red items + +* Rename named_scope to scope. *Pratik Naik* + +* Changed ActiveRecord::Base.store_full_sti_class to be true by default reflecting the previously announced Rails 3 default *DHH* + +* Add Relation#except. *Pratik Naik* + + one_red_item = Item.where(:colour => 'red').limit(1) + all_items = one_red_item.except(:where, :limit) + +* Add Relation#delete_all. *Pratik Naik* + + Item.where(:colour => 'red').delete_all + +* Add Model.having and Relation#having. *Pratik Naik* + + Developer.group("salary").having("sum(salary) > 10000").select("salary") + +* Add Relation#count. *Pratik Naik* + + legends = People.where("age > 100") + legends.count + legends.count(:age, :distinct => true) + legends.select('id').count + +* Add Model.readonly and association_collection#readonly finder method. *Pratik Naik* + + Post.readonly.to_a # Load all posts in readonly mode + @user.items.readonly(false).to_a # Load all the user items in writable mode + +* Add .lock finder method *Pratik Naik* + + User.lock.where(:name => 'lifo').to_a + + old_items = Item.where("age > 100") + old_items.lock.each {|i| .. } + +* Add Model.from and association_collection#from finder methods *Pratik Naik* + + user = User.scoped + user.select('*').from('users, items') + +* Add relation.destroy_all *Pratik Naik* + + old_items = Item.where("age > 100") + old_items.destroy_all + +* Add relation.exists? *Pratik Naik* + + red_items = Item.where(:colours => 'red') + red_items.exists? + red_items.exists?(1) + +* Add find(ids) to relations. *Pratik Naik* + + old_users = User.order("age DESC") + old_users.find(1) + old_users.find(1, 2, 3) + +* Add new finder methods to association collection. *Pratik Naik* + + class User < ActiveRecord::Base + has_many :items + end + + user = User.first + user.items.where(:items => {:colour => 'red'}) + user.items.select('items.id') + +* Add relation.reload to force reloading the records. *Pratik Naik* + + topics = Topic.scoped + topics.to_a # force load + topics.first # returns a cached record + topics.reload + topics.first # Fetches a new record from the database + +* Rename Model.conditions and relation.conditions to .where. *Pratik Naik* + + Before : + User.conditions(:name => 'lifo') + User.select('id').conditions(["age > ?", 21]) + + Now : + User.where(:name => 'lifo') + User.select('id').where(["age > ?", 21]) + +* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. *Pratik Naik* + + Examples : + + posts = Post.select('id).order('name') # Returns a lazy relation + posts.each {|p| puts p.id } # Fires "select id from posts order by name" + +* Model.scoped now returns a relation if invoked without any arguments. *Pratik Naik* + + Example : + + posts = Post.scoped + posts.size # Fires "select count(*) from posts" and returns the count + posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects + +* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 *Murray Steele* + + # post.comments sets each comment's post without needing to :include + class Post < ActiveRecord::Base + has_many :comments, :inverse_of => :post + end + +* MySQL: add_ and change_column support positioning. #3286 *Ben Marini* + +* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 *Mike Breen, Gabe da Silveira* + +* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git *Pratik Naik* + +* PostgreSQL: XML datatype support. #1874 *Leonardo Borges* + +* quoted_date converts time-like objects to ActiveRecord::Base.default_timezone before serialization. This allows you to use Time.now in find conditions and have it correctly be serialized as the current time in UTC when default_timezone == :utc. #2946 *Geoff Buesing* + +* SQLite: drop support for 'dbfile' option in favor of 'database.' #2363 *Paul Hinze, Jeremy Kemper* + +* Added :primary_key option to belongs_to associations. #765 *Szymon Nowak, Philip Hallstrom, Noel Rocha* + # employees.company_name references companies.name + Employee.belongs_to :company, :primary_key => 'name', :foreign_key => 'company_name' + +* Implement #many? for NamedScope and AssociationCollection using #size. #1500 *Chris Kampmeier* + +* Added :touch option to belongs_to associations that will touch the parent record when the current record is saved or destroyed *DHH* + +* Added ActiveRecord::Base#touch to update the updated_at/on attributes (or another specified timestamp) with the current time *DHH* + + +## 2.3.2 Final (March 15, 2009) ## + +* Added ActiveRecord::Base.find_each and ActiveRecord::Base.find_in_batches for batch processing *DHH/Jamis Buck* + +* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 *Scott Taylor* + +* Add Support for updating deeply nested models from a single form. #1202 *Eloy Duran* + + class Book < ActiveRecord::Base + has_one :author + has_many :pages + + accepts_nested_attributes_for :author, :pages + end + +* Make after_save callbacks fire only if the record was successfully saved. #1735 *Michael Lovitt* + + Previously the callbacks would fire if a before_save cancelled saving. + +* Support nested transactions using database savepoints. #383 *Jonathan Viney, Hongli Lai* + +* Added dynamic scopes ala dynamic finders #1648 *Yaroslav Markin* + +* Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 *Yaroslav Markin* + +* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 *Akira Matsuda* + +* Add :having as a key to find and the relevant associations. *Emilio Tagua* + +* Added default_scope to Base #1381 [Paweł Kondzior]. Example: + + class Person < ActiveRecord::Base + default_scope :order => 'last_name, first_name' + end + + class Company < ActiveRecord::Base + has_many :people + end + + Person.all # => Person.find(:all, :order => 'last_name, first_name') + Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 }) + + +## 2.2.1 RC2 (November 14th, 2008) ## + +* Ensure indices don't flip order in schema.rb #1266 *Jordi Bunster* + +* Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 *Andreas Korth* + + +## 2.2.0 RC1 (October 24th, 2008) ## + +* Skip collection ids reader optimization if using :finder_sql *Jeremy Kemper* + +* Add Model#delete instance method, similar to Model.delete class method. #1086 *Hongli Lai (Phusion)* + +* MySQL: cope with quirky default values for not-null text columns. #1043 *Frederick Cheung* + +* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] *Geoff Buesing* + +* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] *Emilio Tagua* + +* Added find_last_by dynamic finder #762 *Emilio Tagua* + +* Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 *Hongli Lai (Phusion)* + +* Changed benchmarks to be reported in milliseconds *David Heinemeier Hansson* + +* Connection pooling. #936 *Nick Sieger* + +* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 *Andrew White* + +* before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 *Xavier Noria* + +* Transactional migrations for databases which support them. #834 *divoxx, Adam Wiggins, Tarmo Tänav* + +* Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp. #446. *Andrew Stone, Nik Wakelin* + +* change_column_default preserves the not-null constraint. #617 *Tarmo Tänav* + +* Fixed that create database statements would always include "DEFAULT NULL" (Nick Sieger) *#334* + +* Add :tokenizer option to validates_length_of to specify how to split up the attribute string. #507. [David Lowenfels] Example : + + \# Ensure essay contains at least 100 words. + validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) } + +* Allow conditions on multiple tables to be specified using hash. [Pratik Naik]. Example: + + User.all :joins => :items, :conditions => { :age => 10, :items => { :color => 'black' } } + Item.first :conditions => { :items => { :color => 'red' } } + +* Always treat integer :limit as byte length. #420 *Tarmo Tänav* + +* Partial updates don't update lock_version if nothing changed. #426 *Daniel Morrison* + +* Fix column collision with named_scope and :joins. #46 *Duncan Beevers, Mark Catley* + +* db:migrate:down and :up update schema_migrations. #369 *Michael Raidel, RaceCondition* + +* PostgreSQL: support :conditions => [':foo::integer', { :foo => 1 }] without treating the ::integer typecast as a bind variable. *Tarmo Tänav* + +* MySQL: rename_column preserves column defaults. #466 *Diego Algorta* + +* Add :from option to calculations. #397 *Ben Munat* + +* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. *Jan De Poorter* + +* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. *Jeremy Kemper* + +* Added SQL escaping for :limit and :offset in MySQL *Jonathan Wiess* + + +## 2.1.0 (May 31st, 2008) ## + +* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. *Rick Olson* + +* Add first/last methods to associations/named_scope. Resolved #226. *Ryan Bates* + +* Added SQL escaping for :limit and :offset #288 *Aaron Bedra, Steven Bristol, Jonathan Wiess* + +* Added first/last methods to associations/named_scope. Resolved #226. *Ryan Bates* + +* Ensure hm:t preloading honours reflection options. Resolves #137. *Frederick Cheung* + +* Added protection against duplicate migration names (Aslak Hellesøy) *#112* + +* Base#instantiate_time_object: eliminate check for Time.zone, since we can assume this is set if time_zone_aware_attributes is set to true *Geoff Buesing* + +* Time zone aware attribute methods use Time.zone.parse instead of #to_time for String arguments, so that offset information in String is respected. Resolves #105. *Scott Fleckenstein, Geoff Buesing* + +* Added change_table for migrations (Jeff Dean) [#71]. Example: + + change_table :videos do |t| + t.timestamps # adds created_at, updated_at + t.belongs_to :goat # adds goat_id integer + t.string :name, :email, :limit => 20 # adds name and email both with a 20 char limit + t.remove :name, :email # removes the name and email columns + end + +* Fixed has_many :through .create with no parameters caused a "can't dup NilClass" error (Steven Soroka) *#85* + +* Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) *#39* + +* Fixed that pessimistic locking you reference the quoted table name (Josh Susser) *#67* + +* Fixed that change_column should be able to use :null => true on a field that formerly had false [Nate Wiger] *#26* + +* Added that the MySQL adapter should map integer to either smallint, int, or bigint depending on the :limit just like PostgreSQL *David Heinemeier Hansson* + +* Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. *Rick Olson* + +* Add support for interleaving migrations by storing which migrations have run in the new schema_migrations table. Closes #11493 *Jordi Bunster* + +* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 *Kamal Fariz Mahyuddin* + +* Ensure that respond_to? considers dynamic finder methods. Closes #11538. *James Mead* + +* Ensure that save on parent object fails for invalid has_one association. Closes #10518. *Pratik Naik* + +* Remove duplicate code from associations. *Pratik Naik* + +* Refactor HasManyThroughAssociation to inherit from HasManyAssociation. Association callbacks and <association>_ids= now work with hm:t. #11516 *Ruy Asan* + +* Ensure HABTM#create and HABTM#build do not load entire association. *Pratik Naik* + +* Improve documentation. *Xavier Noria, Jack Danger Canty, leethal* + +* Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} *Rick Olson* + + Post.find(1).to_json # => {"title": ...} + config.active_record.include_root_in_json = true + Post.find(1).to_json # => {"post": {"title": ...}} + +* Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). *stopdropandrew* + +* PostgreSQL: create_ and drop_database support. #9042 *ez, pedz, Nick Sieger* + +* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. *Nik Wakelin, cavalle* + +* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. *Jeremy Kemper* + +* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled *Geoff Buesing* + +* Fixed that validates_size_of :within works in associations #11295, #10019 *cavalle* + +* Track changes to unsaved attributes. *Jeremy Kemper* + +* Switched to UTC-timebased version numbers for migrations and the schema. This will as good as eliminate the problem of multiple migrations getting the same version assigned in different branches. Also added rake db:migrate:up/down to apply individual migrations that may need to be run when you merge branches #11458 *John Barnette* + +* Fixed that has_many :through would ignore the hash conditions #11447 *Emilio Tagua* + +* Fix issue where the :uniq option of a has_many :through association is ignored when find(:all) is called. Closes #9407 *cavalle* + +* Fix duplicate table alias error when including an association with a has_many :through association on the same join table. Closes #7310 *cavalle* + +* More efficient association preloading code that compacts a through_records array in a central location. Closes #11427 *Jack Danger Canty* + +* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert* + +* Fixed that ActiveRecord#Base.find_or_create/initialize would not honor attr_protected/accessible when used with a hash #11422 *Emilio Tagua* + +* Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:last) #11413 *nkallen, Chris O'Sullivan* + +* Merge the has_finder gem, renamed as 'named_scope'. #11404 *nkallen* + + class Article < ActiveRecord::Base + named_scope :published, :conditions => {:published => true} + named_scope :popular, :conditions => ... + end + + Article.published.paginate(:page => 1) + Article.published.popular.count + Article.popular.find(:first) + Article.popular.find(:all, :conditions => {...}) + + See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries + +* Add has_one :through support. #4756 *Chris O'Sullivan* + +* Migrations: create_table supports primary_key_prefix_type. #10314 *student, Chris O'Sullivan* + +* Added logging for dependency load errors with fixtures #11056 *stuthulhu* + +* Time zone aware attributes use Time#in_time_zone *Geoff Buesing* + +* Fixed that scoped joins would not always be respected #6821 *Theory/Jack Danger Canty* + +* Ensure that ActiveRecord::Calculations disambiguates field names with the table name. #11027 *cavalle* + +* Added add/remove_timestamps to the schema statements for adding the created_at/updated_at columns on existing tables #11129 *jramirez* + +* Added ActiveRecord::Base.find(:last) #11338 *Emilio Tagua* + +* test_native_types expects DateTime.local_offset instead of DateTime.now.offset; fixes test breakage due to dst transition *Geoff Buesing* + +* Add :readonly option to HasManyThrough associations. #11156 *Emilio Tagua* + +* Improve performance on :include/:conditions/:limit queries by selectively joining in the pre-query. #9560 *dasil003* + +* Perf fix: Avoid the use of named block arguments. Closes #11109 *adymo* + +* PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg driver. #11127 *jdavis* + +* Ensure association preloading doesn't break when an association returns nil. ##11145 *GMFlash* + +* Make dynamic finders respect the :include on HasManyThrough associations. #10998. *cpytel* + +* Base#instantiate_time_object only uses Time.zone when Base.time_zone_aware_attributes is true; leverages Time#time_with_datetime_fallback for readability *Geoff Buesing* + +* Refactor ConnectionAdapters::Column.new_time: leverage DateTime failover behavior of Time#time_with_datetime_fallback *Geoff Buesing* + +* Improve associations performance by using symbol callbacks instead of string callbacks. #11108 *adymo* + +* Optimise the BigDecimal conversion code. #11110 *adymo* + +* Introduce the :readonly option to all associations. Records from the association cannot be saved. #11084 *Emilio Tagua* + +* Multiparameter attributes for time columns fail over to DateTime when out of range of Time *Geoff Buesing* + +* Base#instantiate_time_object uses Time.zone.local() *Geoff Buesing* + +* Add timezone-aware attribute readers and writers. #10982 *Geoff Buesing* + +* Instantiating time objects in multiparameter attributes uses Time.zone if available. #10982 *Rick Olson* + +* Add note about how ActiveRecord::Observer classes are initialized in a Rails app. #10980 *Xavier Noria* + +* MySQL: omit text/blob defaults from the schema instead of using an empty string. #10963 *mdeiters* + +* belongs_to supports :dependent => :destroy and :delete. #10592 *Jonathan Viney* + +* Introduce preload query strategy for eager :includes. #9640 *Frederick Cheung, Aliaksey Kandratsenka, codafoo* + +* Support aggregations in finder conditions. #10572 *Ryan Kinderman* + +* Organize and clean up the Active Record test suite. #10742 *John Barnette* + +* Ensure that modifying has_and_belongs_to_many actions clear the query cache. Closes #10840 *john.andrews* + +* Fix issue where Table#references doesn't pass a :null option to a *_type attribute for polymorphic associations. Closes #10753 *railsjitsu* + +* Fixtures: removed support for the ancient pre-YAML file format. #10736 *John Barnette* + +* More thoroughly quote table names. #10698 *dimdenis, lotswholetime, Jeremy Kemper* + +* update_all ignores scoped :order and :limit, so post.comments.update_all doesn't try to include the comment order in the update statement. #10686 *Brendan Ribera* + +* Added ActiveRecord::Base.cache_key to make it easier to cache Active Records in combination with the new ActiveSupport::Cache::* libraries *David Heinemeier Hansson* + +* Make sure CSV fixtures are compatible with ruby 1.9's new csv implementation. *JEG2* + +* Added by parameter to increment, decrement, and their bang varieties so you can do player1.increment!(:points, 5) #10542 *Sam* + +* Optimize ActiveRecord::Base#exists? to use #select_all instead of #find. Closes #10605 *jamesh, Frederick Cheung, protocool* + +* Don't unnecessarily load has_many associations in after_update callbacks. Closes #6822 *stopdropandrew, canadaduane* + +* Eager belongs_to :include infers the foreign key from the association name rather than the class name. #10517 *Jonathan Viney* + +* SQLite: fix rename_ and remove_column for columns with unique indexes. #10576 *Brandon Keepers* + +* Ruby 1.9 compatibility. #10655 *Jeremy Kemper, Dirkjan Bussink* + + +## 2.0.2 (December 16th, 2007) ## + +* Ensure optimistic locking handles nil #lock_version values properly. Closes #10510 *Rick Olson* + +* Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases. Closes #10379 *brynary* + +* Fix that validates_acceptance_of still works for non-existent tables (useful for bootstrapping new databases). Closes #10474 *Josh Susser* + +* Ensure that the :uniq option for has_many :through associations retains the order. #10463 *remvee* + +* Base.exists? doesn't rescue exceptions to avoid hiding SQL errors. #10458 *Michael Klishin* + +* Documentation: Active Record exceptions, destroy_all and delete_all. #10444, #10447 *Michael Klishin* + + +## 2.0.1 (December 7th, 2007) ## + +* Removed query cache rescue as it could cause code to be run twice (closes #10408) *David Heinemeier Hansson* + + +## 2.0.0 (December 6th, 2007) ## + +* Anchor DateTimeTest to fixed DateTime instead of a variable value based on Time.now#advance#to_datetime, so that this test passes on 64-bit platforms running Ruby 1.8.6+ *Geoff Buesing* + +* Fixed that the Query Cache should just be ignored if the database is misconfigured (so that the "About your applications environment" works even before the database has been created) *David Heinemeier Hansson* + +* Fixed that the truncation of strings longer than 50 chars should use inspect + so newlines etc are escaped #10385 [Norbert Crombach] +* Fixed that habtm associations should be able to set :select as part of their definition and have that honored *David Heinemeier Hansson* + +* Document how the :include option can be used in Calculations::calculate. Closes #7446 *adamwiggins, ultimoamore* + +* Fix typo in documentation for polymorphic associations w/STI. Closes #7461 *johnjosephbachir* + +* Reveal that the type option in migrations can be any supported column type for your database but also include caveat about agnosticism. Closes #7531 *adamwiggins, mikong* + +* More complete documentation for find_by_sql. Closes #7912 *fearoffish* + +* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [David Heinemeier Hansson]. Example: + + render :partial => @client.becomes(Company) # renders companies/company instead of clients/client + +* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 *Cheah Chu Yeow* + +* Fix documentation typo introduced in [8250]. Closes #10339 *Henrik N* + +* Foxy fixtures: support single-table inheritance. #10234 *tom* + +* Foxy fixtures: allow mixed usage to make migration easier and more attractive. #10004 *lotswholetime* + +* Make the record_timestamps class-inheritable so it can be set per model. #10004 *tmacedo* + +* Allow validates_acceptance_of to use a real attribute instead of only virtual (so you can record that the acceptance occured) #7457 *ambethia* + +* DateTimes use Ruby's default calendar reform setting. #10201 *Geoff Buesing* + +* Dynamic finders on association collections respect association :order and :limit. #10211, #10227 *Patrick Joyce, Rick Olson, Jack Danger Canty* + +* Add 'foxy' support for fixtures of polymorphic associations. #10183 *John Barnette, David Lowenfels* + +* validates_inclusion_of and validates_exclusion_of allow formatted :message strings. #8132 *devrieda, Mike Naberezny* + +* attr_readonly behaves well with optimistic locking. #10188 *Nick Bugajski* + +* Base#to_xml supports the nil="true" attribute like Hash#to_xml. #8268 *Jonathan del Strother* + +* Change plings to the more conventional quotes in the documentation. Closes #10104 *Jack Danger Canty* + +* Fix HasManyThrough Association so it uses :conditions on the HasMany Association. Closes #9729 *Jack Danger Canty* + +* Ensure that column names are quoted. Closes #10134 *wesley.moxam* + +* Smattering of grammatical fixes to documentation. Closes #10083 *Bob Silva* + +* Enhance explanation with more examples for attr_accessible macro. Closes #8095 *fearoffish, Marcel Molina Jr.* + +* Update association/method mapping table to refected latest collection methods for has_many :through. Closes #8772 *Pratik Naik* + +* Explain semantics of having several different AR instances in a transaction block. Closes #9036 *jacobat, Marcel Molina Jr.* + +* Update Schema documentation to use updated sexy migration notation. Closes #10086 *Sam Granieri* + +* Make fixtures work with the new test subclasses. *Tarmo Tänav, Michael Koziarski* + +* Introduce finder :joins with associations. Same :include syntax but with inner rather than outer joins. #10012 *RubyRedRick* + # Find users with an avatar + User.find(:all, :joins => :avatar) + + # Find posts with a high-rated comment. + Post.find(:all, :joins => :comments, :conditions => 'comments.rating > 3') + +* Associations: speedup duplicate record check. #10011 *Pratik Naik* + +* Make sure that << works on has_many associations on unsaved records. Closes #9989 *Josh Susser* + +* Allow association redefinition in subclasses. #9346 *wildchild* + +* Fix has_many :through delete with custom foreign keys. #6466 *naffis* + +* Foxy fixtures, from rathole (http://svn.geeksomnia.com/rathole/trunk/README) + - stable, autogenerated IDs + - specify associations (belongs_to, has_one, has_many) by label, not ID + - specify HABTM associations as inline lists + - autofill timestamp columns + - support YAML defaults + - fixture label interpolation + Enabled for fixtures that correspond to a model class and don't specify a primary key value. #9981 *John Barnette* + +* Add docs explaining how to protect all attributes using attr_accessible with no arguments. Closes #9631 *boone, rmm5t* + +* Update add_index documentation to use new options api. Closes #9787 *Kamal Fariz Mahyuddin* + +* Allow find on a has_many association defined with :finder_sql to accept id arguments as strings like regular find does. Closes #9916 *krishna* + +* Use VALID_FIND_OPTIONS when resolving :find scoping rather than hard coding the list of valid find options. Closes #9443 *sur* + +* Limited eager loading no longer ignores scoped :order. Closes #9561 *Jack Danger Canty, Josh Peek* + +* Assigning an instance of a foreign class to a composed_of aggregate calls an optional conversion block. Refactor and simplify composed_of implementation. #6322 *brandon, Chris Cruft* + +* Assigning nil to a composed_of aggregate also sets its immediate value to nil. #9843 *Chris Cruft* + +* Ensure that mysql quotes table names with database names correctly. Closes #9911 *crayz* + + "foo.bar" => "`foo`.`bar`" + +* Complete the assimilation of Sexy Migrations from ErrFree *Chris Wanstrath, PJ Hyett* + http://errtheblog.com/post/2381 + +* Qualified column names work in hash conditions, like :conditions => { 'comments.created_at' => ... }. #9733 *Jack Danger Canty* + +* Fix regression where the association would not construct new finder SQL on save causing bogus queries for "WHERE owner_id = NULL" even after owner was saved. #8713 *Bryan Helmkamp* + +* Refactor association create and build so before & after callbacks behave consistently. #8854 *Pratik Naik, mortent* + +* Quote table names. Defaults to column quoting. #4593 *Justin Lynn, gwcoffey, eadz, Dmitry V. Sabanin, Jeremy Kemper* + +* Alias association #build to #new so it behaves predictably. #8787 *Pratik Naik* + +* Add notes to documentation regarding attr_readonly behavior with counter caches and polymorphic associations. Closes #9835 *saimonmoore, Rick Olson* + +* Observers can observe model names as symbols properly now. Closes #9869 *queso* + +* find_and_(initialize|create)_by methods can now properly initialize protected attributes *Tobias Lütke* + +* belongs_to infers the foreign key from the association name instead of from the class name. *Jeremy Kemper* + +* PostgreSQL: support multiline default values. #7533 *Carl Lerche, aguynamedryan, Rein Henrichs, Tarmo Tänav* + +* MySQL: fix change_column on not-null columns that don't accept dfeault values of ''. #6663 *Jonathan Viney, Tarmo Tänav* + +* validates_uniqueness_of behaves well with abstract superclasses and + single-table inheritance. #3833, #9886 [Gabriel Gironda, rramdas, François Beausoleil, Josh Peek, Tarmo Tänav, pat] +* Warn about protected attribute assigments in development and test environments when mass-assigning to an attr_protected attribute. #9802 *Henrik N* + +* Speedup database date/time parsing. *Jeremy Kemper, Tarmo Tänav* + +* Fix calling .clear on a has_many :dependent=>:delete_all association. *Tarmo Tänav* + +* Allow change_column to set NOT NULL in the PostgreSQL adapter *Tarmo Tänav* + +* Fix that ActiveRecord would create attribute methods and override custom attribute getters if the method is also defined in Kernel.methods. *Rick Olson* + +* Don't call attr_readonly on polymorphic belongs_to associations, in case it matches the name of some other non-ActiveRecord class/module. *Rick Olson* + +* Try loading activerecord-<adaptername>-adapter gem before trying a plain require so you can use custom gems for the bundled adapters. Also stops gems from requiring an adapter from an old Active Record gem. *Jeremy Kemper, Derrick Spell* + + +## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.14.2 - 1.15.3 ## + +* Add attr_readonly to specify columns that are skipped during a normal ActiveRecord #save operation. Closes #6896 *Dan Manges* + + class Comment < ActiveRecord::Base + # Automatically sets Article#comments_count as readonly. + belongs_to :article, :counter_cache => :comments_count + end + + class Article < ActiveRecord::Base + attr_readonly :approved_comments_count + end + +* Make size for has_many :through use counter cache if it exists. Closes #9734 *Xavier Shay* + +* Remove DB2 adapter since IBM chooses to maintain their own adapter instead. *Jeremy Kemper* + +* Extract Oracle, SQLServer, and Sybase adapters into gems. *Jeremy Kemper* + +* Added fixture caching that'll speed up a normal fixture-powered test suite between 50% and 100% #9682 *Frederick Cheung* + +* Correctly quote id list for limited eager loading. #7482 *tmacedo* + +* Fixed that using version-targetted migrates would fail on loggers other than the default one #7430 *valeksenko* + +* Fixed rename_column for SQLite when using symbols for the column names #8616 *drodriguez* + +* Added the possibility of using symbols in addition to concrete classes with ActiveRecord::Observer#observe. #3998 *Robby Russell, Tarmo Tänav* + +* Added ActiveRecord::Base#to_json/from_json *David Heinemeier Hansson, Cheah Chu Yeow* + +* Added ActiveRecord::Base#from_xml [David Heinemeier Hansson]. Example: + + xml = "<person><name>David</name></person>" + Person.new.from_xml(xml).name # => "David" + +* Define dynamic finders as real methods after first usage. *bscofield* + +* Deprecation: remove deprecated threaded_connections methods. Use allow_concurrency instead. *Jeremy Kemper* + +* Associations macros accept extension blocks alongside modules. #9346 *Josh Peek* + +* Speed up and simplify query caching. *Jeremy Kemper* + +* connection.select_rows 'sql' returns an array (rows) of arrays (field values). #2329 *Michael Schuerig* + +* Eager loading respects explicit :joins. #9496 *dasil003* + +* Extract Firebird, FrontBase, and OpenBase adapters into gems. #9508, #9509, #9510 *Jeremy Kemper* + +* RubyGem database adapters: expects a gem named activerecord-<database>-adapter with active_record/connection_adapters/<database>_adapter.rb in its load path. *Jeremy Kemper* + +* Fixed that altering join tables in migrations would fail w/ sqlite3 #7453 *TimoMihaljov/brandon* + +* Fix association writer with :dependent => :nullify. #7314 *Jonathan Viney* + +* OpenBase: update for new lib and latest Rails. Support migrations. #8748 *dcsesq* + +* Moved acts_as_tree into a plugin of the same name on the official Rails svn. #9514 *Pratik Naik* + +* Moved acts_as_nested_set into a plugin of the same name on the official Rails svn. #9516 *Josh Peek* + +* Moved acts_as_list into a plugin of the same name on the official Rails svn. *Josh Peek* + +* Explicitly require active_record/query_cache before using it. *Jeremy Kemper* + +* Fix bug where unserializing an attribute attempts to modify a frozen @attributes hash for a deleted record. *Rick Olson, marclove* + +* Performance: absorb instantiate and initialize_with_callbacks into the Base methods. *Jeremy Kemper* + +* Fixed that eager loading queries and with_scope should respect the :group option *David Heinemeier Hansson* + +* Improve performance and functionality of the postgresql adapter. Closes #8049 *roderickvd* + + For more information see: http://dev.rubyonrails.org/ticket/8049 + +* Don't clobber includes passed to has_many.count *Jack Danger Canty* + +* Make sure has_many uses :include when counting *Jack Danger Canty* + +* Change the implementation of ActiveRecord's attribute reader and writer methods *Michael Koziarski* + - Generate Reader and Writer methods which cache attribute values in hashes. This is to avoid repeatedly parsing the same date or integer columns. - Change exception raised when users use find with :select then try to access a skipped column. Plugins could override missing_attribute() to lazily load the columns. - Move method definition to the class, instead of the instance - Always generate the readers, writers and predicate methods. +* Perform a deep #dup on query cache results so that modifying activerecord attributes does not modify the cached attributes. *Rick Olson* + + \# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [Pratik Naik] +* Added :unless clause to validations #8003 [monki]. Example: + + def using_open_id? + !identity_url.blank? + end + + validates_presence_of :identity_url, :if => using_open_id? + validates_presence_of :username, :unless => using_open_id? + validates_presence_of :password, :unless => using_open_id? + +* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 *Pratik Naik* + +* Fix and properly document/test count(column_name) usage. Closes #8999 *Pratik Naik* + +* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 *Pratik Naik* + +* Change belongs_to so that the foreign_key assumption is taken from the association name, not the class name. Closes #8992 *Josh Susser* + + OLD + belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is user_id + + NEW + belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is visitor_id + +* Remove spurious tests from deprecated_associations_test, most of these aren't deprecated, and are duplicated in associations_test. Closes #8987 *Pratik Naik* + +* Make create! on a has_many :through association return the association object. Not the collection. Closes #8786 *Pratik Naik* + +* Move from select * to select tablename.* to avoid clobbering IDs. Closes #8889 *dasil003* + +* Don't call unsupported methods on associated objects when using :include, :method with to_xml #7307, *Manfred Stienstra, jwilger* + +* Define collection singular ids method for has_many :through associations. #8763 *Pratik Naik* + +* Array attribute conditions work with proxied association collections. #8318 *Kamal Fariz Mahyuddin, theamazingrando* + +* Fix polymorphic has_one associations declared in an abstract class. #8638 *Pratik Naik, Dax Huiberts* + +* Fixed validates_associated should not stop on the first error. #4276 *mrj, Manfred Stienstra, Josh Peek* + +* Rollback if commit raises an exception. #8642 *kik, Jeremy Kemper* + +* Update tests' use of fixtures for the new collections api. #8726 *Kamal Fariz Mahyuddin* + +* Save associated records only if the association is already loaded. #8713 *Blaine* + +* MySQL: fix show_variable. #8448 *matt, Jeremy Kemper* + +* Fixtures: correctly delete and insert fixtures in a single transaction. #8553 *Michael Schuerig* + +* Fixtures: people(:technomancy, :josh) returns both fixtures. #7880 *technomancy, Josh Peek* + +* Calculations support non-numeric foreign keys. #8154 *Kamal Fariz Mahyuddin* + +* with_scope is protected. #8524 *Josh Peek* + +* Quickref for association methods. #7723 *marclove, Mindsweeper* + +* Calculations: return nil average instead of 0 when there are no rows to average. #8298 *davidw* + +* acts_as_nested_set: direct_children is sorted correctly. #4761 *Josh Peek, rails@33lc0.net* + +* Raise an exception if both attr_protected and attr_accessible are declared. #8507 *stellsmi* + +* SQLite, MySQL, PostgreSQL, Oracle: quote column names in column migration SQL statements. #8466 *marclove, lorenjohnson* + +* Allow nil serialized attributes with a set class constraint. #7293 *sandofsky* + +* Oracle: support binary fixtures. #7987 *Michael Schoen* + +* Fixtures: pull fixture insertion into the database adapters. #7987 *Michael Schoen* + +* Announce migration versions as they're performed. *Jeremy Kemper* + +* find gracefully copes with blank :conditions. #7599 *Dan Manges, johnnyb* + +* validates_numericality_of takes :greater_than, :greater_than_or_equal_to, :equal_to, :less_than, :less_than_or_equal_to, :odd, and :even options. #3952 *Bob Silva, Dan Kubb, Josh Peek* + +* MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. #8448 *matt* + +* Find with a list of ids supports limit/offset. #8437 *hrudududu* + +* Optimistic locking: revert the lock version when an update fails. #7840 *plang* + +* Migrations: add_column supports custom column types. #7742 *jsgarvin, Theory* + +* Load database adapters on demand. Eliminates config.connection_adapters and RAILS_CONNECTION_ADAPTERS. Add your lib directory to the $LOAD_PATH and put your custom adapter in lib/active_record/connection_adapters/adaptername_adapter.rb. This way you can provide custom adapters as plugins or gems without modifying Rails. *Jeremy Kemper* + +* Ensure that associations with :dependent => :delete_all respect :conditions option. Closes #8034 *Jack Danger Canty, Josh Peek, Rick Olson* + +* belongs_to assignment creates a new proxy rather than modifying its target in-place. #8412 *mmangino@elevatedrails.com* + +* Fix column type detection while loading fixtures. Closes #7987 *roderickvd* + +* Document deep eager includes. #6267 *Josh Susser, Dan Manges* + +* Document warning that associations names shouldn't be reserved words. #4378 *murphy@cYcnus.de, Josh Susser* + +* Sanitize Base#inspect. #8392, #8623 *Nik Wakelin, jnoon* + +* Replace the transaction {|transaction|..} semantics with a new Exception ActiveRecord::Rollback. *Michael Koziarski* + +* Oracle: extract column length for CHAR also. #7866 *ymendel* + +* Document :allow_nil option for validates_acceptance_of since it defaults to true. *tzaharia* + +* Update documentation for :dependent declaration so that it explicitly uses the non-deprecated API. *Jack Danger Canty* + +* Add documentation caveat about when to use count_by_sql. *fearoffish* + +* Enhance documentation for increment_counter and decrement_counter. *fearoffish* + +* Provide brief introduction to what optimistic locking is. *fearoffish* + +* Add documentation for :encoding option to mysql adapter. *marclove* + +* Added short-hand declaration style to migrations (inspiration from Sexy Migrations, http://errtheblog.com/post/2381) [David Heinemeier Hansson]. Example: + + create_table "products" do |t| + t.column "shop_id", :integer + t.column "creator_id", :integer + t.column "name", :string, :default => "Untitled" + t.column "value", :string, :default => "Untitled" + t.column "created_at", :datetime + t.column "updated_at", :datetime + end + + ...can now be written as: + + create_table :products do |t| + t.integer :shop_id, :creator_id + t.string :name, :value, :default => "Untitled" + t.timestamps + end + +* Use association name for the wrapper element when using .to_xml. Previous behavior lead to non-deterministic situations with STI and polymorphic associations. *Michael Koziarski, jstrachan* + +* Improve performance of calling .create on has_many :through associations. *evan* + +* Improved cloning performance by relying less on exception raising #8159 *Blaine* + +* Added ActiveRecord::Base.inspect to return a column-view like #<Post id:integer, title:string, body:text> *David Heinemeier Hansson* + +* Added yielding of Builder instance for ActiveRecord::Base#to_xml calls *David Heinemeier Hansson* + +* Small additions and fixes for ActiveRecord documentation. Closes #7342 *Jeremy McAnally* + +* Add helpful debugging info to the ActiveRecord::StatementInvalid exception in ActiveRecord::ConnectionAdapters::SqliteAdapter#table_structure. Closes #7925. *court3nay* + +* SQLite: binary escaping works with $KCODE='u'. #7862 *tsuka* + +* Base#to_xml supports serialized attributes. #7502 *jonathan* + +* Base.update_all :order and :limit options. Useful for MySQL updates that must be ordered to avoid violating unique constraints. *Jeremy Kemper* + +* Remove deprecated object transactions. People relying on this functionality should install the object_transactions plugin at http://code.bitsweat.net/svn/object_transactions. Closes #5637 *Michael Koziarski, Jeremy Kemper* + +* PostgreSQL: remove DateTime -> Time downcast. Warning: do not enable translate_results for the C bindings if you have timestamps outside Time's domain. *Jeremy Kemper* + +* find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. For example, Person.find_or_create_by_name(:name => 'Henry', :comments => 'Hi new user!') is equivalent to Person.find_by_name('Henry') || Person.create(:name => 'Henry', :comments => 'Hi new user!'). #7368 *Josh Susser* + +* Make sure with_scope takes both :select and :joins into account when setting :readonly. Allows you to save records you retrieve using method_missing on a has_many :through associations. *Michael Koziarski* + +* Allow a polymorphic :source for has_many :through associations. Closes #7143 *protocool* + +* Consistent public/protected/private visibility for chained methods. #7813 *Dan Manges* + +* Oracle: fix quoted primary keys and datetime overflow. #7798 *Michael Schoen* + +* Consistently quote primary key column names. #7763 *toolmantim* + +* Fixtures: fix YAML ordered map support. #2665 *Manuel Holtgrewe, nfbuckley* + +* DateTimes assume the default timezone. #7764 *Geoff Buesing* + +* Sybase: hide timestamp columns since they're inherently read-only. #7716 *Mike Joyce* + +* Oracle: overflow Time to DateTime. #7718 *Michael Schoen* + +* PostgreSQL: don't use async_exec and async_query with postgres-pr. #7727, #7762 *flowdelic, toolmantim* + +* Fix has_many :through << with custom foreign keys. #6466, #7153 *naffis, Rich Collins* + +* Test DateTime native type in migrations, including an edge case with dates + during calendar reform. #7649, #7724 [fedot, Geoff Buesing] +* SQLServer: correctly schema-dump tables with no indexes or descending indexes. #7333, #7703 *Jakob Skjerning, Tom Ward* + +* SQLServer: recognize real column type as Ruby float. #7057 *sethladd, Tom Ward* + +* Added fixtures :all as a way of loading all fixtures in the fixture directory at once #7214 *Manfred Stienstra* + +* Added database connection as a yield parameter to ActiveRecord::Base.transaction so you can manually rollback [David Heinemeier Hansson]. Example: + + transaction do |transaction| + david.withdrawal(100) + mary.deposit(100) + transaction.rollback! # rolls back the transaction that was otherwise going to be successful + end + +* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method *Jamis Buck* + +* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however *Tobias Lütke* + Task.cache { Task.find(1); Task.find(1) } # => 1 query + +* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck* + +* Oracle: fix lob and text default handling. #7344 *gfriedrich, Michael Schoen* + +* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning* + +* MySQL: blob and text columns may not have defaults in 5.x. Update fixtures schema for strict mode. #6695 *Dan Kubb* + +* update_all can take a Hash argument. sanitize_sql splits into two methods for conditions and assignment since NULL values and delimiters are handled differently. #6583, #7365 *sandofsky, Assaf* + +* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc* + +* Use Date#to_s(:db) for quoted dates. #7411 *Michael Schoen* + +* Don't create instance writer methods for class attributes. Closes #7401 *Rick Olson* + +* Docs: validations examples. #7343 *zackchandler* + +* Add missing tests ensuring callbacks work with class inheritance. Closes #7339 *sandofsky* + +* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden* + +* Remove useless code in #attribute_present? since 0 != blank?. Closes #7249 *Josh Susser* + +* Fix minor doc typos. Closes #7157 *Josh Susser* + +* Fix incorrect usage of #classify when creating the eager loading join statement. Closes #7044 *Josh Susser* + +* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org* + +* Subclasses of an abstract class work with single-table inheritance. #5704, #7284 *BertG, nick+rails@ag.arizona.edu* + +* Make sure sqlite3 driver closes open connections on disconnect *Rob Rasmussen* + +* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally* + +* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper* + +* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com* + +* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen* + +* MySQL: retain SSL settings on reconnect. #6976 *randyv2* + +* Apply scoping during initialize instead of create. Fixes setting of foreign key when using find_or_initialize_by with scoping. *Cody Fauser* + +* SQLServer: handle [quoted] table names. #6635 *rrich* + +* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser* + +* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen* + +* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges* + Student.find(:all, :conditions => { :grade => 9..12 }) + +* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler* + +* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell* + +* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot* + +* Bring the sybase adapter up to scratch for 1.2 release. *jsheets* + +* Rollback new_record? and id when an exception is raised in a save callback. #6910 *Ben Curren, outerim* + +* Pushing a record on an association collection doesn't unnecessarily load all the associated records. *Obie Fernandez, Jeremy Kemper* + +* Oracle: fix connection reset failure. #6846 *leonlleslie* + +* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper* + +* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool* + +* Consolidated different create and create! versions to call through to the base class with scope. This fixes inconsistencies, especially related to protected attribtues. Closes #5847 *Alexander Dymo, Tobias Lütke* + +* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper* + +* Add AssociationCollection#create! to be consistent with AssociationCollection#create when dealing with a foreign key that is a protected attribute *Cody Fauser* + +* Added counter optimization for AssociationCollection#any? so person.friends.any? won't actually load the full association if we have the count in a cheaper form *David Heinemeier Hansson* + +* Change fixture_path to a class inheritable accessor allowing test cases to have their own custom set of fixtures. #6672 *Zach Dennis* + +* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov* + +* Simplify query_attribute by typecasting the attribute value and checking whether it's nil, false, zero or blank. #6659 *Jonathan Viney* + +* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz* + +* Run validations in the order they were declared. #6657 *obrie* + +* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper* + +* Simplify association proxy implementation by factoring construct_scope out of method_missing. #6643 *martin* + +* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen* + +* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen* + +* Don't inspect unloaded associations. #2905 *lmarlow* + +* SQLite: use AUTOINCREMENT primary key in >= 3.1.0. #6588, #6616 *careo, lukfugl* + +* Cache inheritance_column. #6592 *Stefan Kaes* + +* Firebird: decimal/numeric support. #6408 *macrnic* + +* make add_order a tad faster. #6567 *Stefan Kaes* + +* Find with :include respects scoped :order. #5850 + +* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper* + find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } + +* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si* + +* SQLite: fix calculations workaround, remove count(distinct) query rewrite, cleanup test connection scripts. *Jeremy Kemper* + +* SQLite: count(distinct) queries supported in >= 3.2.6. #6544 *Bob Silva* + +* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes* + +* Deprecation: object transactions warning. *Jeremy Kemper* + +* has_one :dependent => :nullify ignores nil associates. #4848, #6528 *bellis@deepthought.org, janovetz, Jeremy Kemper* + +* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen* + +* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie* + +* Document other options available to migration's add_column. #6419 *grg* + +* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper* + +* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney* + +* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson* + +* Restore eager condition interpolation, document it's differences *Rick Olson* + +* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper* + +* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers* + +* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson* + +* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com* + +* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com* + +* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan* + +* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva* + +* The has_many create method works with polymorphic associations. #6361 *Dan Peterson* + +* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes* + +* save! shouldn't validate twice. #6324 *maiha, Bob Silva* + +* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig* + +* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson* + +* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva* + +* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper* + +* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski* + +* Add a :namespace option to AR::Base#to_xml *Michael Koziarski* + +* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper* + +* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson* + +* Improve yaml fixtures error reporting. #6205 *Bruce Williams* + +* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski* + +* Add deprecation warning for inferred foreign key. #6029 *Josh Susser* + +* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com* + +* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser* + +* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 *Bob Silva* + +* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward* + +* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher* + +* Deprecation: update docs. #5998 *Jakob Skjerning, Kevin Clark* + +* Add some XmlSerialization tests for ActiveRecord *Rick Olson* + +* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com* + +* Tighten rescue clauses. #5985 *james@grayproductions.net* + +* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck* + +* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney* + +* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney* + +* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi* + +* SQLServer: fix eager association test. #5901 *Tom Ward* + +* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark* + +* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com* + +* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com* + +* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward* + +* to_xml: correct naming of included associations. #5831 *Josh Starcher* + +* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser* + +* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper* + + # Create a tagging to associate the post and tag. + post.tags << Tag.find_by_name('old') + post.tags.create! :name => 'general' + + # Would have been: + post.taggings.create!(:tag => Tag.find_by_name('finally') + transaction do + post.taggings.create!(:tag => Tag.create!(:name => 'general')) + end + +* Cache nil results for :included has_one associations also. #5787 *Michael Schoen* + +* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke* + +* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper* + Example: Invoice::Lineitem is given table name invoice_lineitems + +* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper* + # people_active_last_name_index, people_active_deactivated_at_index + add_index :people, [:active, :last_name] + add_index :people, [:active, :deactivated_at] + remove_index :people, [:active, :last_name] + remove_index :people, [:active, :deactivated_at] + + WARNING: backward-incompatibility. Multicolumn indexes created before this + revision were named using the first column name only. Now they're uniquely + named using all indexed columns. + + To remove an old multicolumn index, remove_index :table_name, :first_column + +* Fix for deep includes on the same association. *richcollins@gmail.com* + +* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark* + +* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson* + +* Document find's :from option. Closes #5762. *andrew@redlinesoftware.com* + +* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com* + +* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar* + +* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen* + +* Add documentation for how to disable timestamps on a per model basis. Closes #5684. *matt@mattmargolis.net Marcel Molina Jr.* + +* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney* + +* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson* + +* Formally deprecate the deprecated finders. *Michael Koziarski* + +* Formally deprecate rich associations. *Michael Koziarski* + +* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com* + +* Fix announcement of very long migration names. #5722 *blake@near-time.com* + +* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com* + +* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com* + +* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: + + assert (Topic.exists?(:author_name => "David")) + assert (Topic.exists?(:author_name => "Mary", :approved => true)) + assert (Topic.exists?(["parent_id = ?", 1])) + +* Schema dumper quotes date :default values. *Dave Thomas* + +* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson* + +* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper* + +* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck* + +* Allow #count through a has_many association to accept :include. *Dan Peterson* + +* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw* + +* PostgreSQL: return array fields as strings. #4664 *Robby Russell* + +* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward* + +* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers* + +* Oracle: BigDecimal support. #5667 *Michael Schoen* + +* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk* + +* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>* + +* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com* + +* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>* + +* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net* + +* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com* + +* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net* + +* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen* + +* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen* + +* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org* + +* Minor tweak to improve performance of ActiveRecord::Base#to_param. + +* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au* + +* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper* + +* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com* + +* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com* + +* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. + +* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson* + +* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda* + # Obtain an exclusive lock on person 1 so we can safely increment visits. + Person.transaction do + # select * from people where id=1 for update + person = Person.find(1, :lock => true) + person.visits += 1 + person.save! + end + +* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper* + +* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper* + +* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar* + +* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) + +* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson* + +* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: + + Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) + + ...is the same as: + Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) + + This makes it easier to pass in the options from a form or otherwise outside. + + +* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com* + +* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net* + +* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com* + +* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com* + +* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp* + +* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net* + +* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>* + +* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp* + +* Records and arrays of records are bound as quoted ids. *Jeremy Kemper* + Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) + Foo.find(:first, :conditions => ['bar_id = ?', bar]) + +* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson* + +* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson* + +* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser* + +* Provide Association Extensions access to the instance that the association is being accessed from. + Closes #4433 *Josh Susser* + +* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell* + +* Add a quick note about :select and eagerly included associations. *Rick Olson* + +* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com* + +* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson* + +* Added :allow_nil option for aggregations #5091 *Ian White* + +* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen* + +* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper* + +* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com* + +* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk* + +* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org* + +* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com* + +* Allow :uniq => true with has_many :through associations. *Jeremy Kemper* + +* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.* + +* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com* + +* Replace superfluous name_to_class_name variant with camelize. *Marcel Molina Jr.* + +* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.* + +* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.* + +* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>* + +* Update FrontBase adapter to check binding version. Closes #4920. *mlaster@metavillage.com* + +* New Frontbase connections don't start in auto-commit mode. Closes #4922. *mlaster@metavillage.com* + +* When grouping, use the appropriate option key. *Marcel Molina Jr.* + +* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. *Marcel Molina Jr.* + +* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com* + +* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>* + +* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić* + +* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu* + +* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com* + +* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net* + +* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>* + +* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com* + +* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net* + +* Fix bug where calculations with long alias names return null. *Rick Olson* + +* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson* + + @post.tags << @tag # BAD + @post.taggings.create(:tag => @tag) # GOOD + +* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson* + +* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com* + +* Add ActiveRecord::Errors#to_xml *Jamis Buck* + +* Properly quote index names in migrations (closes #4764) *John Long* + +* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson* + +* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson* + +* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson* + +* DRY up association collection reader method generation. *Marcel Molina Jr.* + +* DRY up and tweak style of the validation error object. *Marcel Molina Jr.* + +* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson* + + class Account < ActiveRecord::Base + validates_uniqueness_of :email, :case_sensitive => false + end + +* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser* + + class Account < ActiveRecord::Base + has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] + end + + *1.15.3* (March 12th, 2007) + + * Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool] + + * Consistently quote primary key column names. #7763 [toolmantim] + + * Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley] + + * Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins] + + +## 1.15.2 (February 5th, 2007) ## + +* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges* + Student.find(:all, :conditions => { :grade => 9..12 }) + +* Don't create instance writer methods for class attributes. *Rick Olson* + +* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck* + +* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning* + +* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si* + +* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc* + +* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden* + +* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org* + + +## 1.15.1 (January 17th, 2007) ## + +* Fix nodoc breaking of adapters + + +## 1.15.0 (January 16th, 2007) ## + +* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally* + +* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper* + +* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com* + +* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen* + +* MySQL: retain SSL settings on reconnect. #6976 *randyv2* + +* SQLServer: handle [quoted] table names. #6635 *rrich* + +* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser* + +* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen* + +* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler* + +* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell* + +* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot* + +* Bring the sybase adapter up to scratch for 1.2 release. *jsheets* + +* Oracle: fix connection reset failure. #6846 *leonlleslie* + +* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper* + +* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool* + +* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper* + +* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper* + find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } + +* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov* + +* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper* + +* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz* + +* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen* + +* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen* + +* Firebird: decimal/numeric support. #6408 *macrnic* + +* Find with :include respects scoped :order. #5850 + +* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes* + +* Deprecation: object transactions warning. *Jeremy Kemper* + +* has_one :dependent => :nullify ignores nil associates. #6528 *janovetz, Jeremy Kemper* + +* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen* + +* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie* + +* Document other options available to migration's add_column. #6419 *grg* + +* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper* + +* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney* + +* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson* + +* Restore eager condition interpolation, document it's differences *Rick Olson* + +* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper* + +* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers* + +* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson* + +* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com* + +* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com* + +* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan* + +* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva* + +* The has_many create method works with polymorphic associations. #6361 *Dan Peterson* + +* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes* + +* save! shouldn't validate twice. #6324 *maiha, Bob Silva* + +* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig* + +* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson* + +* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva* + +* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper* + +* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski* + +* Add a :namespace option to AR::Base#to_xml *Michael Koziarski* + +* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper* + +* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson* + +* Improve yaml fixtures error reporting. #6205 *Bruce Williams* + +* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski* + +* Add deprecation warning for inferred foreign key. #6029 *Josh Susser* + +* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com* + +* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser* + +* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward* + +* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher* + +* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com* + +* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck* + +* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney* + +* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney* + +* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi* + +* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark* + +* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com* + +* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com* + +* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward* + +* to_xml: correct naming of included associations. #5831 *Josh Starcher* + +* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser* + +* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper* + + # Create a tagging to associate the post and tag. + post.tags << Tag.find_by_name('old') + post.tags.create! :name => 'general' + + # Would have been: + post.taggings.create!(:tag => Tag.find_by_name('finally') + transaction do + post.taggings.create!(:tag => Tag.create!(:name => 'general')) + end + +* Cache nil results for :included has_one associations also. #5787 *Michael Schoen* + +* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke* + +* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper* + Example: Invoice::Lineitem is given table name invoice_lineitems + +* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper* + # people_active_last_name_index, people_active_deactivated_at_index + add_index :people, [:active, :last_name] + add_index :people, [:active, :deactivated_at] + remove_index :people, [:active, :last_name] + remove_index :people, [:active, :deactivated_at] + + WARNING: backward-incompatibility. Multicolumn indexes created before this + revision were named using the first column name only. Now they're uniquely + named using all indexed columns. + + To remove an old multicolumn index, remove_index :table_name, :first_column + +* Fix for deep includes on the same association. *richcollins@gmail.com* + +* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark* + +* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson* + +* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com* + +* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar* + +* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen* + +* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney* + +* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson* + +* Formally deprecate the deprecated finders. *Michael Koziarski* + +* Formally deprecate rich associations. *Michael Koziarski* + +* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com* + +* Fix announcement of very long migration names. #5722 *blake@near-time.com* + +* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com* + +* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com* + +* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: + + assert (Topic.exists?(:author_name => "David")) + assert (Topic.exists?(:author_name => "Mary", :approved => true)) + assert (Topic.exists?(["parent_id = ?", 1])) + +* Schema dumper quotes date :default values. *Dave Thomas* + +* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson* + +* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper* + +* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck* + +* Allow #count through a has_many association to accept :include. *Dan Peterson* + +* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw* + +* PostgreSQL: return array fields as strings. #4664 *Robby Russell* + +* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward* + +* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers* + +* Oracle: BigDecimal support. #5667 *Michael Schoen* + +* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk* + +* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>* + +* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com* + +* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net* + +* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com* + +* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net* + +* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen* + +* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen* + +* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org* + +* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au* + +* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper* + +* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com* + +* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com* + +* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. + +* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson* + +* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda* + # Obtain an exclusive lock on person 1 so we can safely increment visits. + Person.transaction do + # select * from people where id=1 for update + person = Person.find(1, :lock => true) + person.visits += 1 + person.save! + end + +* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper* + +* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper* + +* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar* + +* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) + +* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson* + +* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: + + Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) + + ...is the same as: + Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) + + This makes it easier to pass in the options from a form or otherwise outside. + + +* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com* + +* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net* + +* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com* + +* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com* + +* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp* + +* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net* + +* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>* + +* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp* + +* Records and arrays of records are bound as quoted ids. *Jeremy Kemper* + Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) + Foo.find(:first, :conditions => ['bar_id = ?', bar]) + +* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson* + +* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson* + +* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser* + +* Provide Association Extensions access to the instance that the association is being accessed from. + Closes #4433 *Josh Susser* + +* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell* + +* Add a quick note about :select and eagerly included associations. *Rick Olson* + +* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com* + +* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson* + +* Added :allow_nil option for aggregations #5091 *Ian White* + +* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen* + +* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper* + +* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com* + +* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk* + +* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org* + +* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com* + +* Allow :uniq => true with has_many :through associations. *Jeremy Kemper* + +* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.* + +* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com* + +* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>* + +* When grouping, use the appropriate option key. *Marcel Molina Jr.* + +* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com* + +* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>* + +* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić* + +* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu* + +* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com* + +* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net* + +* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>* + +* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com* + +* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net* + +* Fix bug where calculations with long alias names return null. *Rick Olson* + +* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson* + + @post.tags << @tag # BAD + @post.taggings.create(:tag => @tag) # GOOD + +* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson* + +* Add ActiveRecord::Errors#to_xml *Jamis Buck* + +* Properly quote index names in migrations (closes #4764) *John Long* + +* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson* + +* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson* + +* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson* + +* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson* + + class Account < ActiveRecord::Base + validates_uniqueness_of :email, :case_sensitive => false + end + +* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser* + + class Account < ActiveRecord::Base + has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] + end + + +## 1.14.4 (August 8th, 2006) ## + +* Add warning about the proper way to validate the presence of a foreign key. #4147 *Francois Beausoleil <francois.beausoleil@gmail.com>* + +* Fix syntax error in documentation. #4679 *Mislav Marohnić* + +* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com* + + +## 1.14.3 (June 27th, 2006) ## + +* Fix announcement of very long migration names. #5722 *blake@near-time.com* + +* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>* + +* Properly quote index names in migrations (closes #4764) *John Long* + +* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson* + +* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson* + + +## 1.14.2 (April 9th, 2006) ## + +* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen* + + +## 1.14.1 (April 6th, 2006) ## + +* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar* + +* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind* + +* Enable Limit/Offset in Calculations (closes #4558) *lmarlow* + +* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson* + +* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr* + +* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis* + +* Support eager includes when going through a polymorphic has_many association. *Rick Olson* + +* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson* + + class Post < ActiveRecord::Base + has_one :tagging, :as => :taggable + end + + Post.find :all, :include => :tagging + +* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson* + +* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson* + + class PhotoCollection < ActiveRecord::Base + has_many :photos, :as => :photographic + belongs_to :firm + end + + class Firm < ActiveRecord::Base + has_many :photo_collections + has_many :photos, :through => :photo_collections + end + +* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com* + +* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber* + +* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan* + +* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson* + +* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson* + +* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson* + +* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.* + +* Fixed broken OCIAdapter #4457 *Michael Schoen* + + +## 1.14.0 (March 27th, 2006) ## + +* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar* + +* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson* + +* Add support for :include to with_scope *andrew@redlinesoftware.com* + +* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen* + +* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com* + +* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson* + +* Fixed issue that kept :select options from being scoped *Rick Olson* + +* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson* + +* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson* + +* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson* + + class Connection < ActiveRecord::Base + belongs_to :user + belongs_to :channel + end + + class Channel < ActiveRecord::Base + has_many :connections + has_many :contacts, :through => :connections, :class_name => 'User' # OLD + has_many :contacts, :through => :connections, :source => :user # NEW + end + +* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de* + +* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson* + + In this example, :include => false disables the default eager association from loading. :select changes the standard + select clause. :joins specifies a join that is added to the end of the has_many :through query. + + class Post < ActiveRecord::Base + has_many :tags, :through => :taggings, :include => :tagging do + def add_joins_and_select + find :all, :select => 'tags.*, authors.id as author_id', :include => false, + :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' + end + end + end + +* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson* + +* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney* + +* Quit ignoring default :include options in has_many :through calls *Mark James* + +* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney* + +* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson* + +* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: + + class Firm < ActiveRecord::Base + has_many :clients + has_many :invoices, :through => :clients + end + + class Client < ActiveRecord::Base + belongs_to :firm + has_many :invoices + end + + class Invoice < ActiveRecord::Base + belongs_to :client + end + +* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser* + +* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney* + +* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson* + +* SQL Server adapter gets some love #4298 *Ryan Tomayko* + +* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com* + +* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): + + Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') + +* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson* + +* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski* + +* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski* + +* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward* + +* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com* + +* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck* + +* Use association's :conditions when eager loading. [Jeremy Evans] #4144 + +* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans* + + This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. + + Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') + +* Oracle adapter gets some love #4230 *Michael Schoen* + + * Changes :text to CLOB rather than BLOB [Moses Hohman] + * Fixes an issue with nil numeric length/scales (several) + * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] + * Tweaks a unit test to get it all green again + * Adds support for #current_database + +* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson* + + class CachedModel < ActiveRecord::Base + self.abstract_class = true + end + + class Post < CachedModel + end + + CachedModel.abstract_class? + => true + + Post.abstract_class? + => false + + Post.base_class + => Post + + Post.table_name + => 'posts' + +* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson* + + class Foo < ActiveRecord::Base + has_many :attachments, :as => :attachable, :dependent => :delete_all + end + +* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay* + +* Upgrade to Transaction::Simple 1.3 *Jamis Buck* + +* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson* + +* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com* + +* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com* + +* Dynamically set allow_concurrency. #4044 *Stefan Kaes* + +* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: + + topic.to_xml + + ...returns: + + <?xml version="1.0" encoding="UTF-8"?> + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <id type="integer">1</id> + <approved type="boolean">false</approved> + <replies-count type="integer">0</replies-count> + <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> + <written-on type="datetime">2003-07-16 09:28:00</written-on> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + ...and you can configure with: + + topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) + + ...that'll return: + + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <approved type="boolean">false</approved> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + You can even do load first-level associations as part of the document: + + firm.to_xml :include => [ :account, :clients ] + + ...that'll return something like: + + <?xml version="1.0" encoding="UTF-8"?> + <firm> + <id type="integer">1</id> + <rating type="integer">1</rating> + <name>37signals</name> + <clients> + <client> + <rating type="integer">1</rating> + <name>Summit</name> + </client> + <client> + <rating type="integer">1</rating> + <name>Microsoft</name> + </client> + </clients> + <account> + <id type="integer">1</id> + <credit-limit type="integer">50</credit-limit> + </account> + </firm> + +* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck* + +* Documentation fixes for :dependent *robby@planetargon.com* + +* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney* + +* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org* + +* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson* + +* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>* + +* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson* + + * The first time a table is referenced in a join, no alias is used. + * After that, the parent class name and the reflection name are used. + + Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... + + * Any additional join references get a numerical suffix like '_2', '_3', etc. + +* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. + +* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: + + # cascaded in two levels + >> Author.find(:all, :include=>{:posts=>:comments}) + => authors + +- posts + +- comments + + # cascaded in two levels and normal association + >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in two levels with two has_many associations + >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in three levels + >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) + => companies + +- groups + +- members + +- favorites + +* Make counter cache work when replacing an association #3245 *eugenol@gmail.com* + +* Make migrations verbose *Jamis Buck* + +* Make counter_cache work with polymorphic belongs_to *Jamis Buck* + +* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp* + +* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: + + * Does not support DATE SQL column types; use DATETIME instead. + * Date columns on HABTM join tables are returned as String, not Time. + * Insertions are potentially broken for :polymorphic join tables + * BLOB column access not yet fully supported + +* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper* + +* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper* + +* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen* + +* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson* + +* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes* + +* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark* + +* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net* + +* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney* + +* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward* + +* Added support for nested scopes #3407 [anna@wota.jp]. Examples: + + Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 + + # inner rule is used. (all previous parameters are ignored) + Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') + end + + # parameters are merged + Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 + end + end + +* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com* + +* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh* + +* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind* + +* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: + + Person.average :age + Person.minimum :age + Person.maximum :age + Person.sum :salary, :group => :last_name + +* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath* + +* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper* + +* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net* + +* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de* + +* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes* + +* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva* + +* Allow :include to be used with has_many :through associations #3611 *Michael Schoen* + +* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac* + +* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward* + +* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson* + +* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org* + +* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark* + +* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke* + +* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson* + +* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar* + +* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt* + +* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda* + +* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>* + +* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen* + +* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson* + +* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.* + +* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar* + +* Make .count work for has_many associations with multi line finder sql *Michael Schoen* + +* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck* + +* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com* + +* Don't hardcode 'id' in acts as list. *ror@philippeapril.com* + +* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark* + +* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp* + +* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com* + +* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke* + +* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.* + +* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de* + +* Sanitize scoped conditions. *Marcel Molina Jr.* + +* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson* + +* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke* + +* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke* + +* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber* + +* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron* + +* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke* + +* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke* + +* made .find() work on :through relations. *Tobias Lütke* + +* Fix typo in association docs. #3296. *Blair Zajac* + +* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke* + +## 1.13.2 (December 13th, 2005) ## + +* Become part of Rails 1.0 + +* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper* + +* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: + + class Post + has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author + end + + post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors + post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors + post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors + +* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson* + +* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder* + +* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com* + +* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org* + +* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com* + +* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko* + +* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com* + +* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen* + +* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes* + +* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil* + +* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond* + +* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson* + +* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen* + +* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper* + +* Added preliminary support for polymorphic associations *David Heinemeier Hansson* + +* Added preliminary support for join models *David Heinemeier Hansson* + +* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.* + +* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>* + +* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>* + +* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper* + +* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen* + +* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com* + +* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper* + +* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen* + +* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda* + +* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper* + +* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda* + +* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.* + +* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes* + +* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes* + +* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>* + +* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans* + +* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.* + +* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>* + +* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com* + +* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>* + +* Correct documentation for Base.delete_all. #1568 *Newhydra* + +* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>* + +* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>* + +* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper* + +* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>* + +* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper* + +* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper* + +* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper* + +* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko* + +* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>* + +* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de* + +* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>* + +* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com* + +* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar* + +* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney* + +* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper* + +* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.* + +* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com* + +* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper* + +* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper* + +* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>* + + +## 1.13.0 (November 7th, 2005) ## + +* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko* + +* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: + + has_many :posts, :include => [ :author, :comments ] + +* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: + + Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do + # Find where name = ? and active=true + Comment.find :all, :conditions => ['name = ?', name] + # Create comment associated with :post_id + Comment.create :body => "Hello world" + end + +* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko* + +* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: + + Comment.constrain(:creation => { :post_id => 5 }) do + # Associated with :post_id + Comment.create :body => "Hello world" + end + + This is rarely used directly, but allows for find_or_create on associations. So you can do: + + # If the tag doesn't exist, a new one is created that's associated with the person + person.tags.find_or_create_by_name("Summer") + +* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: + + # No 'Summer' tag exists + Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") + + # Now the 'Summer' tag does exist + Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") + +* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: + + class Account < ActiveRecord::Base + has_many :people do + def find_or_create_by_name(name) + first_name, *last_name = name.split + last_name = last_name.join " " + + find_or_create_by_first_name_and_last_name(first_name, last_name) + end + end + end + + person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") + person.first_name # => "David" + person.last_name # => "Heinemeier Hansson" + + Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). + +* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko* + +* Quote column names in generated SQL. #2728 *Ryan Tomayko* + +* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper* + +* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper* + +* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>* + +* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson* + +* Added migration support for Oracle #2647 *Michael Schoen* + +* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>* + +* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko* + +* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward* + +* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward* + +* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com* + +* Constraints are cloned so they can't be inadvertently modified while they're + in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] +* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com* + +* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen* + +* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt* + + +## 1.12.2 (October 26th, 2005) ## + +* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark* + +* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>* + +* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes* + +* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>* + +* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>* + +* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>* + + +## 1.12.1 (October 19th, 2005) ## + +* Always parenthesize :conditions options so they may be safely combined with STI and constraints. + +* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com* + +* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations + + +## 1.12.0 (October 16th, 2005) ## + +* Update/clean up documentation (rdoc) + +* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>* + +* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson* + +* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net* + +* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>* + +* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. + +* Avoid memleak in dev mode when using fcgi + +* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>* + +* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>* + +* Fix errors caused by assigning a has-one or belongs-to property to itself + +* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson* + +* Update DB2 adapter. #2206. *contact@maik-schmidt.de* + +* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com* + +* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. + +* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>* + +* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code* + +* Add test coverage for content_columns. #2432. *coffee2code* + +* Speed up for unthreaded environments. #2431. *Stefan Kaes* + +* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes* + +* Speed up the setting of table_name. #2428. *Stefan Kaes* + +* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes* + +* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>* + +* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes* + +* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>* + +* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick* + +* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes* + +* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes* + +* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar* + +* Added :force option to create_table that'll try to drop the table if it already exists before creating + +* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar* + +* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>* + +* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>* + +* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman* + +* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>* + +* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>* + +* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>* + +* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>* + +* Make update_attribute use the same writer method that update_attributes uses. + \#2237 [trevor@protocool.com] +* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.* + +* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org* + +* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com* + +* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) + +* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: + + ActiveRecord::Base.observers = :cacher, :garbage_collector + +* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com* + +* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck* + +* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck* + +* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck* + +* Fixed migrations for Windows when using more than 10 *David Naseby* + +* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber* + +* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke* + +* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar* + +* Fixed that Observers didn't observe sub-classes #627 *Florian Weber* + +* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.* + +* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae* + +* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber* + +* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil* + +* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com* + +* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg* + +* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward* + +* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code* + +* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net* + +* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ + +* Make sure the schema_info table is created before querying the current version #1903 + +* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning* + +* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine* + +* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz* + +* Make destroy return self #1913 *Sebastian Kanthak* + +* Fix typo in validations documentation #1938 *court3nay* + +* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org* + +* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky* + +* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com* + +* Fix create_table so that id column is implicitly added *Rick Olson* + +* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 + +* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 + +* Fixed the handling of camelCase columns names in Oracle #1798 + +* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 + +* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 + +* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke* + + class Comment < AR:B + def self.search(q) + find(:all, :conditions => ["body = ?", q]) + end + end + + class Post < AR:B + has_many :comments + end + + Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' + + NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as + by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on + details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself + noticed :) + +* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson* + +* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar* + +* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions + +* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt* + +* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes* + + +## 1.11.1 (11 July, 2005) ## + +* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson* + +* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com* + +* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson* + +* Correct reflected table name for singular associations. #1688 *court3nay* + +* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net* + +* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current + +* Added better error message for "packets out of order" #1630 *court3nay* + +* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 + + +## 1.11.0 (6 July, 2005) ## + +* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar* + +* Changed logging of SQL statements to use the DEBUG level instead of INFO + +* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. + +* Added callback hooks to association collections #1549 [Florian Weber]. Example: + + class Project + has_and_belongs_to_many :developers, :before_add => :evaluate_velocity + + def evaluate_velocity(developer) + ... + end + end + + ..raising an exception will cause the object not to be added (or removed, with before_remove). + + +* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry* + +* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato* + +* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber* + +* Speed up ActiveRecord#method_missing for the common case (read_attribute). + +* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes* + +* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath* + +* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at* + +* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig* + +* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry* + +* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry* + +* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net* + +* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl* + +* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: + + Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' + + ...should instead be: + + Developer.find( + :all, + :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', + :conditions => 'project_id=1' + ) + +* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.* + +* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon* + +* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 + +* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid* + +* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice + +* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper* + +* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. + Example: + + david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] + david.save + + If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new + project is saved when david.save is called. + + Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: + + david.project_ids = [1, 5, 7] + +* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com* + +* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke* + +* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org* + +* Corrected @@configurations typo #1410 *david@ruppconsulting.com* + +* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com* + +* Allow before/after update hooks to work on models using optimistic locking + +* Eager loading of dependent has_one associations won't delete the association #1212 + +* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. + +* Using transactional fixtures now causes the data to be loaded only once. + +* Added fixture accessor methods that can be used when instantiated fixtures are disabled. + + fixtures :web_sites + + def test_something + assert_equal "Ruby on Rails", web_sites(:rubyonrails).name + end + +* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar* + +* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar* + +* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 + +* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead + +* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: + + Conditional validations such as the following are made possible: + validates_numericality_of :income, :if => :employed? + + Conditional validations can also solve the salted login generator problem: + validates_confirmation_of :password, :if => :new_password? + + Using blocks: + validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } + +* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net* + +* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson* + +* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper* + +* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. + +* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. + +* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: + + # SELECT * FROM topics WHERE title IN ('First', 'Second') + Topic.find_all_by_title(["First", "Second"]) + +* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor* + +* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor* + +* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid* + +* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com* + +* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: + + development: + adapter: postgresql + database: rails_development + host: localhost + username: postgres + password: + encoding: UTF8 + min_messages: ERROR + +* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck* + +* Added validates_exclusion_of as a negative of validates_inclusion_of + +* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls + + +## 1.10.1 (20th April, 2005) ## + +* Fixed frivilous database queries being triggered with eager loading on empty associations and other things + +* Fixed order of loading in eager associations + +* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 + + +## 1.10.0 (19th April, 2005) ## + +* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: + + for post in Post.find(:all, :limit => 100) + puts "Post: " + post.title + puts "Written by: " + post.author.name + puts "Last comment on: " + post.comments.first.created_on + end + + This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: + + for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) + + ...and the number of database queries needed is now 1. + +* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: + + Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(:first, :order => "created_on DESC", :offset => 5) + Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) + Person.find(:all, :offset => 10, :limit => 10) + +* Added acts_as_nested_set #1000 [wschenk]. Introduction: + + This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with + the added feature that you can select the children and all of it's descendants with + a single query. A good use case for this is a threaded post system, where you want + to display every reply to a comment without multiple selects. + +* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas* + +* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com* + +* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com* + +* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com* + +* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher* + +* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle* + +* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com* + +* Added insert_at(position) to acts_as_list #1083 *DeLynnB* + +* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) + +* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com* + +* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org* + +* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 + +* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt* + +* Added quoting of column names for fixtures #997 *jcfischer@gmail.com* + +* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis* + +* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes* + +* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org* + +* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper* + +* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org* + +* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes* + +* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes* + +* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas* + +* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) + + +## 1.9.1 (27th March, 2005) ## + +* Fixed that Active Record objects with float attribute could not be cloned #808 + +* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar* + +* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count + +* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron* + +* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb* + + +## 1.9.0 (22th March, 2005) ## + +* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: + + Developer.find_all nil, 'id ASC', 5 # return the first five developers + Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward + + This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. + +* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson* + +* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins* + +* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org* + +* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel* + +* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid* + +* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com* + +* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net* + +* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak* + +* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak* + +* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm* + +* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself + +* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) + + +## 1.8.0 (7th March, 2005) ## + +* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) + +* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron* + +* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: + + * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the + +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ + objects that should be inspected to determine which attributes triggered the errors. + * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. + You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. + +* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k* + +* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper* + +* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: + + class Account < ActiveRecord::Base + has_one :credit_card, :dependent => true + end + class CreditCard < ActiveRecord::Base + belongs_to :account + end + + account.credit_card # => returns existing credit card, lets say id = 12 + account.credit_card = CreditCard.create("number" => "123") + account.save # => CC with id = 12 is destroyed + + +* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: + + Validates whether the value of the specified attribute is numeric by trying to convert it to + a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression + <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). + + class Person < ActiveRecord::Base + validates_numericality_of :value, :on => :create + end + + Configuration options: + * <tt>message</tt> - A custom error message (default is: "is not a number") + * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) + * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) + + +* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron* + +* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) + +* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com* + + +## 1.7.0 (24th February, 2005) ## + +* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck* + +* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: + + 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple + and safe way of passing table-specific sequence information to the adapter.) + 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to + resort to some hacks to get data converted to Date or Time in Ruby. + If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the + hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. + This is nasty - but if you use Duck Typing you'll probably not care very much. + In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is + valid - too many databases use DATE for both. + Timezones and sub-second precision on timestamps are not supported. + 3. Default values that are functions (such as "SYSDATE") are not supported. This is a + restriction of the way active record supports default values. + 4. Referential integrity constraints are not fully supported. Under at least + some circumstances, active record appears to delete parent and child records out of + sequence and out of transaction scope. (Or this may just be a problem of test setup.) + + The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ + +* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke* + +* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm* + +* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka* + +* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar* + +* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com* + +* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au* + +* Fixed that find_by_* would fail when column names had numbers #670 *demetrius* + +* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn* + + 1. Created a new columns method that is much cleaner. + 2. Corrected a problem with the select and select_all methods + that didn't account for the LIMIT clause being passed into raw SQL statements. + 3. Implemented the string_to_time method in order to create proper instances of the time class. + 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. + 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. + +* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow* + +* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: + + class Person < ActiveRecord::Base + validates_each :first_name, :last_name do |record, attr| + record.errors.add attr, 'starts with z.' if attr[0] == ?z + end + end + +* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper* + +* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: + + class Person < ActiveRecord::Base + validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } + end + +* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates* + +* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: + + class Project < ActiveRecord::Base + primary_key "sysid" + table_name "XYZ_PROJECT" + inheritance_column { original_inheritance_column + "_id" } + end + +* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu* + + +## 1.6.0 (January 25th, 2005) ## + +* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. + +* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 + +* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. + +* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example + + people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } + Person.update(people.keys, people.values) + +* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron* + +* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat* + +* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius* + +* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper* + +* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson* + +* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson* + +* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not + +* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription + +* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius* + +* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron* + + +## 1.5.1 (January 18th, 2005) ## + +* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates* + +* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle* + + +## 1.5.0 (January 17th, 2005) ## + +* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel* + +* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: + + class Book < ActiveRecord::Base + has_many :pages + belongs_to :library + + validates_associated :pages, :library + end + +* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: + + == Unsaved objects and associations + + You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be + aware of, mostly involving the saving of associated objects. + + === One-to-one associations + + * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in + order to update their primary keys - except if the parent object is unsaved (new_record? == true). + * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment + is cancelled. + * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). + * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does + not save the parent either. + + === Collections + + * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object + (the owner of the collection) is not yet stored in the database. + * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. + * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). + * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. + +* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates* + +* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates* + +* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates* + +* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates* + +* Fixed binary support for PostgreSQL #444 *alex@byzantine.no* + +* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the + collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If + it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, + it'll take one less SELECT query if you use length. + +* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de* + +* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson* + +* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey* + +* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz* + +* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper* + +* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower* + +* Added that Observers can use the observes class method instead of overwriting self.observed_class(). + + Before: + class ListSweeper < ActiveRecord::Base + def self.observed_class() [ List, Item ] + end + + After: + class ListSweeper < ActiveRecord::Base + observes List, Item + end + +* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is + +* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name + +* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. + + Before: topic.update_attribute(:approved, !approved?) + After : topic.toggle!(:approved) + +* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: + + page.views # => 1 + page.increment!(:views) # executes an UPDATE statement + page.views # => 2 + + page.increment(:views).increment!(:views) + page.views # => 4 + +* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. + + + + +## 1.14.2 (April 9th, 2005) ## + +* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen* + + +## 1.14.1 (April 6th, 2006) ## + +* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar* + +* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind* + +* Enable Limit/Offset in Calculations (closes #4558) *lmarlow* + +* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson* + +* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr* + +* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis* + +* Support eager includes when going through a polymorphic has_many association. *Rick Olson* + +* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson* + + class Post < ActiveRecord::Base + has_one :tagging, :as => :taggable + end + + Post.find :all, :include => :tagging + +* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson* + +* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson* + + class PhotoCollection < ActiveRecord::Base + has_many :photos, :as => :photographic + belongs_to :firm + end + + class Firm < ActiveRecord::Base + has_many :photo_collections + has_many :photos, :through => :photo_collections + end + +* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com* + +* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber* + +* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan* + +* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson* + +* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson* + +* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson* + +* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.* + +* Fixed broken OCIAdapter #4457 *Michael Schoen* + + +## 1.14.0 (March 27th, 2006) ## + +* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar* + +* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson* + +* Add support for :include to with_scope *andrew@redlinesoftware.com* + +* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen* + +* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com* + +* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson* + +* Fixed issue that kept :select options from being scoped *Rick Olson* + +* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson* + +* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson* + +* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson* + + class Connection < ActiveRecord::Base + belongs_to :user + belongs_to :channel + end + + class Channel < ActiveRecord::Base + has_many :connections + has_many :contacts, :through => :connections, :class_name => 'User' # OLD + has_many :contacts, :through => :connections, :source => :user # NEW + end + +* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de* + +* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson* + + In this example, :include => false disables the default eager association from loading. :select changes the standard + select clause. :joins specifies a join that is added to the end of the has_many :through query. + + class Post < ActiveRecord::Base + has_many :tags, :through => :taggings, :include => :tagging do + def add_joins_and_select + find :all, :select => 'tags.*, authors.id as author_id', :include => false, + :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' + end + end + end + +* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson* + +* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney* + +* Quit ignoring default :include options in has_many :through calls *Mark James* + +* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney* + +* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson* + +* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: + + class Firm < ActiveRecord::Base + has_many :clients + has_many :invoices, :through => :clients + end + + class Client < ActiveRecord::Base + belongs_to :firm + has_many :invoices + end + + class Invoice < ActiveRecord::Base + belongs_to :client + end + +* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser* + +* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney* + +* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson* + +* SQL Server adapter gets some love #4298 *Ryan Tomayko* + +* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com* + +* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): + + Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') + +* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson* + +* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski* + +* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski* + +* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward* + +* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com* + +* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck* + +* Use association's :conditions when eager loading. [Jeremy Evans] #4144 + +* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans* + + This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. + + Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') + +* Oracle adapter gets some love #4230 *Michael Schoen* + + * Changes :text to CLOB rather than BLOB [Moses Hohman] + * Fixes an issue with nil numeric length/scales (several) + * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] + * Tweaks a unit test to get it all green again + * Adds support for #current_database + +* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson* + + class CachedModel < ActiveRecord::Base + self.abstract_class = true + end + + class Post < CachedModel + end + + CachedModel.abstract_class? + => true + + Post.abstract_class? + => false + + Post.base_class + => Post + + Post.table_name + => 'posts' + +* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson* + + class Foo < ActiveRecord::Base + has_many :attachments, :as => :attachable, :dependent => :delete_all + end + +* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay* + +* Upgrade to Transaction::Simple 1.3 *Jamis Buck* + +* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson* + +* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com* + +* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com* + +* Dynamically set allow_concurrency. #4044 *Stefan Kaes* + +* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: + + topic.to_xml + + ...returns: + + <?xml version="1.0" encoding="UTF-8"?> + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <id type="integer">1</id> + <approved type="boolean">false</approved> + <replies-count type="integer">0</replies-count> + <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> + <written-on type="datetime">2003-07-16 09:28:00</written-on> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + ...and you can configure with: + + topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) + + ...that'll return: + + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <approved type="boolean">false</approved> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + You can even do load first-level associations as part of the document: + + firm.to_xml :include => [ :account, :clients ] + + ...that'll return something like: + + <?xml version="1.0" encoding="UTF-8"?> + <firm> + <id type="integer">1</id> + <rating type="integer">1</rating> + <name>37signals</name> + <clients> + <client> + <rating type="integer">1</rating> + <name>Summit</name> + </client> + <client> + <rating type="integer">1</rating> + <name>Microsoft</name> + </client> + </clients> + <account> + <id type="integer">1</id> + <credit-limit type="integer">50</credit-limit> + </account> + </firm> + +* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck* + +* Documentation fixes for :dependent *robby@planetargon.com* + +* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney* + +* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org* + +* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson* + +* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>* + +* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson* + + * The first time a table is referenced in a join, no alias is used. + * After that, the parent class name and the reflection name are used. + + Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... + + * Any additional join references get a numerical suffix like '_2', '_3', etc. + +* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. + +* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: + + # cascaded in two levels + >> Author.find(:all, :include=>{:posts=>:comments}) + => authors + +- posts + +- comments + + # cascaded in two levels and normal association + >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in two levels with two has_many associations + >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in three levels + >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) + => companies + +- groups + +- members + +- favorites + +* Make counter cache work when replacing an association #3245 *eugenol@gmail.com* + +* Make migrations verbose *Jamis Buck* + +* Make counter_cache work with polymorphic belongs_to *Jamis Buck* + +* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp* + +* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: + + * Does not support DATE SQL column types; use DATETIME instead. + * Date columns on HABTM join tables are returned as String, not Time. + * Insertions are potentially broken for :polymorphic join tables + * BLOB column access not yet fully supported + +* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper* + +* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper* + +* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen* + +* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson* + +* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes* + +* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark* + +* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net* + +* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney* + +* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward* + +* Added support for nested scopes #3407 [anna@wota.jp]. Examples: + + Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 + + # inner rule is used. (all previous parameters are ignored) + Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') + end + + # parameters are merged + Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 + end + end + +* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com* + +* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh* + +* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind* + +* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: + + Person.average :age + Person.minimum :age + Person.maximum :age + Person.sum :salary, :group => :last_name + +* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath* + +* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper* + +* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net* + +* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de* + +* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes* + +* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva* + +* Allow :include to be used with has_many :through associations #3611 *Michael Schoen* + +* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac* + +* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward* + +* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson* + +* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org* + +* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark* + +* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke* + +* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson* + +* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar* + +* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt* + +* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda* + +* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>* + +* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen* + +* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson* + +* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.* + +* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar* + +* Make .count work for has_many associations with multi line finder sql *Michael Schoen* + +* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck* + +* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com* + +* Don't hardcode 'id' in acts as list. *ror@philippeapril.com* + +* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark* + +* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp* + +* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com* + +* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke* + +* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.* + +* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de* + +* Sanitize scoped conditions. *Marcel Molina Jr.* + +* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson* + +* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke* + +* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke* + +* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber* + +* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron* + +* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke* + +* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke* + +* made .find() work on :through relations. *Tobias Lütke* + +* Fix typo in association docs. #3296. *Blair Zajac* + +* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke* + +## 1.13.2 (December 13th, 2005) ## + +* Become part of Rails 1.0 + +* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper* + +* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: + + class Post + has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author + end + + post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors + post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors + post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors + +* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson* + +* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder* + +* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com* + +* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org* + +* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com* + +* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko* + +* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com* + +* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen* + +* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes* + +* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil* + +* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond* + +* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson* + +* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen* + +* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper* + +* Added preliminary support for polymorphic associations *David Heinemeier Hansson* + +* Added preliminary support for join models *David Heinemeier Hansson* + +* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.* + +* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>* + +* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>* + +* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper* + +* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen* + +* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com* + +* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper* + +* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen* + +* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda* + +* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper* + +* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda* + +* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.* + +* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes* + +* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes* + +* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>* + +* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans* + +* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.* + +* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>* + +* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com* + +* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>* + +* Correct documentation for Base.delete_all. #1568 *Newhydra* + +* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>* + +* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>* + +* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper* + +* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>* + +* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper* + +* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper* + +* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper* + +* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko* + +* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>* + +* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de* + +* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>* + +* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com* + +* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar* + +* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney* + +* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper* + +* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.* + +* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com* + +* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper* + +* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper* + +* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>* + + +## 1.13.0 (November 7th, 2005) ## + +* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko* + +* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: + + has_many :posts, :include => [ :author, :comments ] + +* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: + + Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do + # Find where name = ? and active=true + Comment.find :all, :conditions => ['name = ?', name] + # Create comment associated with :post_id + Comment.create :body => "Hello world" + end + +* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko* + +* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: + + Comment.constrain(:creation => { :post_id => 5 }) do + # Associated with :post_id + Comment.create :body => "Hello world" + end + + This is rarely used directly, but allows for find_or_create on associations. So you can do: + + # If the tag doesn't exist, a new one is created that's associated with the person + person.tags.find_or_create_by_name("Summer") + +* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: + + # No 'Summer' tag exists + Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") + + # Now the 'Summer' tag does exist + Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") + +* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: + + class Account < ActiveRecord::Base + has_many :people do + def find_or_create_by_name(name) + first_name, *last_name = name.split + last_name = last_name.join " " + + find_or_create_by_first_name_and_last_name(first_name, last_name) + end + end + end + + person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") + person.first_name # => "David" + person.last_name # => "Heinemeier Hansson" + + Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). + +* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko* + +* Quote column names in generated SQL. #2728 *Ryan Tomayko* + +* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper* + +* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper* + +* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>* + +* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson* + +* Added migration support for Oracle #2647 *Michael Schoen* + +* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>* + +* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko* + +* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward* + +* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward* + +* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com* + +* Constraints are cloned so they can't be inadvertently modified while they're + in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] +* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com* + +* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen* + +* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt* + + +## 1.12.2 (October 26th, 2005) ## + +* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark* + +* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>* + +* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes* + +* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>* + +* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>* + +* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>* + + +## 1.12.1 (October 19th, 2005) ## + +* Always parenthesize :conditions options so they may be safely combined with STI and constraints. + +* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com* + +* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations + + +## 1.12.0 (October 16th, 2005) ## + +* Update/clean up documentation (rdoc) + +* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>* + +* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson* + +* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net* + +* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>* + +* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. + +* Avoid memleak in dev mode when using fcgi + +* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>* + +* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>* + +* Fix errors caused by assigning a has-one or belongs-to property to itself + +* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson* + +* Update DB2 adapter. #2206. *contact@maik-schmidt.de* + +* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com* + +* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. + +* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>* + +* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code* + +* Add test coverage for content_columns. #2432. *coffee2code* + +* Speed up for unthreaded environments. #2431. *Stefan Kaes* + +* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes* + +* Speed up the setting of table_name. #2428. *Stefan Kaes* + +* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes* + +* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>* + +* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes* + +* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>* + +* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick* + +* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes* + +* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes* + +* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar* + +* Added :force option to create_table that'll try to drop the table if it already exists before creating + +* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar* + +* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>* + +* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>* + +* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman* + +* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>* + +* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>* + +* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>* + +* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>* + +* Make update_attribute use the same writer method that update_attributes uses. + \#2237 [trevor@protocool.com] +* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.* + +* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org* + +* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com* + +* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) + +* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: + + ActiveRecord::Base.observers = :cacher, :garbage_collector + +* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com* + +* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck* + +* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck* + +* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck* + +* Fixed migrations for Windows when using more than 10 *David Naseby* + +* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber* + +* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke* + +* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar* + +* Fixed that Observers didn't observe sub-classes #627 *Florian Weber* + +* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.* + +* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae* + +* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber* + +* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil* + +* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com* + +* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg* + +* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward* + +* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code* + +* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net* + +* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ + +* Make sure the schema_info table is created before querying the current version #1903 + +* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning* + +* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine* + +* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz* + +* Make destroy return self #1913 *Sebastian Kanthak* + +* Fix typo in validations documentation #1938 *court3nay* + +* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org* + +* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky* + +* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com* + +* Fix create_table so that id column is implicitly added *Rick Olson* + +* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 + +* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 + +* Fixed the handling of camelCase columns names in Oracle #1798 + +* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 + +* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 + +* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke* + + class Comment < AR:B + def self.search(q) + find(:all, :conditions => ["body = ?", q]) + end + end + + class Post < AR:B + has_many :comments + end + + Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' + + NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as + by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on + details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself + noticed :) + +* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson* + +* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar* + +* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions + +* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt* + +* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes* + + +## 1.11.1 (11 July, 2005) ## + +* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson* + +* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com* + +* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson* + +* Correct reflected table name for singular associations. #1688 *court3nay* + +* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net* + +* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current + +* Added better error message for "packets out of order" #1630 *court3nay* + +* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 + + +## 1.11.0 (6 July, 2005) ## + +* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar* + +* Changed logging of SQL statements to use the DEBUG level instead of INFO + +* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. + +* Added callback hooks to association collections #1549 [Florian Weber]. Example: + + class Project + has_and_belongs_to_many :developers, :before_add => :evaluate_velocity + + def evaluate_velocity(developer) + ... + end + end + + ..raising an exception will cause the object not to be added (or removed, with before_remove). + + +* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry* + +* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato* + +* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber* + +* Speed up ActiveRecord#method_missing for the common case (read_attribute). + +* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes* + +* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath* + +* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at* + +* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig* + +* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry* + +* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry* + +* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net* + +* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl* + +* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: + + Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' + + ...should instead be: + + Developer.find( + :all, + :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', + :conditions => 'project_id=1' + ) + +* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.* + +* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon* + +* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 + +* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid* + +* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice + +* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper* + +* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. + Example: + + david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] + david.save + + If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new + project is saved when david.save is called. + + Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: + + david.project_ids = [1, 5, 7] + +* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com* + +* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke* + +* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org* + +* Corrected @@configurations typo #1410 *david@ruppconsulting.com* + +* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com* + +* Allow before/after update hooks to work on models using optimistic locking + +* Eager loading of dependent has_one associations won't delete the association #1212 + +* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. + +* Using transactional fixtures now causes the data to be loaded only once. + +* Added fixture accessor methods that can be used when instantiated fixtures are disabled. + + fixtures :web_sites + + def test_something + assert_equal "Ruby on Rails", web_sites(:rubyonrails).name + end + +* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar* + +* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar* + +* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 + +* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead + +* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: + + Conditional validations such as the following are made possible: + validates_numericality_of :income, :if => :employed? + + Conditional validations can also solve the salted login generator problem: + validates_confirmation_of :password, :if => :new_password? + + Using blocks: + validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } + +* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net* + +* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson* + +* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper* + +* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. + +* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. + +* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: + + # SELECT * FROM topics WHERE title IN ('First', 'Second') + Topic.find_all_by_title(["First", "Second"]) + +* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor* + +* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor* + +* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid* + +* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com* + +* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: + + development: + adapter: postgresql + database: rails_development + host: localhost + username: postgres + password: + encoding: UTF8 + min_messages: ERROR + +* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck* + +* Added validates_exclusion_of as a negative of validates_inclusion_of + +* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls + + +## 1.10.1 (20th April, 2005) ## + +* Fixed frivilous database queries being triggered with eager loading on empty associations and other things + +* Fixed order of loading in eager associations + +* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 + + +## 1.10.0 (19th April, 2005) ## + +* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: + + for post in Post.find(:all, :limit => 100) + puts "Post: " + post.title + puts "Written by: " + post.author.name + puts "Last comment on: " + post.comments.first.created_on + end + + This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: + + for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) + + ...and the number of database queries needed is now 1. + +* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: + + Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(:first, :order => "created_on DESC", :offset => 5) + Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) + Person.find(:all, :offset => 10, :limit => 10) + +* Added acts_as_nested_set #1000 [wschenk]. Introduction: + + This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with + the added feature that you can select the children and all of it's descendants with + a single query. A good use case for this is a threaded post system, where you want + to display every reply to a comment without multiple selects. + +* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas* + +* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com* + +* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com* + +* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com* + +* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher* + +* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle* + +* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com* + +* Added insert_at(position) to acts_as_list #1083 *DeLynnB* + +* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) + +* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com* + +* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org* + +* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 + +* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt* + +* Added quoting of column names for fixtures #997 *jcfischer@gmail.com* + +* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis* + +* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes* + +* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org* + +* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper* + +* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org* + +* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes* + +* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes* + +* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas* + +* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) + + +## 1.9.1 (27th March, 2005) ## + +* Fixed that Active Record objects with float attribute could not be cloned #808 + +* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar* + +* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count + +* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron* + +* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb* + + +## 1.9.0 (22th March, 2005) ## + +* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: + + Developer.find_all nil, 'id ASC', 5 # return the first five developers + Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward + + This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. + +* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson* + +* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins* + +* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org* + +* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel* + +* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid* + +* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com* + +* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net* + +* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak* + +* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak* + +* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm* + +* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself + +* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) + + +## 1.8.0 (7th March, 2005) ## + +* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) + +* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron* + +* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: + + * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the + +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ + objects that should be inspected to determine which attributes triggered the errors. + * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. + You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. + +* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k* + +* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper* + +* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: + + class Account < ActiveRecord::Base + has_one :credit_card, :dependent => true + end + class CreditCard < ActiveRecord::Base + belongs_to :account + end + + account.credit_card # => returns existing credit card, lets say id = 12 + account.credit_card = CreditCard.create("number" => "123") + account.save # => CC with id = 12 is destroyed + + +* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: + + Validates whether the value of the specified attribute is numeric by trying to convert it to + a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression + <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). + + class Person < ActiveRecord::Base + validates_numericality_of :value, :on => :create + end + + Configuration options: + * <tt>message</tt> - A custom error message (default is: "is not a number") + * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) + * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) + + +* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron* + +* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) + +* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com* + + +## 1.7.0 (24th February, 2005) ## + +* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck* + +* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: + + 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple + and safe way of passing table-specific sequence information to the adapter.) + 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to + resort to some hacks to get data converted to Date or Time in Ruby. + If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the + hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. + This is nasty - but if you use Duck Typing you'll probably not care very much. + In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is + valid - too many databases use DATE for both. + Timezones and sub-second precision on timestamps are not supported. + 3. Default values that are functions (such as "SYSDATE") are not supported. This is a + restriction of the way active record supports default values. + 4. Referential integrity constraints are not fully supported. Under at least + some circumstances, active record appears to delete parent and child records out of + sequence and out of transaction scope. (Or this may just be a problem of test setup.) + + The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ + +* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke* + +* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm* + +* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka* + +* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar* + +* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com* + +* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au* + +* Fixed that find_by_* would fail when column names had numbers #670 *demetrius* + +* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn* + + 1. Created a new columns method that is much cleaner. + 2. Corrected a problem with the select and select_all methods + that didn't account for the LIMIT clause being passed into raw SQL statements. + 3. Implemented the string_to_time method in order to create proper instances of the time class. + 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. + 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. + +* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow* + +* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: + + class Person < ActiveRecord::Base + validates_each :first_name, :last_name do |record, attr| + record.errors.add attr, 'starts with z.' if attr[0] == ?z + end + end + +* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper* + +* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: + + class Person < ActiveRecord::Base + validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } + end + +* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates* + +* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: + + class Project < ActiveRecord::Base + primary_key "sysid" + table_name "XYZ_PROJECT" + inheritance_column { original_inheritance_column + "_id" } + end + +* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu* + + +## 1.6.0 (January 25th, 2005) ## + +* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. + +* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 + +* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. + +* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example + + people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } + Person.update(people.keys, people.values) + +* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron* + +* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat* + +* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius* + +* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper* + +* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson* + +* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson* + +* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not + +* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription + +* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius* + +* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron* + + +## 1.5.1 (January 18th, 2005) ## + +* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates* + +* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle* + + +## 1.5.0 (January 17th, 2005) ## + +* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel* + +* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: + + class Book < ActiveRecord::Base + has_many :pages + belongs_to :library + + validates_associated :pages, :library + end + +* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: + + == Unsaved objects and associations + + You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be + aware of, mostly involving the saving of associated objects. + + === One-to-one associations + + * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in + order to update their primary keys - except if the parent object is unsaved (new_record? == true). + * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment + is cancelled. + * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). + * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does + not save the parent either. + + === Collections + + * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object + (the owner of the collection) is not yet stored in the database. + * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. + * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). + * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. + +* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates* + +* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates* + +* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates* + +* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates* + +* Fixed binary support for PostgreSQL #444 *alex@byzantine.no* + +* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the + collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If + it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, + it'll take one less SELECT query if you use length. + +* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de* + +* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson* + +* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey* + +* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz* + +* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper* + +* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower* + +* Added that Observers can use the observes class method instead of overwriting self.observed_class(). + + Before: + class ListSweeper < ActiveRecord::Base + def self.observed_class() [ List, Item ] + end + + After: + class ListSweeper < ActiveRecord::Base + observes List, Item + end + +* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is + +* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name + +* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. + + Before: topic.update_attribute(:approved, !approved?) + After : topic.toggle!(:approved) + +* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: + + page.views # => 1 + page.increment!(:views) # executes an UPDATE statement + page.views # => 2 + + page.increment(:views).increment!(:views) + page.views # => 4 + +* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. + + +## 1.4.0 (January 4th, 2005) ## + +* Added automated optimistic locking if the field <tt>lock_version</tt> is present. Each update to the + record increments the lock_version column and the locking facilities ensure that records instantiated twice + will let the last one saved raise a StaleObjectError if the first was also updated. Example: + + p1 = Person.find(1) + p2 = Person.find(1) + + p1.first_name = "Michael" + p1.save + + p2.first_name = "should fail" + p2.save # Raises a ActiveRecord::StaleObjectError + + You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, + or otherwise apply the business logic needed to resolve the conflict. + + \#384 *Michael Koziarski* + +* Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL. + They work by appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name, + Payment.find_by_transaction_id</tt>. So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do + <tt>Person.find_by_user_name(user_name)</tt>. + + It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like + <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing + <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do + <tt>Person.find_by_user_name_and_password(user_name, password)</tt>. + + While primarily a construct for easier find_firsts, it can also be used as a construct for find_all by using calls like + <tt>Payment.find_all_by_amount(50)</tt> that is turned into <tt>Payment.find_all(["amount = ?", 50])</tt>. This is something not as equally useful, + though, as it's not possible to specify the order in which the objects are returned. + +* Added block-style for callbacks #332 [Jeremy Kemper]. + + Before: + before_destroy(Proc.new{ |record| Person.destroy_all "firm_id = #{record.id}" }) + + After: + before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" } + +* Added :counter_cache option to acts_as_tree that works just like the one you can define on belongs_to #371 *Josh Peek* + +* Added Base.default_timezone accessor that determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates + and times from the database. This is set to :local by default. + +* Added the possibility for adapters to overwrite add_limit! to implement a different limiting scheme than "LIMIT X" used by MySQL, PostgreSQL, and SQLite. + +* Added the possibility of having objects with acts_as_list created before their scope is available or... + +* Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://raa.ruby-lang.org/project/ruby-db2/) #386 *Maik Schmidt* + +* Added the final touches to the Microsoft SQL Server adapter by Joey Gibson that makes it suitable for actual use #394 *DeLynn Barry* + +* Added that Base#find takes an optional options hash, including :conditions. Base#find_on_conditions deprecated in favor of #find with :conditions #407 *Jeremy Kemper* + +* Added HasManyAssociation#count that works like Base#count #413 *intinig* + +* Fixed handling of binary content in blobs and similar fields for Ruby/MySQL and SQLite #409 *xal* + +* Fixed a bug in the Ruby/MySQL that caused binary content to be escaped badly and come back mangled #405 *Tobias Lütke* + +* Fixed that the const_missing autoload assumes the requested constant is set by require_association and calls const_get to retrieve it. + If require_association did not set the constant then const_get will call const_missing, resulting in an infinite loop #380 *Jeremy Kemper* + +* Fixed broken transactions that were actually only running object-level and not db level transactions *andreas* + +* Fixed that validates_uniqueness_of used 'id' instead of defined primary key #406 + +* Fixed that the overwritten respond_to? method didn't take two parameters like the original #391 + +* Fixed quoting in validates_format_of that would allow some rules to pass regardless of input #390 *Dmitry V. Sabanin* + + +## 1.3.0 (December 23, 2004) ## + +* Added a require_association hook on const_missing that makes it possible to use any model class without requiring it first. This makes STI look like: + + before: + require_association 'person' + class Employee < Person + end + + after: + class Employee < Person + end + + This also reduces the usefulness of Controller.model in Action Pack to currently only being for documentation purposes. + +* Added that Base.update_all and Base.delete_all return an integer of the number of affected rows #341 + +* Added scope option to validation_uniqueness #349 *Kent Sibilev* + +* Added respondence to *_before_type_cast for all attributes to return their string-state before they were type casted by the column type. + This is helpful for getting "100,000" back on a integer-based validation where the value would normally be "100". + +* Added allow_nil options to validates_inclusion_of so that validation is only triggered if the attribute is not nil *what-a-day* + +* Added work-around for PostgreSQL and the problem of getting fixtures to be created from id 1 on each test case. + This only works for auto-incrementing primary keys called "id" for now #359 *Scott Baron* + +* Added Base#clear_association_cache to empty all the cached associations #347 *Tobias Lütke* + +* Added more informative exceptions in establish_connection #356 *Jeremy Kemper* + +* Added Base#update_attributes that'll accept a hash of attributes and save the record (returning true if it passed validation, false otherwise). + + Before: + person.attributes = @params["person"] + person.save + + Now: + person.update_attributes(@params["person"]) + +* Added Base.destroy and Base.delete to remove records without holding a reference to them first. + +* Added that query benchmarking will only happen if its going to be logged anyway #344 + +* Added higher_item and lower_item as public methods for acts_as_list #342 *Tobias Lütke* + +* Fixed that options[:counter_sql] was overwritten with interpolated sql rather than original sql #355 *Jeremy Kemper* + +* Fixed that overriding an attribute's accessor would be disregarded by add_on_empty and add_on_boundary_breaking because they simply used + the attributes[] hash instead of checking for @base.respond_to?(attr.to_s). *Marten* + +* Fixed that Base.table_name would expect a parameter when used in has_and_belongs_to_many joins *Anna Lissa Cruz* + +* Fixed that nested transactions now work by letting the outer most transaction have the responsibilty of starting and rolling back the transaction. + If any of the inner transactions swallow the exception raised, though, the transaction will not be rolled back. So always let the transaction + bubble up even when you've dealt with local issues. Closes #231 and #340. + +* Fixed validates_{confirmation,acceptance}_of to only happen when the virtual attributes are not nil #348 *dpiddy@gmail.com* + +* Changed the interface on AbstractAdapter to require that adapters return the number of affected rows on delete and update operations. + +* Fixed the automated timestamping feature when running under Rails' development environment that resets the inheritable attributes on each request. + + + +## 1.2.0 ## + +* Added Base.validates_inclusion_of that validates whether the value of the specified attribute is available in a particular enumerable + object. *what-a-day* + + class Person < ActiveRecord::Base + validates_inclusion_of :gender, :in=>%w( m f ), :message=>"woah! what are you then!??!!" + validates_inclusion_of :age, :in=>0..99 + end + +* Added acts_as_list that can decorates an existing class with methods like move_higher/lower, move_to_top/bottom. [Tobias Lütke] Example: + + class TodoItem < ActiveRecord::Base + acts_as_list :scope => :todo_list_id + belongs_to :todo_list + end + +* Added acts_as_tree that can decorates an existing class with a many to many relationship with itself. Perfect for categories in + categories and the likes. *Tobias Lütke* + +* Added that Active Records will automatically record creation and/or update timestamps of database objects if fields of the names + created_at/created_on or updated_at/updated_on are present. *Tobias Lütke* + +* Added Base.default_error_messages as a hash of all the error messages used in the validates_*_of so they can be changed in one place *Tobias Lütke* + +* Added automatic transaction block around AssociationCollection.<<, AssociationCollection.delete, and AssociationCollection.destroy_all + +* Fixed that Base#find will return an array if given an array -- regardless of the number of elements #270 *Marten* + +* Fixed that has_and_belongs_to_many would generate bad sql when naming conventions differed from using vanilla "id" everywhere *RedTerror* + +* Added a better exception for when a type column is used in a table without the intention of triggering single-table inheritance. Example: + + ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'bad_class!'. + This error is raised because the column 'type' is reserved for storing the class in case of inheritance. + Please rename this column if you didn't intend it to be used for storing the inheritance class or + overwrite Company.inheritance_column to use another column for that information. + +* Added that single-table inheritance will only kick in if the inheritance_column (by default "type") is present. Otherwise, inheritance won't + have any magic side effects. + +* Added the possibility of marking fields as being in error without adding a message (using nil) to it that'll get displayed wth full_messages #208 *mjobin* + +* Fixed Base.errors to be indifferent as to whether strings or symbols are used. Examples: + + Before: + errors.add(:name, "must be shorter") if name.size > 10 + errors.on(:name) # => "must be shorter" + errors.on("name") # => nil + + After: + errors.add(:name, "must be shorter") if name.size > 10 + errors.on(:name) # => "must be shorter" + errors.on("name") # => "must be shorter" + +* Added Base.validates_format_of that Validates whether the value of the specified attribute is of the correct form by matching + it against the regular expression provided. *Marcel Molina Jr.* + + class Person < ActiveRecord::Base + validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :on => :create + end + +* Added Base.validates_length_of that delegates to add_on_boundary_breaking #312 [Tobias Lütke]. Example: + + Validates that the specified attribute matches the length restrictions supplied in either: + + - configuration[:minimum] + - configuration[:maximum] + - configuration[:is] + - configuration[:within] (aka. configuration[:in]) + + Only one option can be used at a time. + + class Person < ActiveRecord::Base + validates_length_of :first_name, :maximum=>30 + validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind" + validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name" + validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character" + validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me." + end + +* Added Base.validate_presence as an alternative to implementing validate and doing errors.add_on_empty yourself. + +* Added Base.validates_uniqueness_of that alidates whether the value of the specified attributes are unique across the system. + Useful for making sure that only one user can be named "davidhh". + + class Person < ActiveRecord::Base + validates_uniqueness_of :user_name + end + + When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified + attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself. + + +* Added Base.validates_confirmation_of that encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example: + + Model: + class Person < ActiveRecord::Base + validates_confirmation_of :password + end + + View: + <%= password_field "person", "password" %> + <%= password_field "person", "password_confirmation" %> + + The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual. + It exists only as an in-memory variable for validating the password. This check is performed both on create and update. + + +* Added Base.validates_acceptance_of that encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example: + + class Person < ActiveRecord::Base + validates_acceptance_of :terms_of_service + end + + The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed both on create and update. + + NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox. + + +* Added validation macros to make the stackable just like the life cycle callbacks. Examples: + + class Person < ActiveRecord::Base + validate { |record| record.errors.add("name", "too short") unless name.size > 10 } + validate { |record| record.errors.add("name", "too long") unless name.size < 20 } + validate_on_create :validate_password + + private + def validate_password + errors.add("password", "too short") unless password.size > 6 + end + end + +* Added the option for sanitizing find_by_sql and the offset parts in regular finds [Sam Stephenson]. Examples: + + Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20] + Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date] + +* Fixed value quoting in all generated SQL statements, so that integers are not surrounded in quotes and that all sanitation are happening + through the database's own quoting routine. This should hopefully make it lots easier for new adapters that doesn't accept '1' for integer + columns. + +* Fixed has_and_belongs_to_many guessing of foreign key so that keys are generated correctly for models like SomeVerySpecialClient + *Florian Weber* + +* Added counter_sql option for has_many associations [Jeremy Kemper]. Documentation: + + <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is + specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM. + +* Fixed that methods wrapped in callbacks still return their original result #260 *Jeremy Kemper* + +* Fixed the Inflector to handle the movie/movies pair correctly #261 *Scott Baron* + +* Added named bind-style variable interpolation #281 [Michael Koziarski]. Example: + + Person.find(["id = :id and first_name = :first_name", { :id => 5, :first_name = "bob' or 1=1" }]) + +* Added bind-style variable interpolation for the condition arrays that uses the adapter's quote method *Michael Koziarski* + + Before: + find_first([ "user_name = '%s' AND password = '%s'", user_name, password ])] + find_first([ "firm_id = %s", firm_id ])] # unsafe! + + After: + find_first([ "user_name = ? AND password = ?", user_name, password ])] + find_first([ "firm_id = ?", firm_id ])] + +* Added CSV format for fixtures #272 [what-a-day]. (See the new and expanded documentation on fixtures for more information) + +* Fixed fixtures using primary key fields called something else than "id" *dave* + +* Added proper handling of time fields that are turned into Time objects with the dummy date of 2000/1/1 *HariSeldon* + +* Added reverse order of deleting fixtures, so referential keys can be maintained #247 *Tim Bates* + +* Added relative path search for sqlite dbfiles in database.yml (if RAILS_ROOT is defined) #233 *Jeremy Kemper* + +* Added option to establish_connection where you'll be able to leave out the parameter to have it use the RAILS_ENV environment variable + +* Fixed problems with primary keys and postgresql sequences (#230) *Tim Bates* + +* Added reloading for associations under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development. + This is turned on by default, but can be turned off with ActiveRecord::Base.reload_dependencies = false in production environments. + + NOTE: This will only have an effect if you let the associations manage the requiring of model classes. All libraries loaded through + require will be "forever" cached. You can, however, use ActiveRecord::Base.load_or_require("library") to get this behavior outside of the + auto-loading associations. + +* Added ERB capabilities to the fixture files for dynamic fixture generation. You don't need to do anything, just include ERB blocks like: + + david: + id: 1 + name: David + + jamis: + id: 2 + name: Jamis + + <% for digit in 3..10 %> + dev_<%= digit %>: + id: <%= digit %> + name: fixture_<%= digit %> + <% end %> + +* Changed the yaml fixture searcher to look in the root of the fixtures directory, so when you before could have something like: + + fixtures/developers/fixtures.yaml + fixtures/accounts/fixtures.yaml + + ...you now need to do: + + fixtures/developers.yaml + fixtures/accounts.yaml + +* Changed the fixture format from: + + name: david + data: + id: 1 + name: David Heinemeier Hansson + birthday: 1979-10-15 + profession: Systems development + --- + name: steve + data: + id: 2 + name: Steve Ross Kellock + birthday: 1974-09-27 + profession: guy with keyboard + + ...to: + + david: + id: 1 + name: David Heinemeier Hansson + birthday: 1979-10-15 + profession: Systems development + + steve: + id: 2 + name: Steve Ross Kellock + birthday: 1974-09-27 + profession: guy with keyboard + + The change is NOT backwards compatible. Fixtures written in the old YAML style needs to be rewritten! + +* All associations will now attempt to require the classes that they associate to. Relieving the need for most explicit 'require' statements. + + +## 1.1.0 (34) ## + +* Added automatic fixture setup and instance variable availability. Fixtures can also be automatically + instantiated in instance variables relating to their names using the following style: + + class FixturesTest < Test::Unit::TestCase + fixtures :developers # you can add more with comma separation + + def test_developers + assert_equal 3, @developers.size # the container for all the fixtures is automatically set + assert_kind_of Developer, @david # works like @developers["david"].find + assert_equal "David Heinemeier Hansson", @david.name + end + end + +* Added HasAndBelongsToManyAssociation#push_with_attributes(object, join_attributes) that can create associations in the join table with additional + attributes. This is really useful when you have information that's only relevant to the join itself, such as a "added_on" column for an association + between post and category. The added attributes will automatically be injected into objects retrieved through the association similar to the piggy-back + approach: + + post.categories.push_with_attributes(category, :added_on => Date.today) + post.categories.first.added_on # => Date.today + + NOTE: The categories table doesn't have a added_on column, it's the categories_post join table that does! + +* Fixed that :exclusively_dependent and :dependent can't be activated at the same time on has_many associations *Jeremy Kemper* + +* Fixed that database passwords couldn't be all numeric *Jeremy Kemper* + +* Fixed that calling id would create the instance variable for new_records preventing them from being saved correctly *Jeremy Kemper* + +* Added sanitization feature to HasManyAssociation#find_all so it works just like Base.find_all *Sam Stephenson/Jeremy Kemper* + +* Added that you can pass overlapping ids to find without getting duplicated records back *Jeremy Kemper* + +* Added that Base.benchmark returns the result of the block *Jeremy Kemper* + +* Fixed problem with unit tests on Windows with SQLite *paterno* + +* Fixed that quotes would break regular non-yaml fixtures *Dmitry Sabanin/daft* + +* Fixed fixtures on windows with line endings cause problems under unix / mac *Tobias Lütke* + +* Added HasAndBelongsToManyAssociation#find(id) that'll search inside the collection and find the object or record with that id + +* Added :conditions option to has_and_belongs_to_many that works just like the one on all the other associations + +* Added AssociationCollection#clear to remove all associations from has_many and has_and_belongs_to_many associations without destroying the records *geech* + +* Added type-checking and remove in 1-instead-of-N sql statements to AssociationCollection#delete *geech* + +* Added a return of self to AssociationCollection#<< so appending can be chained, like project << Milestone.create << Milestone.create *geech* + +* Added Base#hash and Base#eql? which means that all of the equality using features of array and other containers now works: + + [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] + +* Added :uniq as an option to has_and_belongs_to_many which will automatically ensure that AssociateCollection#uniq is called + before pulling records out of the association. This is especially useful for three-way (and above) has_and_belongs_to_many associations. + +* Added AssociateCollection#uniq which is especially useful for has_and_belongs_to_many associations that can include duplicates, + which is common on associations that also use metadata. Usage: post.categories.uniq + +* Fixed respond_to? to use a subclass specific hash instead of an Active Record-wide one + +* Fixed has_and_belongs_to_many to treat associations between classes in modules properly *Florian Weber* + +* Added a NoMethod exception to be raised when query and writer methods are called for attributes that doesn't exist *geech* + +* Added a more robust version of Fixtures that throws meaningful errors when on formatting issues *geech* + +* Added Base#transaction as a compliment to Base.transaction for prettier use in instance methods *geech* + +* Improved the speed of respond_to? by placing the dynamic methods lookup table in a hash *geech* + +* Added that any additional fields added to the join table in a has_and_belongs_to_many association + will be placed as attributes when pulling records out through has_and_belongs_to_many associations. + This is helpful when have information about the association itself that you want available on retrival. + +* Added better loading exception catching and RubyGems retries to the database adapters *alexeyv* + +* Fixed bug with per-model transactions *daniel* + +* Fixed Base#transaction so that it returns the result of the last expression in the transaction block *alexeyv* + +* Added Fixture#find to find the record corresponding to the fixture id. The record + class name is guessed by using Inflector#classify (also new) on the fixture directory name. + + Before: Document.find(@documents["first"]["id"]) + After : @documents["first"].find + +* Fixed that the table name part of column names ("TABLE.COLUMN") wasn't removed properly *Andreas Schwarz* + +* Fixed a bug with Base#size when a finder_sql was used that didn't capitalize SELECT and FROM *geech* + +* Fixed quoting problems on SQLite by adding quote_string to the AbstractAdapter that can be overwritten by the concrete + adapters for a call to the dbm. *Andreas Schwarz* + +* Removed RubyGems backup strategy for requiring SQLite-adapter -- if people want to use gems, they're already doing it with AR. + + +## 1.0.0 (35) ## + +* Added OO-style associations methods [Florian Weber]. Examples: + + Project#milestones_count => Project#milestones.size + Project#build_to_milestones => Project#milestones.build + Project#create_for_milestones => Project#milestones.create + Project#find_in_milestones => Project#milestones.find + Project#find_all_in_milestones => Project#milestones.find_all + +* Added serialize as a new class method to control when text attributes should be YAMLized or not. This means that automated + serialization of hashes, arrays, and so on WILL NO LONGER HAPPEN (#10). You need to do something like this: + + class User < ActiveRecord::Base + serialize :settings + end + + This will assume that settings is a text column and will now YAMLize any object put in that attribute. You can also specify + an optional :class_name option that'll raise an exception if a serialized object is retrieved as a descendant of a class not in + the hierarchy. Example: + + class User < ActiveRecord::Base + serialize :settings, :class_name => "Hash" + end + + user = User.create("settings" => %w( one two three )) + User.find(user.id).settings # => raises SerializationTypeMismatch + +* Added the option to connect to a different database for one model at a time. Just call establish_connection on the class + you want to have connected to another database than Base. This will automatically also connect decendents of that class + to the different database [Renald Buter]. + +* Added transactional protection for Base#save. Validations can now check for values knowing that it happens in a transaction and callbacks + can raise exceptions knowing that the save will be rolled back. *Suggested by Alexey Verkhovsky* + +* Added column name quoting so reserved words, such as "references", can be used as column names *Ryan Platte* + +* Added the possibility to chain the return of what happened inside a logged block [geech]: + + This now works: + log { ... }.map { ... } + + Instead of doing: + result = [] + log { result = ... } + result.map { ... } + +* Added "socket" option for the MySQL adapter, so you can change it to something else than "/tmp/mysql.sock" *Anna Lissa Cruz* + +* Added respond_to? answers for all the attribute methods. So if Person has a name attribute retrieved from the table schema, + person.respond_to? "name" will return true. + +* Added Base.benchmark which can be used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block. + Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all): + + Project.benchmark("Creating project") do + project = Project.create("name" => "stuff") + project.create_manager("name" => "David") + project.milestones << Milestone.find_all + end + +* Added logging of invalid SQL statements *Daniel Von Fange* + +* Added alias Errors#[] for Errors#on, so you can now say person.errors["name"] to retrieve the errors for name *Andreas Schwarz* + +* Added RubyGems require attempt if sqlite-ruby is not available through regular methods. + +* Added compatibility with 2.x series of sqlite-ruby drivers. *Jamis Buck* + +* Added type safety for association assignments, so a ActiveRecord::AssociationTypeMismatch will be raised if you attempt to + assign an object that's not of the associated class. This cures the problem with nil giving id = 4 and fixnums giving id = 1 on + mistaken association assignments. *Reported by Andreas Schwarz* + +* Added the option to keep many fixtures in one single YAML document *what-a-day* + +* Added the class method "inheritance_column" that can be overwritten to return the name of an alternative column than "type" for storing + the type for inheritance hierarchies. *Dave Steinberg* + +* Added [] and []= as an alternative way to access attributes when the regular methods have been overwritten *Dave Steinberg* + +* Added the option to observer more than one class at the time by specifying observed_class as an array + +* Added auto-id propagation support for tables with arbitrary primary keys that have autogenerated sequences associated with them + on PostgreSQL. *Dave Steinberg* + +* Changed that integer and floats set to "" through attributes= remain as NULL. This was especially a problem for scaffolding and postgresql. (#49) + +* Changed the MySQL Adapter to rely on MySQL for its defaults for socket, host, and port *Andreas Schwarz* + +* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue. + +* Changed class inheritable attributes to not use eval *Caio Chassot* + +* Changed Errors#add to now use "invalid" as the default message instead of true, which means full_messages work with those *Marcel Molina Jr.* + +* Fixed spelling on Base#add_on_boundry_breaking to Base#add_on_boundary_breaking (old naming still works) *Marcel Molina Jr.* + +* Fixed that entries in the has_and_belongs_to_many join table didn't get removed when an associated object was destroyed. + +* Fixed unnecessary calls to SET AUTOCOMMIT=0/1 for MySQL adapter *Andreas Schwarz* + +* Fixed PostgreSQL defaults are now handled gracefully *Dave Steinberg* + +* Fixed increment/decrement_counter are now atomic updates *Andreas Schwarz* + +* Fixed the problems the Inflector had turning Attachment into attuchments and Cases into Casis *radsaq/Florian Gross* + +* Fixed that cloned records would point attribute references on the parent object *Andreas Schwarz* + +* Fixed SQL for type call on inheritance hierarchies *Caio Chassot* + +* Fixed bug with typed inheritance *Florian Weber* + +* Fixed a bug where has_many collection_count wouldn't use the conditions specified for that association + + +## 0.9.5 ## + +* Expanded the table_name guessing rules immensely [Florian Green]. Documentation: + + Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending + directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used + to guess the table name from even when called on Reply. The guessing rules are as follows: + * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table. + * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies", + so a Category class becomes a categories table. + * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table. + * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table. + * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table. + * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table. + * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table. + * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table. + * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table. + * Class name ends in an "s": No additional characters are added or removed. + * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table. + * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table. + Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended. + So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts". + + You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a + "mice" table. Example: + + class Mouse < ActiveRecord::Base + def self.table_name() "mice" end + end + + This conversion is now done through an external class called Inflector residing in lib/active_record/support/inflector.rb. + +* Added find_all_in_collection to has_many defined collections. Works like this: + + class Firm < ActiveRecord::Base + has_many :clients + end + + firm.id # => 1 + firm.find_all_in_clients "revenue > 1000" # SELECT * FROM clients WHERE firm_id = 1 AND revenue > 1000 + + *Requested by Dave Thomas* + +* Fixed finders for inheritance hierarchies deeper than one level *Florian Weber* + +* Added add_on_boundry_breaking to errors to accompany add_on_empty as a default validation method. It's used like this: + + class Person < ActiveRecord::Base + protected + def validation + errors.add_on_boundry_breaking "password", 3..20 + end + end + + This will add an error to the tune of "is too short (minimum is 3 characters)" or "is too long (minimum is 20 characters)" if + the password is outside the boundry. The messages can be changed by passing a third and forth parameter as message strings. + +* Implemented a clone method that works properly with AR. It returns a clone of the record that + hasn't been assigned an id yet and is treated as a new record. + +* Allow for domain sockets in PostgreSQL by not assuming localhost when no host is specified *Scott Barron* + +* Fixed that bignums are saved properly instead of attempted to be YAMLized *Andreas Schwartz* + +* Fixed a bug in the GEM where the rdoc options weren't being passed according to spec *Chad Fowler* + +* Fixed a bug with the exclusively_dependent option for has_many + + +## 0.9.4 ## + +* Correctly guesses the primary key when the class is inside a module [Dave Steinberg]. + +* Added [] and []= as alternatives to read_attribute and write_attribute *Dave Steinberg* + +* has_and_belongs_to_many now accepts an :order key to determine in which order the collection is returned [radsaq]. + +* The ids passed to find and find_on_conditions are now automatically sanitized. + +* Added escaping of plings in YAML content. + +* Multi-parameter assigns where all the parameters are empty will now be set to nil instead of a new instance of their class. + +* Proper type within an inheritance hierarchy is now ensured already at object initialization (instead of first at create) + + +## 0.9.3 ## + +* Fixed bug with using a different primary key name together with has_and_belongs_to_many *Investigation by Scott* + +* Added :exclusively_dependent option to the has_many association macro. The doc reads: + + If set to true all the associated object are deleted in one SQL statement without having their + before_destroy callback run. This should only be used on associations that depend solely on + this class and don't need to do any clean-up in before_destroy. The upside is that it's much + faster, especially if there's a counter_cache involved. + +* Added :port key to connection options, so the PostgreSQL and MySQL adapters can connect to a database server + running on another port than the default. + +* Converted the new natural singleton methods that prevented AR objects from being saved by PStore + (and hence be placed in a Rails session) to a module. *Florian Weber* + +* Fixed the use of floats (was broken since 0.9.0+) + +* Fixed PostgreSQL adapter so default values are displayed properly when used in conjunction with + Action Pack scaffolding. + +* Fixed booleans support for PostgreSQL (use real true/false on boolean fields instead of 0/1 on tinyints) *radsaq* + + +## 0.9.2 ## + +* Added static method for instantly updating a record + +* Treat decimal and numeric as Ruby floats *Andreas Schwartz* + +* Treat chars as Ruby strings (fixes problem for Action Pack form helpers too) + +* Removed debugging output accidently left in (which would screw web applications) + + +## 0.9.1 ## + +* Added MIT license + +* Added natural object-style assignment for has_and_belongs_to_many associations. Consider the following model: + + class Event < ActiveRecord::Base + has_one_and_belongs_to_many :sponsors + end + + class Sponsor < ActiveRecord::Base + has_one_and_belongs_to_many :sponsors + end + + Earlier, you'd have to use synthetic methods for creating associations between two objects of the above class: + + roskilde_festival.add_to_sponsors(carlsberg) + roskilde_festival.remove_from_sponsors(carlsberg) + + nike.add_to_events(world_cup) + nike.remove_from_events(world_cup) + + Now you can use regular array-styled methods: + + roskilde_festival.sponsors << carlsberg + roskilde_festival.sponsors.delete(carlsberg) + + nike.events << world_cup + nike.events.delete(world_cup) + +* Added delete method for has_many associations. Using this will nullify an association between the has_many and the belonging + object by setting the foreign key to null. Consider this model: + + class Post < ActiveRecord::Base + has_many :comments + end + + class Comment < ActiveRecord::Base + belongs_to :post + end + + You could do something like: + + funny_comment.has_post? # => true + announcement.comments.delete(funny_comment) + funny_comment.has_post? # => false + + +## 0.9.0 ## + +* Active Record is now thread safe! (So you can use it with Cerise and WEBrick applications) + *Implementation idea by Michael Neumann, debugging assistance by Jamis Buck* + +* Improved performance by roughly 400% on a basic test case of pulling 100 records and querying one attribute. + This brings the tax for using Active Record instead of "riding on the metal" (using MySQL-ruby C-driver directly) down to ~50%. + Done by doing lazy type conversions and caching column information on the class-level. + +* Added callback objects and procs as options for implementing the target for callback macros. + +* Added "counter_cache" option to belongs_to that automates the usage of increment_counter and decrement_counter. Consider: + + class Post < ActiveRecord::Base + has_many :comments + end + + class Comment < ActiveRecord::Base + belongs_to :post + end + + Iterating over 100 posts like this: + + <% for post in @posts %> + <%= post.title %> has <%= post.comments_count %> comments + <% end %> + + Will generate 100 SQL count queries -- one for each call to post.comments_count. If you instead add a "comments_count" int column + to the posts table and rewrite the comments association macro with: + + class Comment < ActiveRecord::Base + belongs_to :post, :counter_cache => true + end + + Those 100 SQL count queries will be reduced to zero. Beware that counter caching is only appropriate for objects that begin life + with the object it's specified to belong with and is destroyed like that as well. Typically objects where you would also specify + :dependent => true. If your objects switch from one belonging to another (like a post that can be move from one category to another), + you'll have to manage the counter yourself. + +* Added natural object-style assignment for has_one and belongs_to associations. Consider the following model: + + class Project < ActiveRecord::Base + has_one :manager + end + + class Manager < ActiveRecord::Base + belongs_to :project + end + + Earlier, assignments would work like following regardless of which way the assignment told the best story: + + active_record.manager_id = david.id + + Now you can do it either from the belonging side: + + david.project = active_record + + ...or from the having side: + + active_record.manager = david + + If the assignment happens from the having side, the assigned object is automatically saved. So in the example above, the + project_id attribute on david would be set to the id of active_record, then david would be saved. + +* Added natural object-style assignment for has_many associations [Florian Weber]. Consider the following model: + + class Project < ActiveRecord::Base + has_many :milestones + end + + class Milestone < ActiveRecord::Base + belongs_to :project + end + + Earlier, assignments would work like following regardless of which way the assignment told the best story: + + deadline.project_id = active_record.id + + Now you can do it either from the belonging side: + + deadline.project = active_record + + ...or from the having side: + + active_record.milestones << deadline + + The milestone is automatically saved with the new foreign key. + +* API CHANGE: Attributes for text (or blob or similar) columns will now have unknown classes stored using YAML instead of using + to_s. (Known classes that won't be yamelized are: String, NilClass, TrueClass, FalseClass, Fixnum, Date, and Time). + Likewise, data pulled out of text-based attributes will be attempted converged using Yaml if they have the "--- " header. + This was primarily done to be enable the storage of hashes and arrays without wrapping them in aggregations, so now you can do: + + user = User.find(1) + user.preferences = { "background" => "black", "display" => large } + user.save + + User.find(1).preferences # => { "background" => "black", "display" => large } + + Please note that this method should only be used when you don't care about representing the object in proper columns in + the database. A money object consisting of an amount and a currency is still a much better fit for a value object done through + aggregations than this new option. + +* POSSIBLE CODE BREAKAGE: As a consequence of the lazy type conversions, it's a bad idea to reference the @attributes hash + directly (it always was, but now it's paramount that you don't). If you do, you won't get the type conversion. So to implement + new accessors for existing attributes, use read_attribute(attr_name) and write_attribute(attr_name, value) instead. Like this: + + class Song < ActiveRecord::Base + # Uses an integer of seconds to hold the length of the song + + def length=(minutes) + write_attribute("length", minutes * 60) + end + + def length + read_attribute("length") / 60 + end + end + + The clever kid will notice that this opens a door to sidestep the automated type conversion by using @attributes directly. + This is not recommended as read/write_attribute may be granted additional responsibilities in the future, but if you think + you know what you're doing and aren't afraid of future consequences, this is an option. + +* Applied a few minor bug fixes reported by Daniel Von Fange. + + +## 0.8.4 ## + + _Reflection_ +* Added ActiveRecord::Reflection with a bunch of methods and classes for reflecting in aggregations and associations. + +* Added Base.columns and Base.content_columns which returns arrays of column description (type, default, etc) objects. + +* Added Base#attribute_names which returns an array of names for the attributes available on the object. + +* Added Base#column_for_attribute(name) which returns the column description object for the named attribute. + + + _Misc_ +* Added multi-parameter assignment: + + # Instantiate objects for all attribute classes that needs more than one constructor parameter. This is done + # by calling new on the column type or aggregation type (through composed_of) object with these parameters. + # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate + # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the + # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float, + # s for String, and a for Array. + + This is incredibly useful for assigning dates from HTML drop-downs of month, year, and day. + +* Fixed bug with custom primary key column name and Base.find on multiple parameters. + +* Fixed bug with dependent option on has_one associations if there was no associated object. + + +## 0.8.3 ## + + _Transactions_ +* Added transactional protection for destroy (important for the new :dependent option) *Suggested by Carl Youngblood* + +* Fixed so transactions are ignored on MyISAM tables for MySQL (use InnoDB to get transactions) + +* Changed transactions so only exceptions will cause a rollback, not returned false. + + + _Mapping_ +* Added support for non-integer primary keys *Aredridel/earlier work by Michael Neumann* + + User.find "jdoe" + Product.find "PDKEY-INT-12" + +* Added option to specify naming method for primary key column. ActiveRecord::Base.primary_key_prefix_type can either + be set to nil, :table_name, or :table_name_with_underscore. :table_name will assume that Product class has a primary key + of "productid" and :table_name_with_underscore will assume "product_id". The default nil will just give "id". + +* Added an overwriteable primary_key method that'll instruct AR to the name of the + id column *Aredridele/earlier work by Guan Yang* + + class Project < ActiveRecord::Base + def self.primary_key() "project_id" end + end + +* Fixed that Active Records can safely associate inside and out of modules. + + class MyApplication::Account < ActiveRecord::Base + has_many :clients # will look for MyApplication::Client + has_many :interests, :class_name => "Business::Interest" # will look for Business::Interest + end + +* Fixed that Active Records can safely live inside modules *Aredridel* + + class MyApplication::Account < ActiveRecord::Base + end + + + _Misc_ +* Added freeze call to value object assignments to ensure they remain immutable *Spotted by Gavin Sinclair* + +* Changed interface for specifying observed class in observers. Was OBSERVED_CLASS constant, now is + observed_class() class method. This is more consistant with things like self.table_name(). Works like this: + + class AuditObserver < ActiveRecord::Observer + def self.observed_class() Account end + def after_update(account) + AuditTrail.new(account, "UPDATED") + end + end + + *Suggested by Gavin Sinclair* + +* Create new Active Record objects by setting the attributes through a block. Like this: + + person = Person.new do |p| + p.name = 'Freddy' + p.age = 19 + end + + *Suggested by Gavin Sinclair* + + +## 0.8.2 ## + +* Added inheritable callback queues that can ensure that certain callback methods or inline fragments are + run throughout the entire inheritance hierarchy. Regardless of whether a descendant overwrites the callback + method: + + class Topic < ActiveRecord::Base + before_destroy :destroy_author, 'puts "I'm an inline fragment"' + end + + Learn more in link:classes/ActiveRecord/Callbacks.html + +* Added :dependent option to has_many and has_one, which will automatically destroy associated objects when + the holder is destroyed: + + class Album < ActiveRecord::Base + has_many :tracks, :dependent => true + end + + All the associated tracks are destroyed when the album is. + +* Added Base.create as a factory that'll create, save, and return a new object in one step. + +* Automatically convert strings in config hashes to symbols for the _connection methods. This allows you + to pass the argument hashes directly from yaml. (Luke) + +* Fixed the install.rb to include simple.rb *Spotted by Kevin Bullock* + +* Modified block syntax to better follow our code standards outlined in + http://www.rubyonrails.org/CodingStandards + + +## 0.8.1 ## + +* Added object-level transactions *Austin Ziegler* + +* Changed adapter-specific connection methods to use centralized ActiveRecord::Base.establish_connection, + which is parametized through a config hash with symbol keys instead of a regular parameter list. + This will allow for database connections to be opened in a more generic fashion. (Luke) + + NOTE: This requires all *_connections to be updated! Read more in: + http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000081 + +* Fixed SQLite adapter so objects fetched from has_and_belongs_to_many have proper attributes + (t.name is now name). *Spotted by Garrett Rooney* + +* Fixed SQLite adapter so dates are returned as Date objects, not Time objects *Spotted by Gavin Sinclair* + +* Fixed requirement of date class, so date conversions are succesful regardless of whether you + manually require date or not. + + +## 0.8.0 ## + +* Added transactions + +* Changed Base.find to also accept either a list (1, 5, 6) or an array of ids ([5, 7]) + as parameter and then return an array of objects instead of just an object + +* Fixed method has_collection? for has_and_belongs_to_many macro to behave as a + collection, not an association + +* Fixed SQLite adapter so empty or nil values in columns of datetime, date, or time type + aren't treated as current time *Spotted by Gavin Sinclair* + + +## 0.7.6 ## + +* Fixed the install.rb to create the lib/active_record/support directory *Spotted by Gavin Sinclair* +* Fixed that has_association? would always return true *Daniel Von Fange* diff --git a/activerecord/MIT-LICENSE b/activerecord/MIT-LICENSE index c73d1af096..03bde18130 100644 --- a/activerecord/MIT-LICENSE +++ b/activerecord/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2011 David Heinemeier Hansson +Copyright (c) 2004-2012 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc index b5db57569c..30a66ff5f0 100644 --- a/activerecord/README.rdoc +++ b/activerecord/README.rdoc @@ -143,14 +143,14 @@ A short rundown of some of the major features: * Logging support for Log4r[http://log4r.sourceforge.net] and Logger[http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc]. - ActiveRecord::Base.logger = Logger.new(STDOUT) + ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT) ActiveRecord::Base.logger = Log4r::Logger.new("Application Log") * Database agnostic schema management with Migrations. class AddSystemSettings < ActiveRecord::Migration - def self.up + def up create_table :system_settings do |t| t.string :name t.string :label @@ -162,7 +162,7 @@ A short rundown of some of the major features: SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1 end - def self.down + def down drop_table :system_settings end end @@ -208,7 +208,9 @@ Source code can be downloaded as part of the Rails project on GitHub == License -Active Record is released under the MIT license. +Active Record is released under the MIT license: + +* http://www.opensource.org/licenses/MIT == Support diff --git a/activerecord/Rakefile b/activerecord/Rakefile index d769a73dba..4090293b56 100755 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -48,8 +48,8 @@ end |x| x =~ /\/adapters\// } + Dir.glob("test/cases/adapters/#{adapter_short}/**/*_test.rb")).sort - t.verbose = true t.warning = true + t.verbose = true } task "isolated_test_#{adapter}" do @@ -187,15 +187,15 @@ end task :lines do lines, codelines, total_lines, total_codelines = 0, 0, 0, 0 - for file_name in FileList["lib/active_record/**/*.rb"] + FileList["lib/active_record/**/*.rb"].each do |file_name| next if file_name =~ /vendor/ - f = File.open(file_name) - - while line = f.gets - lines += 1 - next if line =~ /^\s*$/ - next if line =~ /^\s*#/ - codelines += 1 + File.open(file_name, 'r') do |f| + while line = f.gets + lines += 1 + next if line =~ /^\s*$/ + next if line =~ /^\s*#/ + codelines += 1 + end end puts "L: #{sprintf("%4d", lines)}, LOC #{sprintf("%4d", codelines)} | #{file_name}" diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 2de81c31a3..8484e1093e 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -7,13 +7,13 @@ 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 = '>= 1.8.7' + s.required_ruby_version = '>= 1.9.3' s.author = 'David Heinemeier Hansson' s.email = 'david@loudthinking.com' s.homepage = 'http://www.rubyonrails.org' - s.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*'] + s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*'] s.require_path = 'lib' s.extra_rdoc_files = %w( README.rdoc ) @@ -21,6 +21,6 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) - s.add_dependency('arel', '~> 2.2.1') + s.add_dependency('arel', '~> 3.0.0') s.add_dependency('tzinfo', '~> 0.3.29') end diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb index 63822731d5..31f3e02bb8 100644 --- a/activerecord/examples/performance.rb +++ b/activerecord/examples/performance.rb @@ -1,6 +1,6 @@ TIMES = (ENV['N'] || 10000).to_i -require 'rubygems' +require File.expand_path('../../../load_paths', __FILE__) require "active_record" conn = { :adapter => 'sqlite3', :database => ':memory:' } @@ -29,6 +29,14 @@ class Exhibit < ActiveRecord::Base def look; attributes end def feel; look; user.name end + def self.with_name + where("name IS NOT NULL") + end + + def self.with_notes + where("notes IS NOT NULL") + end + def self.look(exhibits) exhibits.each { |e| e.look } end def self.feel(exhibits) exhibits.each { |e| e.feel } end end @@ -37,7 +45,14 @@ puts 'Generating data...' module ActiveRecord class Faker - LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. Praesent varius tincidunt commodo".split + LOREM = %Q{Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. + Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. + Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, + tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, + varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum + tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. + Praesent varius tincidunt commodo}.split + def self.name LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join ' ' end @@ -102,6 +117,10 @@ Benchmark.bm(46) do |x| TIMES.times { Exhibit.first.look } end + x.report 'Model.named_scope' do + TIMES.times { Exhibit.limit(10).with_name.with_notes } + end + x.report("Model.all limit(100) (x#{(TIMES / 10).ceil})") do (TIMES / 10).ceil.times { Exhibit.look Exhibit.limit(100) } end diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 132dc12680..73c8a06ab7 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2004-2011 David Heinemeier Hansson +# Copyright (c) 2004-2012 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -39,9 +39,11 @@ module ActiveRecord autoload :Aggregations autoload :Associations autoload :AttributeMethods + autoload :AttributeAssignment autoload :AutosaveAssociation autoload :Relation + autoload :NullRelation autoload_under 'relation' do autoload :QueryMethods @@ -50,30 +52,45 @@ module ActiveRecord autoload :PredicateBuilder autoload :SpawnMethods autoload :Batches + autoload :Explain + autoload :Delegation end autoload :Base autoload :Callbacks + autoload :Core autoload :CounterCache + autoload :ConnectionHandling + autoload :DynamicMatchers autoload :DynamicFinderMatch autoload :DynamicScopeMatch + autoload :Explain + autoload :IdentityMap + autoload :Inheritance + autoload :Integration autoload :Migration autoload :Migrator, 'active_record/migration' - autoload :NamedScope + autoload :Model + autoload :ModelSchema autoload :NestedAttributes autoload :Observer autoload :Persistence autoload :QueryCache + autoload :Querying + autoload :ReadonlyAttributes autoload :Reflection autoload :Result + autoload :Sanitization autoload :Schema autoload :SchemaDumper + autoload :Scoping autoload :Serialization autoload :SessionStore + autoload :Store autoload :Timestamp autoload :Transactions + autoload :Translation autoload :Validations - autoload :IdentityMap end module Coders @@ -91,6 +108,7 @@ module ActiveRecord autoload :Read autoload :TimeZoneConversion autoload :Write + autoload :Serialization end end @@ -112,6 +130,15 @@ module ActiveRecord end end + module Scoping + extend ActiveSupport::Autoload + + eager_autoload do + autoload :Named + autoload :Default + end + end + autoload :TestCase autoload :TestFixtures, 'active_record/fixtures' end diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb index 81ddbba51e..5a8addc4e4 100644 --- a/activerecord/lib/active_record/aggregations.rb +++ b/activerecord/lib/active_record/aggregations.rb @@ -172,8 +172,8 @@ module ActiveRecord # with this option. # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value # object. Each mapping is represented as an array where the first item is the name of the - # entity attribute and the second item is the name the attribute in the value object. The - # order in which mappings are defined determine the order in which attributes are sent to the + # entity attribute and the second item is the name of the attribute in the value object. The + # order in which mappings are defined determines the order in which attributes are sent to the # value class constructor. # * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all @@ -191,7 +191,8 @@ module ActiveRecord # # Option examples: # composed_of :temperature, :mapping => %w(reading celsius) - # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money } + # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), + # :converter => Proc.new { |balance| balance.to_money } # composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ] # composed_of :gps_location # composed_of :gps_location, :allow_nil => true diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 9e7d609d19..958821add6 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1,4 +1,3 @@ -require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/enumerable' require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/object/blank' @@ -70,7 +69,7 @@ module ActiveRecord end end - class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc + class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc: def initialize(owner, reflection) super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.") end @@ -196,6 +195,26 @@ module ActiveRecord # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt> # <tt>Project#categories.delete(category1)</tt> # + # === Overriding generated methods + # + # Association methods are generated in a module that is included into the model class, + # which allows you to easily override with your own methods and call the original + # generated method with +super+. For example: + # + # class Car < ActiveRecord::Base + # belongs_to :owner + # belongs_to :old_owner + # def owner=(new_owner) + # self.old_owner = self.owner + # super + # end + # end + # + # If your model class is <tt>Project</tt>, the module is + # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is + # included in the model class immediately after the (anonymous) generated attributes methods + # module, meaning an association will override the methods for an attribute with the same name. + # # === A word of warning # # Don't create associations that have the same name as instance methods of @@ -1078,8 +1097,8 @@ module ActiveRecord # alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated # objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated # objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. If set to - # <tt>:restrict</tt> this object raises an <tt>ActiveRecord::DeleteRestrictionError</tt> exception and - # cannot be deleted if it has any associated objects. + # <tt>:restrict</tt> an error will be added to the object, preventing its deletion, if any associated + # objects are present. # # If using with the <tt>:through</tt> option, the association on the join model must be # a +belongs_to+, and the records which get deleted are the join records, rather than @@ -1165,7 +1184,7 @@ module ActiveRecord # has_many :subscribers, :through => :subscriptions, :source => :user # has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new { # %Q{ - # SELECT DISTINCT people.* + # SELECT DISTINCT * # FROM people p, post_subscriptions ps # WHERE ps.post_id = #{id} AND ps.person_id = p.id # ORDER BY p.first_name @@ -1232,8 +1251,8 @@ module ActiveRecord # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. # If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+. - # Also, association is assigned. If set to <tt>:restrict</tt> this object raises an - # <tt>ActiveRecord::DeleteRestrictionError</tt> exception and cannot be deleted if it has any associated object. + # If set to <tt>:restrict</tt>, an error will be added to the object, preventing its deletion, if an + # associated object is present. # [:foreign_key] # Specify the foreign key used for the association. By default this is guessed to be the name # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association @@ -1424,18 +1443,18 @@ module ActiveRecord # join table with a migration such as this: # # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration - # def self.up + # def change # create_table :developers_projects, :id => false do |t| # t.integer :developer_id # t.integer :project_id # end # end - # - # def self.down - # drop_table :developers_projects - # end # end # + # It's also a good idea to add indexes to each of those columns to speed up the joins process. + # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only + # uses one index per table during the lookup. + # # Adds the following methods for retrieval and query: # # [collection(force_reload = false)] @@ -1575,7 +1594,7 @@ module ActiveRecord # has_and_belongs_to_many :categories, :join_table => "prods_cats" # has_and_belongs_to_many :categories, :readonly => true # has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql => - # 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}' + # "DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}" def has_and_belongs_to_many(name, options = {}, &extension) Builder::HasAndBelongsToMany.build(self, name, options, &extension) end diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index d1e3ff8e38..7887d59aad 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -231,10 +231,7 @@ module ActiveRecord def build_record(attributes, options) reflection.build_association(attributes, options) do |record| - record.assign_attributes( - create_scope.except(*record.changed), - :without_protection => true - ) + record.assign_attributes(create_scope.except(*record.changed), :without_protection => true) end end end diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb index 9e6d9e73c5..0209ce36df 100644 --- a/activerecord/lib/active_record/associations/association_scope.rb +++ b/activerecord/lib/active_record/associations/association_scope.rb @@ -15,40 +15,24 @@ module ActiveRecord def scope scope = klass.unscoped - scope = scope.extending(*Array.wrap(options[:extend])) + scope = scope.extending(*Array(options[:extend])) # It's okay to just apply all these like this. The options will only be present if the # association supports that option; this is enforced by the association builder. scope = scope.apply_finder_options(options.slice( - :readonly, :include, :order, :limit, :joins, :group, :having, :offset)) + :readonly, :include, :references, :order, :limit, :joins, :group, :having, :offset, :select)) if options[:through] && !options[:include] scope = scope.includes(source_options[:include]) end - if select = select_value - scope = scope.select(select) - end + scope = scope.uniq if options[:uniq] add_constraints(scope) end private - def select_value - select_value = options[:select] - - if reflection.collection? - select_value ||= options[:uniq] && "DISTINCT #{reflection.quoted_table_name}.*" - end - - if reflection.macro == :has_and_belongs_to_many - select_value ||= reflection.klass.arel_table[Arel.star] - end - - select_value - end - def add_constraints(scope) tables = construct_tables @@ -68,7 +52,12 @@ module ActiveRecord end if reflection.source_macro == :belongs_to - key = reflection.association_primary_key + if reflection.options[:polymorphic] + key = reflection.association_primary_key(klass) + else + key = reflection.association_primary_key + end + foreign_key = reflection.foreign_key else key = reflection.foreign_key @@ -101,8 +90,11 @@ module ActiveRecord scope = scope.joins(join(foreign_table, constraint)) - unless conditions.empty? - scope = scope.where(sanitize(conditions, table)) + conditions.each do |condition| + condition = interpolate(condition) + condition = { (table.table_alias || table.name) => condition } unless i == 0 + + scope = scope.where(condition) end end end diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb index 58c9648ce8..97f531d064 100644 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -45,7 +45,11 @@ module ActiveRecord end def replace_keys(record) - owner[reflection.foreign_key] = record && record[reflection.association_primary_key] + if record + owner[reflection.foreign_key] = record[reflection.association_primary_key(record.class)] + else + owner[reflection.foreign_key] = nil + end end def foreign_key_present? diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb index 96fca97440..2059d8acdf 100644 --- a/activerecord/lib/active_record/associations/builder/association.rb +++ b/activerecord/lib/active_record/associations/builder/association.rb @@ -1,7 +1,7 @@ module ActiveRecord::Associations::Builder class Association #:nodoc: class_attribute :valid_options - self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate] + self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate, :references] # Set by subclasses class_attribute :macro @@ -16,6 +16,10 @@ module ActiveRecord::Associations::Builder @model, @name, @options = model, name, options end + def mixin + @model.generated_feature_methods + end + def build validate_options reflection = model.create_reflection(self.class.macro, name, options, model) @@ -36,18 +40,47 @@ module ActiveRecord::Associations::Builder def define_readers name = self.name - - model.redefine_method(name) do |*params| + mixin.redefine_method(name) do |*params| association(name).reader(*params) end end def define_writers name = self.name - - model.redefine_method("#{name}=") do |value| + mixin.redefine_method("#{name}=") do |value| association(name).writer(value) end end + + def dependent_restrict_raises? + ActiveRecord::Base.dependent_restrict_raises == true + end + + def dependent_restrict_deprecation_warning + if dependent_restrict_raises? + msg = "In the next release, `:dependent => :restrict` will not raise a `DeleteRestrictionError`. "\ + "Instead, it will add an error on the model. To fix this warning, make sure your code " \ + "isn't relying on a `DeleteRestrictionError` and then add " \ + "`config.active_record.dependent_restrict_raises = false` to your application config." + ActiveSupport::Deprecation.warn msg + end + end + + def define_restrict_dependency_method + name = self.name + mixin.redefine_method(dependency_method_name) do + # has_many or has_one associations + if send(name).respond_to?(:exists?) ? send(name).exists? : !send(name).nil? + if dependent_restrict_raises? + raise ActiveRecord::DeleteRestrictionError.new(name) + else + key = association(name).reflection.macro == :has_one ? "one" : "many" + errors.add(:base, :"restrict_dependent_destroy.#{key}", + :record => self.class.human_attribute_name(name).downcase) + return false + end + end + end + end end end diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb index f6d26840c2..4183c222de 100644 --- a/activerecord/lib/active_record/associations/builder/belongs_to.rb +++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb @@ -25,16 +25,18 @@ module ActiveRecord::Associations::Builder name = self.name method_name = "belongs_to_counter_cache_after_create_for_#{name}" - model.redefine_method(method_name) do + mixin.redefine_method(method_name) do record = send(name) record.class.increment_counter(cache_column, record.id) unless record.nil? end model.after_create(method_name) method_name = "belongs_to_counter_cache_before_destroy_for_#{name}" - model.redefine_method(method_name) do - record = send(name) - record.class.decrement_counter(cache_column, record.id) unless record.nil? + mixin.redefine_method(method_name) do + unless marked_for_destruction? + record = send(name) + record.class.decrement_counter(cache_column, record.id) unless record.nil? + end end model.before_destroy(method_name) @@ -48,7 +50,7 @@ module ActiveRecord::Associations::Builder method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}" touch = options[:touch] - model.redefine_method(method_name) do + mixin.redefine_method(method_name) do record = send(name) unless record.nil? diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb index f62209a226..768f70b6c9 100644 --- a/activerecord/lib/active_record/associations/builder/collection_association.rb +++ b/activerecord/lib/active_record/associations/builder/collection_association.rb @@ -32,7 +32,7 @@ module ActiveRecord::Associations::Builder private def wrap_block_extension - options[:extend] = Array.wrap(options[:extend]) + options[:extend] = Array(options[:extend]) if block_extension silence_warnings do @@ -51,14 +51,14 @@ module ActiveRecord::Associations::Builder # TODO : why do i need method_defined? I think its because of the inheritance chain model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name) - model.send("#{full_callback_name}=", Array.wrap(options[callback_name.to_sym])) + model.send("#{full_callback_name}=", Array(options[callback_name.to_sym])) end def define_readers super name = self.name - model.redefine_method("#{name.to_s.singularize}_ids") do + mixin.redefine_method("#{name.to_s.singularize}_ids") do association(name).ids_reader end end @@ -67,7 +67,7 @@ module ActiveRecord::Associations::Builder super name = self.name - model.redefine_method("#{name.to_s.singularize}_ids=") do |ids| + mixin.redefine_method("#{name.to_s.singularize}_ids=") do |ids| association(name).ids_writer(ids) end end diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index 30fc44b4c2..0b634ab944 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -18,7 +18,7 @@ module ActiveRecord::Associations::Builder model.send(:include, Module.new { class_eval <<-RUBY, __FILE__, __LINE__ + 1 def destroy_associations - association(#{name.to_sym.inspect}).delete_all + association(#{name.to_sym.inspect}).delete_all_on_destroy super end RUBY diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb index ecbc70888f..9ddfd433e4 100644 --- a/activerecord/lib/active_record/associations/builder/has_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_many.rb @@ -21,6 +21,7 @@ module ActiveRecord::Associations::Builder ":nullify or :restrict (#{options[:dependent].inspect})" end + dependent_restrict_deprecation_warning if options[:dependent] == :restrict send("define_#{options[:dependent]}_dependency_method") model.before_destroy dependency_method_name end @@ -28,15 +29,10 @@ module ActiveRecord::Associations::Builder def define_destroy_dependency_method name = self.name - model.send(:define_method, dependency_method_name) do + mixin.redefine_method(dependency_method_name) do send(name).each do |o| # No point in executing the counter update since we're going to destroy the parent anyway - counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym - if o.respond_to?(counter_method) - class << o - self - end.send(:define_method, counter_method, Proc.new {}) - end + o.mark_for_destruction end send(name).delete_all @@ -45,16 +41,15 @@ module ActiveRecord::Associations::Builder def define_delete_all_dependency_method name = self.name - model.send(:define_method, dependency_method_name) do - send(name).delete_all + mixin.redefine_method(dependency_method_name) do + association(name).delete_all_on_destroy end end - alias :define_nullify_dependency_method :define_delete_all_dependency_method - def define_restrict_dependency_method + def define_nullify_dependency_method name = self.name - model.send(:define_method, dependency_method_name) do - raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).empty? + mixin.redefine_method(dependency_method_name) do + send(name).delete_all end end diff --git a/activerecord/lib/active_record/associations/builder/has_one.rb b/activerecord/lib/active_record/associations/builder/has_one.rb index 88c0d3e90f..bc8a212bee 100644 --- a/activerecord/lib/active_record/associations/builder/has_one.rb +++ b/activerecord/lib/active_record/associations/builder/has_one.rb @@ -34,30 +34,23 @@ module ActiveRecord::Associations::Builder ":nullify or :restrict (#{options[:dependent].inspect})" end + dependent_restrict_deprecation_warning if options[:dependent] == :restrict send("define_#{options[:dependent]}_dependency_method") model.before_destroy dependency_method_name end end - def dependency_method_name - "has_one_dependent_#{options[:dependent]}_for_#{name}" - end - def define_destroy_dependency_method - model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1) - def #{dependency_method_name} - association(#{name.to_sym.inspect}).delete - end - eoruby + name = self.name + mixin.redefine_method(dependency_method_name) do + association(name).delete + end end alias :define_delete_dependency_method :define_destroy_dependency_method alias :define_nullify_dependency_method :define_destroy_dependency_method - def define_restrict_dependency_method - name = self.name - model.redefine_method(dependency_method_name) do - raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).nil? - end + def dependency_method_name + "has_one_dependent_#{options[:dependent]}_for_#{name}" end end end diff --git a/activerecord/lib/active_record/associations/builder/singular_association.rb b/activerecord/lib/active_record/associations/builder/singular_association.rb index 0cbbba041a..436b6c1524 100644 --- a/activerecord/lib/active_record/associations/builder/singular_association.rb +++ b/activerecord/lib/active_record/associations/builder/singular_association.rb @@ -16,15 +16,15 @@ module ActiveRecord::Associations::Builder def define_constructors name = self.name - model.redefine_method("build_#{name}") do |*params, &block| + mixin.redefine_method("build_#{name}") do |*params, &block| association(name).build(*params, &block) end - model.redefine_method("create_#{name}") do |*params, &block| + mixin.redefine_method("create_#{name}") do |*params, &block| association(name).create(*params, &block) end - model.redefine_method("create_#{name}!") do |*params, &block| + mixin.redefine_method("create_#{name}!") do |*params, &block| association(name).create!(*params, &block) end end diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index cec876149c..b2136605e1 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/array/wrap' - module ActiveRecord module Associations # = Active Record Association Collection @@ -49,17 +47,25 @@ module ActiveRecord end else column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}" + relation = scoped - scoped.select(column).map! do |record| - record.send(reflection.association_primary_key) + including = (relation.eager_load_values + relation.includes_values).uniq + + if including.any? + join_dependency = ActiveRecord::Associations::JoinDependency.new(reflection.klass, including, []) + relation = join_dependency.join_associations.inject(relation) do |r, association| + association.join_relation(r) + end end + + relation.pluck(column) end end # Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items def ids_writer(ids) pk_column = reflection.primary_key_column - ids = Array.wrap(ids).reject { |id| id.blank? } + ids = Array(ids).reject { |id| id.blank? } ids.map! { |i| pk_column.type_cast(i) } replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids)) end @@ -152,6 +158,13 @@ module ActiveRecord end end + # Called when the association is declared as :dependent => :delete_all. This is + # an optimised version which avoids loading the records into memory. Not really + # for public consumption. + def delete_all_on_destroy + scoped.delete_all + end + # Destroy all the records from this association. # # See destroy for more info. @@ -235,7 +248,7 @@ module ActiveRecord # This method is abstract in the sense that it relies on # +count_records+, which is a method descendants have to provide. def size - if owner.new_record? || (loaded? && !options[:uniq]) + if !find_target? || (loaded? && !options[:uniq]) target.size elsif !loaded? && options[:group] load_target.size @@ -344,8 +357,12 @@ module ActiveRecord if options[:counter_sql] interpolate(options[:counter_sql]) else - # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */ - interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" } + # replace the SELECT clause with COUNT(SELECTS), preserving any hints within /* ... */ + interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) do + count_with = $2.to_s + count_with = '*' if count_with.blank? || count_with =~ /,/ + "SELECT #{$1}COUNT(#{count_with}) FROM" + end end end @@ -381,12 +398,7 @@ module ActiveRecord return memory if persisted.empty? persisted.map! do |record| - # Unfortunately we cannot simply do memory.delete(record) since on 1.8 this returns - # record rather than memory.at(memory.index(record)). The behavior is fixed in 1.9. - mem_index = memory.index(record) - - if mem_index - mem_record = memory.delete_at(mem_index) + if mem_record = memory.delete(record) (record.attribute_names - mem_record.changes.keys).each do |name| mem_record[name] = record[name] diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 6ba3d45aff..5eda0387c4 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -39,21 +39,20 @@ module ActiveRecord instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil\?|send|object_id|to_a)$|^__|^respond_to|proxy_/ } delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, - :lock, :readonly, :having, :to => :scoped + :lock, :readonly, :having, :pluck, :to => :scoped - delegate :target, :load_target, :loaded?, :scoped, - :to => :@association + delegate :target, :load_target, :loaded?, :to => :@association delegate :select, :find, :first, :last, :build, :create, :create!, - :concat, :delete_all, :destroy_all, :delete, :destroy, :uniq, + :concat, :replace, :delete_all, :destroy_all, :delete, :destroy, :uniq, :sum, :count, :size, :length, :empty?, :any?, :many?, :include?, :to => :@association def initialize(association) @association = association - Array.wrap(association.options[:extend]).each { |ext| proxy_extend(ext) } + Array(association.options[:extend]).each { |ext| proxy_extend(ext) } end alias_method :new, :build @@ -62,6 +61,13 @@ module ActiveRecord @association end + def scoped + association = @association + association.scoped.extending do + define_method(:proxy_association) { association } + end + end + def respond_to?(name, include_private = false) super || (load_target && target.respond_to?(name, include_private)) || @@ -76,9 +82,8 @@ module ActiveRecord proxy_association.send :add_to_target, r yield(r) if block_given? end - end - if target.respond_to?(method) || (!proxy_association.klass.respond_to?(method) && Class.respond_to?(method)) + elsif target.respond_to?(method) || (!proxy_association.klass.respond_to?(method) && Class.respond_to?(method)) if load_target if target.respond_to?(method) target.send(method, *args, &block) diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index 1f917f58f2..a4cea99372 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -32,6 +32,10 @@ module ActiveRecord record end + # ActiveRecord::Relation#delete_all needs to support joins before we can use a + # SQL-only implementation. + alias delete_all_on_destroy delete_all + private def count_records diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 50ee60284c..059e6c77bc 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -99,6 +99,10 @@ module ActiveRecord end end end + + def foreign_key_present? + owner.attribute_present?(reflection.association_primary_key) + end end end end diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 2e818dca5d..9657cb081d 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -6,6 +6,13 @@ module ActiveRecord class HasManyThroughAssociation < HasManyAssociation #:nodoc: include ThroughAssociation + def initialize(owner, reflection) + super + + @through_records = {} + @through_association = nil + end + # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been # loaded and calling collection.size if it has. If it's more likely than not that the collection does # have a size larger than zero, and you need to fetch that collection afterwards, it'll take one fewer @@ -42,27 +49,40 @@ module ActiveRecord end end - through_record(record).save! + save_through_record(record) update_counter(1) record end - private + # ActiveRecord::Relation#delete_all needs to support joins before we can use a + # SQL-only implementation. + alias delete_all_on_destroy delete_all - def through_record(record) - through_association = owner.association(through_reflection.name) - attributes = construct_join_attributes(record) + private - through_record = Array.wrap(through_association.target).find { |candidate| - candidate.attributes.slice(*attributes.keys) == attributes - } + def through_association + @through_association ||= owner.association(through_reflection.name) + end - unless through_record - through_record = through_association.build(attributes) + # We temporarily cache through record that has been build, because if we build a + # through record in build_record and then subsequently call insert_record, then we + # want to use the exact same object. + # + # However, after insert_record has been called, we clear the cache entry because + # we want it to be possible to have multiple instances of the same record in an + # association + def build_through_record(record) + @through_records[record.object_id] ||= begin + through_record = through_association.build(construct_join_attributes(record)) through_record.send("#{source_reflection.name}=", record) + through_record end + end - through_record + def save_through_record(record) + build_through_record(record).save! + ensure + @through_records.delete(record.object_id) end def build_record(attributes, options = {}) @@ -73,9 +93,9 @@ module ActiveRecord inverse = source_reflection.inverse_of if inverse if inverse.macro == :has_many - record.send(inverse.name) << through_record(record) + record.send(inverse.name) << build_through_record(record) elsif inverse.macro == :has_one - record.send("#{inverse.name}=", through_record(record)) + record.send("#{inverse.name}=", build_through_record(record)) end end @@ -104,8 +124,7 @@ module ActiveRecord def delete_records(records, method) ensure_not_nested - through = owner.association(through_reflection.name) - scope = through.scoped.where(construct_join_attributes(*records)) + scope = through_association.scoped.where(construct_join_attributes(*records)) case method when :destroy @@ -116,7 +135,7 @@ module ActiveRecord count = scope.delete_all end - delete_through_records(through, records) + delete_through_records(records) if through_reflection.macro == :has_many && update_through_counter?(method) update_counter(-count, through_reflection) @@ -125,15 +144,25 @@ module ActiveRecord update_counter(-count) end - def delete_through_records(through, records) - if through_reflection.macro == :has_many - records.each do |record| - through.target.delete(through_record(record)) - end - else - records.each do |record| - through.target = nil if through.target == through_record(record) + def through_records_for(record) + attributes = construct_join_attributes(record) + candidates = Array.wrap(through_association.target) + candidates.find_all { |c| c.attributes.slice(*attributes.keys) == attributes } + end + + def delete_through_records(records) + records.each do |record| + through_records = through_records_for(record) + + if through_reflection.macro == :has_many + through_records.each { |r| through_association.target.delete(r) } + else + if through_records.include?(through_association.target) + through_association.target = nil + end end + + @through_records.delete(record.object_id) end end diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index 6c878f0f00..827b01c5ac 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -184,7 +184,7 @@ module ActiveRecord macro = join_part.reflection.macro if macro == :has_one - return if record.association_cache.key?(join_part.reflection.name) + return record.association(join_part.reflection.name).target if record.association_cache.key?(join_part.reflection.name) association = join_part.instantiate(row) unless row[join_part.aliased_primary_key].nil? set_target_and_inverse(join_part, association, record) else diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb index 03963ab060..0d7d28e458 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb @@ -95,8 +95,11 @@ module ActiveRecord conditions = self.conditions[i].dup conditions << { reflection.type => foreign_klass.base_class.name } if reflection.type - unless conditions.empty? - constraint = constraint.and(sanitize(conditions, table)) + conditions.each do |condition| + condition = active_record.send(:sanitize_sql, interpolate(condition), table.table_alias || table.name) + condition = Arel.sql(condition) unless condition.is_a?(Arel::Node) + + constraint = constraint.and(condition) end relation.from(join(table, constraint)) diff --git a/activerecord/lib/active_record/associations/join_helper.rb b/activerecord/lib/active_record/associations/join_helper.rb index f83138195c..cea6ad6944 100644 --- a/activerecord/lib/active_record/associations/join_helper.rb +++ b/activerecord/lib/active_record/associations/join_helper.rb @@ -40,16 +40,6 @@ module ActiveRecord def join(table, constraint) table.create_join(table, table.create_on(constraint), join_type) end - - def sanitize(conditions, table) - conditions = conditions.map do |condition| - condition = active_record.send(:sanitize_sql, interpolate(condition), table.table_alias || table.name) - condition = Arel.sql(condition) unless condition.is_a?(Arel::Node) - condition - end - - conditions.length == 1 ? conditions.first : Arel::Nodes::And.new(conditions) - end end end end diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 779f8164cc..253998fb23 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -95,8 +95,8 @@ module ActiveRecord def build_scope scope = klass.scoped - scope = scope.where(process_conditions(options[:conditions])) - scope = scope.where(process_conditions(preload_options[:conditions])) + scope = scope.where(interpolate(options[:conditions])) + scope = scope.where(interpolate(preload_options[:conditions])) scope = scope.select(preload_options[:select] || options[:select] || table[Arel.star]) scope = scope.includes(preload_options[:include] || options[:include]) @@ -112,13 +112,11 @@ module ActiveRecord scope end - def process_conditions(conditions) + def interpolate(conditions) if conditions.respond_to?(:to_proc) - conditions = klass.send(:instance_eval, &conditions) - end - - if conditions - klass.send(:sanitize_sql, conditions) + klass.send(:instance_eval, &conditions) + else + conditions end end end diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb index b347a94978..f95e5337c2 100644 --- a/activerecord/lib/active_record/associations/through_association.rb +++ b/activerecord/lib/active_record/associations/through_association.rb @@ -44,7 +44,7 @@ module ActiveRecord join_attributes = { source_reflection.foreign_key => records.map { |record| - record.send(source_reflection.association_primary_key) + record.send(source_reflection.association_primary_key(reflection.klass)) } } diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb new file mode 100644 index 0000000000..bf9fe70b31 --- /dev/null +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -0,0 +1,221 @@ +require 'active_support/concern' + +module ActiveRecord + module AttributeAssignment + extend ActiveSupport::Concern + include ActiveModel::MassAssignmentSecurity + + module ClassMethods + private + + # The primary key and inheritance column can never be set by mass-assignment for security reasons. + def attributes_protected_by_default + default = [ primary_key, inheritance_column ] + default << 'id' unless primary_key.eql? 'id' + default + end + end + + # Allows you to set all the attributes at once by passing in a hash with keys + # matching the attribute names (which again matches the column names). + # + # If any attributes are protected by either +attr_protected+ or + # +attr_accessible+ then only settable attributes will be assigned. + # + # class User < ActiveRecord::Base + # attr_protected :is_admin + # end + # + # user = User.new + # user.attributes = { :username => 'Phusion', :is_admin => true } + # user.username # => "Phusion" + # user.is_admin? # => false + def attributes=(new_attributes) + return unless new_attributes.is_a?(Hash) + + assign_attributes(new_attributes) + end + + # Allows you to set all the attributes for a particular mass-assignment + # security role by passing in a hash of attributes with keys matching + # the attribute names (which again matches the column names) and the role + # name using the :as option. + # + # To bypass mass-assignment security you can use the :without_protection => true + # option. + # + # class User < ActiveRecord::Base + # attr_accessible :name + # attr_accessible :name, :is_admin, :as => :admin + # end + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }) + # user.name # => "Josh" + # user.is_admin? # => false + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin) + # user.name # => "Josh" + # user.is_admin? # => true + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true) + # user.name # => "Josh" + # user.is_admin? # => true + def assign_attributes(new_attributes, options = {}) + return unless new_attributes + + attributes = new_attributes.stringify_keys + multi_parameter_attributes = [] + nested_parameter_attributes = [] + @mass_assignment_options = options + + unless options[:without_protection] + attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role) + end + + attributes.each do |k, v| + if k.include?("(") + multi_parameter_attributes << [ k, v ] + elsif respond_to?("#{k}=") + if v.is_a?(Hash) + nested_parameter_attributes << [ k, v ] + else + send("#{k}=", v) + end + else + raise(UnknownAttributeError, "unknown attribute: #{k}") + end + end + + # assign any deferred nested attributes after the base attributes have been set + nested_parameter_attributes.each do |k,v| + send("#{k}=", v) + end + + @mass_assignment_options = nil + assign_multiparameter_attributes(multi_parameter_attributes) + end + + protected + + def mass_assignment_options + @mass_assignment_options ||= {} + end + + def mass_assignment_role + mass_assignment_options[:as] || :default + end + + private + + # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done + # by calling new on the column type or aggregation type (through composed_of) object with these parameters. + # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate + # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the + # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, + # f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the + # attribute will be set to nil. + def assign_multiparameter_attributes(pairs) + execute_callstack_for_multiparameter_attributes( + extract_callstack_for_multiparameter_attributes(pairs) + ) + end + + def instantiate_time_object(name, values) + if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name)) + Time.zone.local(*values) + else + Time.time_with_datetime_fallback(self.class.default_timezone, *values) + end + end + + def execute_callstack_for_multiparameter_attributes(callstack) + errors = [] + callstack.each do |name, values_with_empty_parameters| + begin + send(name + "=", read_value_from_parameter(name, values_with_empty_parameters)) + rescue => ex + errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name}", ex, name) + end + end + unless errors.empty? + raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes" + end + end + + def read_value_from_parameter(name, values_hash_from_param) + klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass + if values_hash_from_param.values.all?{|v|v.nil?} + nil + elsif klass == Time + read_time_parameter_value(name, values_hash_from_param) + elsif klass == Date + read_date_parameter_value(name, values_hash_from_param) + else + read_other_parameter_value(klass, name, values_hash_from_param) + end + end + + def read_time_parameter_value(name, values_hash_from_param) + # If Date bits were not provided, error + raise "Missing Parameter" if [1,2,3].any?{|position| !values_hash_from_param.has_key?(position)} + max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param, 6) + # If Date bits were provided but blank, then return nil + return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} + + set_values = (1..max_position).collect{|position| values_hash_from_param[position] } + # If Time bits are not there, then default to 0 + (3..5).each {|i| set_values[i] = set_values[i].blank? ? 0 : set_values[i]} + instantiate_time_object(name, set_values) + end + + def read_date_parameter_value(name, values_hash_from_param) + return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} + set_values = [values_hash_from_param[1], values_hash_from_param[2], values_hash_from_param[3]] + begin + Date.new(*set_values) + rescue ArgumentError # if Date.new raises an exception on an invalid date + instantiate_time_object(name, set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates + end + end + + def read_other_parameter_value(klass, name, values_hash_from_param) + max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param) + values = (1..max_position).collect do |position| + raise "Missing Parameter" if !values_hash_from_param.has_key?(position) + values_hash_from_param[position] + end + klass.new(*values) + end + + def extract_max_param_for_multiparameter_attributes(values_hash_from_param, upper_cap = 100) + [values_hash_from_param.keys.max,upper_cap].min + end + + def extract_callstack_for_multiparameter_attributes(pairs) + attributes = { } + + pairs.each do |pair| + multiparameter_name, value = pair + attribute_name = multiparameter_name.split("(").first + attributes[attribute_name] = {} unless attributes.include?(attribute_name) + + parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value) + attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value + end + + attributes + end + + def type_cast_attribute_value(multiparameter_name, value) + multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value + end + + def find_parameter_position(multiparameter_name) + multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i + end + + end +end diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index d7bfaa5655..a1e34a3aa1 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -7,35 +7,59 @@ module ActiveRecord extend ActiveSupport::Concern include ActiveModel::AttributeMethods + included do + include Read + include Write + include BeforeTypeCast + include Query + include PrimaryKey + include TimeZoneConversion + include Dirty + include Serialization + + # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, + # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). + # (Alias for the protected read_attribute method). + def [](attr_name) + read_attribute(attr_name) + end + + # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. + # (Alias for the protected write_attribute method). + def []=(attr_name, value) + write_attribute(attr_name, value) + end + end + module ClassMethods # Generates all the attribute related methods for columns in the database # accessors, mutators and query methods. def define_attribute_methods - return if attribute_methods_generated? - - if base_class == self + # Use a mutex; we don't want two thread simaltaneously trying to define + # attribute methods. + @attribute_methods_mutex.synchronize do + return if attribute_methods_generated? + superclass.define_attribute_methods unless self == base_class super(column_names) @attribute_methods_generated = true - else - base_class.define_attribute_methods end end def attribute_methods_generated? - if base_class == self - @attribute_methods_generated ||= false - else - base_class.attribute_methods_generated? - end + @attribute_methods_generated ||= false end - def undefine_attribute_methods(*args) - if base_class == self - super - @attribute_methods_generated = false - else - base_class.undefine_attribute_methods(*args) - end + # We will define the methods as instance methods, but will call them as singleton + # methods. This allows us to use method_defined? to check if the method exists, + # which is fast and won't give any false positives from the ancestors (because + # there are no ancestors). + def generated_external_attribute_methods + @generated_external_attribute_methods ||= Module.new { extend self } + end + + def undefine_attribute_methods + super if attribute_methods_generated? + @attribute_methods_generated = false end def instance_method_already_implemented?(method_name) @@ -43,19 +67,46 @@ module ActiveRecord raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord" end - super + if [Base, Model].include?(active_record_super) + super + else + # If B < A and A defines its own attribute method, then we don't want to overwrite that. + defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods) + defined && !ActiveRecord::Base.method_defined?(method_name) || super + end end # A method name is 'dangerous' if it is already defined by Active Record, but # not by any ancestors. (So 'puts' is not dangerous but 'save' is.) - def dangerous_attribute_method?(method_name) - active_record = ActiveRecord::Base - superclass = ActiveRecord::Base.superclass + def dangerous_attribute_method?(name) + method_defined_within?(name, Base) + end + + def method_defined_within?(name, klass, sup = klass.superclass) + if klass.method_defined?(name) || klass.private_method_defined?(name) + if sup.method_defined?(name) || sup.private_method_defined?(name) + klass.instance_method(name).owner != sup.instance_method(name).owner + else + true + end + else + false + end + end - (active_record.method_defined?(method_name) || - active_record.private_method_defined?(method_name)) && - !superclass.method_defined?(method_name) && - !superclass.private_method_defined?(method_name) + def attribute_method?(attribute) + super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, ''))) + end + + # Returns an array of column names as strings if it's not + # an abstract class and table exists. + # Otherwise it returns an empty array. + def attribute_names + @attribute_names ||= if !abstract_class? && table_exists? + column_names + else + [] + end end end @@ -94,9 +145,105 @@ module ActiveRecord super end + # Returns true if the given attribute is in the attributes hash + def has_attribute?(attr_name) + @attributes.has_key?(attr_name.to_s) + end + + # Returns an array of names for the attributes available on this object. + def attribute_names + @attributes.keys + end + + # Returns a hash of all the attributes with their names as keys and the values of the attributes as values. + def attributes + Hash[@attributes.map { |name, _| [name, read_attribute(name)] }] + end + + # Returns an <tt>#inspect</tt>-like string for the value of the + # attribute +attr_name+. String attributes are truncated upto 50 + # characters, and Date and Time attributes are returned in the + # <tt>:db</tt> format. Other attributes return the value of + # <tt>#inspect</tt> without modification. + # + # person = Person.create!(:name => "David Heinemeier Hansson " * 3) + # + # person.attribute_for_inspect(:name) + # # => '"David Heinemeier Hansson David Heinemeier Hansson D..."' + # + # person.attribute_for_inspect(:created_at) + # # => '"2009-01-12 04:48:57"' + def attribute_for_inspect(attr_name) + value = read_attribute(attr_name) + + if value.is_a?(String) && value.length > 50 + "#{value[0..50]}...".inspect + elsif value.is_a?(Date) || value.is_a?(Time) + %("#{value.to_s(:db)}") + else + value.inspect + end + end + + # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither + # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings). + def attribute_present?(attribute) + value = read_attribute(attribute) + !value.nil? || (value.respond_to?(:empty?) && !value.empty?) + end + + # Returns the column object for the named attribute. + def column_for_attribute(name) + self.class.columns_hash[name.to_s] + end + protected - def attribute_method?(attr_name) - attr_name == 'id' || (defined?(@attributes) && @attributes.include?(attr_name)) + + def clone_attributes(reader_method = :read_attribute, attributes = {}) + attribute_names.each do |name| + attributes[name] = clone_attribute_value(reader_method, name) end + attributes + end + + def clone_attribute_value(reader_method, attribute_name) + value = send(reader_method, attribute_name) + value.duplicable? ? value.clone : value + rescue TypeError, NoMethodError + value + end + + # Returns a copy of the attributes hash where all the values have been safely quoted for use in + # an Arel insert/update method. + def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys) + attrs = {} + klass = self.class + arel_table = klass.arel_table + + attribute_names.each do |name| + if (column = column_for_attribute(name)) && (include_primary_key || !column.primary) + + if include_readonly_attributes || !self.class.readonly_attributes.include?(name) + + value = if klass.serialized_attributes.include?(name) + @attributes[name].serialized_value + else + # FIXME: we need @attributes to be used consistently. + # If the values stored in @attributes were already type + # casted, this code could be simplified + read_attribute(name) + end + + attrs[arel_table[name]] = value + end + end + end + + attrs + end + + def attribute_method?(attr_name) + attr_name == 'id' || (defined?(@attributes) && @attributes.include?(attr_name)) + end end end diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 3eff3d54e3..40e4a97e73 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -13,7 +13,7 @@ module ActiveRecord raise "You cannot include Dirty after Timestamp" end - class_attribute :partial_updates + config_attribute :partial_updates self.partial_updates = true end @@ -34,9 +34,9 @@ module ActiveRecord @previously_changed = changes @changed_attributes.clear end - rescue - IdentityMap.remove(self) if IdentityMap.enabled? - raise + rescue + IdentityMap.remove(self) if IdentityMap.enabled? + raise end # <tt>reload</tt> the record and clears changed attributes. diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index ed71b5e7d4..7c59664703 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -5,15 +5,50 @@ module ActiveRecord # Returns this record's primary key value wrapped in an Array if one is available def to_key - key = send(self.class.primary_key) + key = self.id [key] if key end + # Returns the primary key value + def id + read_attribute(self.class.primary_key) + end + + # Sets the primary key value + def id=(value) + write_attribute(self.class.primary_key, value) + end + + # Queries the primary key value + def id? + query_attribute(self.class.primary_key) + end + module ClassMethods + def define_method_attribute(attr_name) + super + + if attr_name == primary_key && attr_name != 'id' + generated_attribute_methods.send(:alias_method, :id, primary_key) + generated_external_attribute_methods.module_eval <<-CODE, __FILE__, __LINE__ + def id(v, attributes, attributes_cache, attr_name) + attr_name = '#{primary_key}' + send(attr_name, attributes[attr_name], attributes, attributes_cache, attr_name) + end + CODE + end + end + + def dangerous_attribute_method?(method_name) + super && !['id', 'id=', 'id?'].include?(method_name) + end + # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the - # primary_key_prefix_type setting, though. + # primary_key_prefix_type setting, though. Since primary keys are usually protected from mass assignment, + # remember to let your database generate them or include the key in +attr_accessible+. def primary_key - @primary_key ||= reset_primary_key + @primary_key = reset_primary_key unless defined? @primary_key + @primary_key end # Returns a quoted version of the primary key name, used to construct SQL statements. @@ -22,11 +57,11 @@ module ActiveRecord end def reset_primary_key #:nodoc: - key = self == base_class ? get_primary_key(base_class.name) : - base_class.primary_key - - set_primary_key(key) - key + if self == base_class + self.primary_key = get_primary_key(base_class.name) + else + self.primary_key = base_class.primary_key + end end def get_primary_key(base_name) #:nodoc: @@ -38,36 +73,32 @@ module ActiveRecord when :table_name_with_underscore base_name.foreign_key else - if ActiveRecord::Base != self && connection.table_exists?(table_name) - connection.primary_key(table_name) + if ActiveRecord::Base != self && table_exists? + connection.schema_cache.primary_keys[table_name] else 'id' end end end - attr_accessor :original_primary_key - - # Attribute writer for the primary key column - def primary_key=(value) - @quoted_primary_key = nil - @primary_key = value - end - - # Sets the name of the primary key column to use to the given value, - # or (if the value is nil or false) to the value returned by the given - # block. + # Sets the name of the primary key column. + # + # class Project < ActiveRecord::Base + # self.primary_key = "sysid" + # end + # + # You can also define the primary_key method yourself: # # class Project < ActiveRecord::Base - # set_primary_key "sysid" + # def self.primary_key + # "foo_" + super + # end # end - def set_primary_key(value = nil, &block) - @quoted_primary_key = nil - @primary_key ||= '' - self.original_primary_key = @primary_key - value &&= value.to_s - connection_pool.primary_keys[table_name] = value - self.primary_key = block_given? ? instance_eval(&block) : value + # Project.primary_key # => "foo_id" + def primary_key=(value) + @original_primary_key = @primary_key if defined?(@primary_key) + @primary_key = value && value.to_s + @quoted_primary_key = nil end end end diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index 4174e4da09..c129dc8c52 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -6,11 +6,8 @@ module ActiveRecord ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date] included do - cattr_accessor :attribute_types_cached_by_default, :instance_writer => false + config_attribute :attribute_types_cached_by_default, :global => true self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT - - # Undefine id so it can be used as an attribute name - undef_method(:id) if method_defined?(:id) end module ClassMethods @@ -32,107 +29,99 @@ module ActiveRecord cached_attributes.include?(attr_name) end - protected - def define_method_attribute(attr_name) - if serialized_attributes.include?(attr_name) - define_read_method_for_serialized_attribute(attr_name) - else - define_read_method(attr_name, attr_name, columns_hash[attr_name]) - end - - if attr_name == primary_key && attr_name != "id" - define_read_method('id', attr_name, columns_hash[attr_name]) - end + def undefine_attribute_methods + generated_external_attribute_methods.module_eval do + instance_methods.each { |m| undef_method(m) } end - private - def cacheable_column?(column) - serialized_attributes.include?(column.name) || attribute_types_cached_by_default.include?(column.type) - end - - # Define read method for serialized attribute. - def define_read_method_for_serialized_attribute(attr_name) - access_code = "@attributes_cache['#{attr_name}'] ||= @attributes['#{attr_name}']" - generated_attribute_methods.module_eval("def _#{attr_name}; #{access_code}; end; alias #{attr_name} _#{attr_name}", __FILE__, __LINE__) - end + super + end - # Define an attribute reader method. Cope with nil column. - # method_name is the same as attr_name except when a non-standard primary key is used, - # we still define #id as an accessor for the key - def define_read_method(method_name, attr_name, column) - cast_code = column.type_cast_code('v') - access_code = "(v=@attributes['#{attr_name}']) && #{cast_code}" + def type_cast_attribute(attr_name, attributes, cache = {}) #:nodoc: + return unless attr_name + attr_name = attr_name.to_s - unless attr_name.to_s == self.primary_key.to_s - access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ") + if generated_external_attribute_methods.method_defined?(attr_name) + if attributes.has_key?(attr_name) || attr_name == 'id' + generated_external_attribute_methods.send(attr_name, attributes[attr_name], attributes, cache, attr_name) end + elsif !attribute_methods_generated? + # If we haven't generated the caster methods yet, do that and + # then try again + define_attribute_methods + type_cast_attribute(attr_name, attributes, cache) + else + # If we get here, the attribute has no associated DB column, so + # just return it verbatim. + attributes[attr_name] + end + end - if cache_attribute?(attr_name) - access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})" + protected + # We want to generate the methods via module_eval rather than define_method, + # because define_method is slower on dispatch and uses more memory (because it + # creates a closure). + # + # But sometimes the database might return columns with characters that are not + # allowed in normal method names (like 'my_column(omg)'. So to work around this + # we first define with the __temp__ identifier, and then use alias method to + # rename it to what we want. + def define_method_attribute(attr_name) + cast_code = attribute_cast_code(attr_name) + + generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + def __temp__ + #{internal_attribute_access_code(attr_name, cast_code)} end + alias_method '#{attr_name}', :__temp__ + undef_method :__temp__ + STR - # Where possible, generate the method by evalling a string, as this will result in - # faster accesses because it avoids the block eval and then string eval incurred - # by the second branch. - # - # The second, slower, branch is necessary to support instances where the database - # returns columns with extra stuff in (like 'my_column(omg)'). - if method_name =~ ActiveModel::AttributeMethods::COMPILABLE_REGEXP - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ - def _#{method_name} - #{access_code} - end - - alias #{method_name} _#{method_name} - STR - else - generated_attribute_methods.module_eval do - define_method("_#{method_name}") { eval(access_code) } - alias_method(method_name, "_#{method_name}") - end + generated_external_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + def __temp__(v, attributes, attributes_cache, attr_name) + #{external_attribute_access_code(attr_name, cast_code)} end + alias_method '#{attr_name}', :__temp__ + undef_method :__temp__ + STR + end + + private + def cacheable_column?(column) + attribute_types_cached_by_default.include?(column.type) + end + + def internal_attribute_access_code(attr_name, cast_code) + access_code = "v = @attributes.fetch(attr_name) { missing_attribute(attr_name, caller) };" + + access_code << "v && #{cast_code};" + + if cache_attribute?(attr_name) + access_code = "@attributes_cache[attr_name] ||= (#{access_code})" end - end - # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, - # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). - def read_attribute(attr_name) - method = "_#{attr_name}" - if respond_to? method - send method if @attributes.has_key?(attr_name.to_s) - else - _read_attribute attr_name + "attr_name = '#{attr_name}'; #{access_code}" end - end - def _read_attribute(attr_name) - attr_name = attr_name.to_s - attr_name = self.class.primary_key if attr_name == 'id' - value = @attributes[attr_name] - unless value.nil? - if column = column_for_attribute(attr_name) - if unserializable_attribute?(attr_name, column) - unserialize_attribute(attr_name) - else - column.type_cast(value) - end - else - value + def external_attribute_access_code(attr_name, cast_code) + access_code = "v && #{cast_code}" + + if cache_attribute?(attr_name) + access_code = "attributes_cache[attr_name] ||= (#{access_code})" end + + access_code end - end - # Returns true if the attribute is of a text column and marked for serialization. - def unserializable_attribute?(attr_name, column) - column.text? && self.class.serialized_attributes.include?(attr_name) + def attribute_cast_code(attr_name) + columns_hash[attr_name].type_cast_code('v') + end end - # Returns the unserialized object of the attribute. - def unserialize_attribute(attr_name) - coder = self.class.serialized_attributes[attr_name] - unserialized_object = coder.load(@attributes[attr_name]) - - @attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object + # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, + # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). + def read_attribute(attr_name) + self.class.type_cast_attribute(attr_name, @attributes, @attributes_cache) end private diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb new file mode 100644 index 0000000000..0c8e4e4b9a --- /dev/null +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -0,0 +1,93 @@ +module ActiveRecord + module AttributeMethods + module Serialization + extend ActiveSupport::Concern + + included do + # Returns a hash of all the attributes that have been specified for serialization as + # keys and their class restriction as values. + config_attribute :serialized_attributes + self.serialized_attributes = {} + end + + class Attribute < Struct.new(:coder, :value, :state) + def unserialized_value + state == :serialized ? unserialize : value + end + + def serialized_value + state == :unserialized ? serialize : value + end + + def unserialize + self.state = :unserialized + self.value = coder.load(value) + end + + def serialize + self.state = :serialized + self.value = coder.dump(value) + end + end + + module ClassMethods + # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, + # then specify the name of that attribute using this method and it will be handled automatically. + # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that + # class on retrieval or SerializationTypeMismatch will be raised. + # + # ==== Parameters + # + # * +attr_name+ - The field name that should be serialized. + # * +class_name+ - Optional, class name that the object type should be equal to. + # + # ==== Example + # # Serialize a preferences attribute + # class User < ActiveRecord::Base + # serialize :preferences + # end + def serialize(attr_name, class_name = Object) + coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) } + class_name + else + Coders::YAMLColumn.new(class_name) + end + + # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy + # has its own hash of own serialized attributes + self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder) + end + + def initialize_attributes(attributes) #:nodoc: + super + + serialized_attributes.each do |key, coder| + if attributes.key?(key) + attributes[key] = Attribute.new(coder, attributes[key], :serialized) + end + end + + attributes + end + + private + + def attribute_cast_code(attr_name) + if serialized_attributes.include?(attr_name) + "v.unserialized_value" + else + super + end + end + end + + def type_cast_attribute_for_write(column, value) + if column && coder = self.class.serialized_attributes[column.name] + Attribute.new(coder, value, :unserialized) + else + super + end + end + end + end +end diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb index 62a3cfa9a5..2f86e32f41 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -7,30 +7,25 @@ module ActiveRecord extend ActiveSupport::Concern included do - cattr_accessor :time_zone_aware_attributes, :instance_writer => false + config_attribute :time_zone_aware_attributes, :global => true self.time_zone_aware_attributes = false - class_attribute :skip_time_zone_conversion_for_attributes, :instance_writer => false + config_attribute :skip_time_zone_conversion_for_attributes self.skip_time_zone_conversion_for_attributes = [] end module ClassMethods protected - # Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled. - # This enhanced read method automatically converts the UTC time stored in the database to the time + # The enhanced read method automatically converts the UTC time stored in the database to the time # zone stored in Time.zone. - def define_method_attribute(attr_name) - if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name]) - method_body, line = <<-EOV, __LINE__ + 1 - def _#{attr_name} - cached = @attributes_cache['#{attr_name}'] - return cached if cached - time = _read_attribute('#{attr_name}') - @attributes_cache['#{attr_name}'] = time.acts_like?(:time) ? time.in_time_zone : time - end - alias #{attr_name} _#{attr_name} - EOV - generated_attribute_methods.module_eval(method_body, __FILE__, line) + def attribute_cast_code(attr_name) + column = columns_hash[attr_name] + + if create_time_zone_conversion_attribute?(attr_name, column) + typecast = "v = #{super}" + time_zone_conversion = "v.acts_like?(:time) ? v.in_time_zone : v" + + "((#{typecast}) && (#{time_zone_conversion}))" else super end diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb index e9cdb130db..fde55b95da 100644 --- a/activerecord/lib/active_record/attribute_methods/write.rb +++ b/activerecord/lib/active_record/attribute_methods/write.rb @@ -10,17 +10,13 @@ module ActiveRecord module ClassMethods protected def define_method_attribute=(attr_name) - if attr_name =~ ActiveModel::AttributeMethods::COMPILABLE_REGEXP + if attr_name =~ ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__) else generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value| write_attribute(attr_name, new_value) end end - - if attr_name == primary_key && attr_name != "id" - generated_attribute_methods.module_eval("alias :id= :'#{primary_key}='") - end end end @@ -32,10 +28,8 @@ module ActiveRecord @attributes_cache.delete(attr_name) column = column_for_attribute(attr_name) - if column && column.number? - @attributes[attr_name] = convert_number_column_value(value) - elsif column || @attributes.has_key?(attr_name) - @attributes[attr_name] = value + if column || @attributes.has_key?(attr_name) + @attributes[attr_name] = type_cast_attribute_for_write(column, value) else raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'" end @@ -47,6 +41,26 @@ module ActiveRecord def attribute=(attribute_name, value) write_attribute(attribute_name, value) end + + def type_cast_attribute_for_write(column, value) + if column && column.number? + convert_number_column_value(value) + else + value + end + end + + def convert_number_column_value(value) + if value == false + 0 + elsif value == true + 1 + elsif value.is_a?(String) && value.blank? + nil + else + value + end + end end end end diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 056170d82a..d468663084 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/array/wrap' - module ActiveRecord # = Active Record Autosave Association # @@ -21,6 +19,21 @@ module ActiveRecord # Note that <tt>:autosave => false</tt> is not same as not declaring <tt>:autosave</tt>. # When the <tt>:autosave</tt> option is not present new associations are saved. # + # == Validation + # + # Children records are validated unless <tt>:validate</tt> is +false+. + # + # == Callbacks + # + # Association with autosave option defines several callbacks on your + # model (before_save, after_create, after_update). Please note that + # callbacks are executed in the order they were defined in + # model. You should avoid modyfing the association content, before + # autosave callbacks are executed. Placing your callbacks after + # associations is usually a good practice. + # + # == Examples + # # === One-to-one Example # # class Post @@ -109,10 +122,7 @@ module ActiveRecord # Now it _is_ removed from the database: # # Comment.find_by_id(id).nil? # => true - # - # === Validation - # - # Children records are validated unless <tt>:validate</tt> is +false+. + module AutosaveAssociation extend ActiveSupport::Concern @@ -264,7 +274,7 @@ module ActiveRecord # turned on for the association. def validate_single_association(reflection) association = association_instance_get(reflection.name) - record = association && association.target + record = association && association.reader association_valid?(reflection, record) if record end @@ -285,7 +295,7 @@ module ActiveRecord def association_valid?(reflection, record) return true if record.destroyed? || record.marked_for_destruction? - unless valid = record.valid? + unless valid = record.valid?(validation_context) if reflection.options[:autosave] record.errors.each do |attribute, message| attribute = "#{reflection.name}.#{attribute}" @@ -331,7 +341,7 @@ module ActiveRecord if autosave saved = association.insert_record(record, false) else - association.insert_record(record) + association.insert_record(record) unless reflection.nested? end elsif autosave saved = record.save(:validate => false) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 558b341c06..d4d0220fb7 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1,8 +1,3 @@ -begin - require 'psych' -rescue LoadError -end - require 'yaml' require 'set' require 'active_support/benchmarkable' @@ -12,7 +7,6 @@ require 'active_support/time' require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/class/attribute_accessors' require 'active_support/core_ext/class/delegating_attributes' -require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/array/extract_options' require 'active_support/core_ext/hash/deep_merge' require 'active_support/core_ext/hash/indifferent_access' @@ -23,9 +17,11 @@ require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/module/introspection' require 'active_support/core_ext/object/duplicable' require 'active_support/core_ext/object/blank' +require 'active_support/deprecation' require 'arel' require 'active_record/errors' require 'active_record/log_subscriber' +require 'active_record/explain_subscriber' module ActiveRecord #:nodoc: # = Active Record @@ -115,8 +111,8 @@ module ActiveRecord #:nodoc: # When joining tables, nested hashes or keys written in the form 'table_name.column_name' # can be used to qualify the table name of a particular condition. For instance: # - # Student.joins(:schools).where(:schools => { :type => 'public' }) - # Student.joins(:schools).where('schools.type' => 'public' ) + # Student.joins(:schools).where(:schools => { :category => 'public' }) + # Student.joins(:schools).where('schools.category' => 'public' ) # # == Overwriting default accessors # @@ -325,1838 +321,8 @@ module ActiveRecord #:nodoc: # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all # instances in the current object space. class Base - ## - # :singleton-method: - # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, - # which is then passed on to any new database connections made and which can be retrieved on both - # a class and instance level by calling +logger+. - cattr_accessor :logger, :instance_writer => false - - ## - # :singleton-method: - # Contains the database configuration - as is typically stored in config/database.yml - - # as a Hash. - # - # For example, the following database.yml... - # - # development: - # adapter: sqlite3 - # database: db/development.sqlite3 - # - # production: - # adapter: sqlite3 - # database: db/production.sqlite3 - # - # ...would result in ActiveRecord::Base.configurations to look like this: - # - # { - # 'development' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/development.sqlite3' - # }, - # 'production' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/production.sqlite3' - # } - # } - cattr_accessor :configurations, :instance_writer => false - @@configurations = {} - - ## - # :singleton-method: - # Accessor for the prefix type that will be prepended to every primary key column name. - # The options are :table_name and :table_name_with_underscore. If the first is specified, - # the Product class will look for "productid" instead of "id" as the primary column. If the - # latter is specified, the Product class will look for "product_id" instead of "id". Remember - # that this is a global setting for all Active Records. - cattr_accessor :primary_key_prefix_type, :instance_writer => false - @@primary_key_prefix_type = nil - - ## - # :singleton-method: - # Accessor for the name of the prefix string to prepend to every table name. So if set - # to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people", - # etc. This is a convenient way of creating a namespace for tables in a shared database. - # By default, the prefix is the empty string. - # - # If you are organising your models within modules you can add a prefix to the models within - # a namespace by defining a singleton method in the parent module called table_name_prefix which - # returns your chosen prefix. - class_attribute :table_name_prefix, :instance_writer => false - self.table_name_prefix = "" - - ## - # :singleton-method: - # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", - # "people_basecamp"). By default, the suffix is the empty string. - class_attribute :table_name_suffix, :instance_writer => false - self.table_name_suffix = "" - - ## - # :singleton-method: - # Indicates whether table names should be the pluralized versions of the corresponding class names. - # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. - # See table_name for the full rules on table/class naming. This is true, by default. - class_attribute :pluralize_table_names, :instance_writer => false - self.pluralize_table_names = true - - ## - # :singleton-method: - # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling - # dates and times from the database. This is set to :local by default. - cattr_accessor :default_timezone, :instance_writer => false - @@default_timezone = :local - - ## - # :singleton-method: - # Specifies the format to use when dumping the database schema with Rails' - # Rakefile. If :sql, the schema is dumped as (potentially database- - # specific) SQL statements. If :ruby, the schema is dumped as an - # ActiveRecord::Schema file which can be loaded into any database that - # supports migrations. Use :ruby if you want to have different database - # adapters for, e.g., your development and test environments. - cattr_accessor :schema_format , :instance_writer => false - @@schema_format = :ruby - - ## - # :singleton-method: - # Specify whether or not to use timestamps for migration versions - cattr_accessor :timestamped_migrations , :instance_writer => false - @@timestamped_migrations = true - - # Determine whether to store the full constant name including namespace when using STI - class_attribute :store_full_sti_class - self.store_full_sti_class = true - - # Stores the default scope for the class - class_attribute :default_scopes, :instance_writer => false - self.default_scopes = [] - - # Returns a hash of all the attributes that have been specified for serialization as - # keys and their class restriction as values. - class_attribute :serialized_attributes - self.serialized_attributes = {} - - class_attribute :_attr_readonly, :instance_writer => false - self._attr_readonly = [] - - class << self # Class methods - delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped - delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped - delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped - delegate :find_each, :find_in_batches, :to => :scoped - delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped - delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped - - # Executes a custom SQL query against your database and returns all the results. The results will - # be returned as an array with columns requested encapsulated as attributes of the model you call - # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in - # a Product object with the attributes you specified in the SQL query. - # - # If you call a complicated SQL query which spans multiple tables the columns specified by the - # SELECT will be attributes of the model, whether or not they are columns of the corresponding - # table. - # - # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be - # no database agnostic conversions performed. This should be a last resort because using, for example, - # MySQL specific terms will lock you to using that particular database engine or require you to - # change your call if you switch engines. - # - # ==== Examples - # # A simple SQL query spanning multiple tables - # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" - # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] - # - # # You can use the same string replacement techniques as you can with ActiveRecord#find - # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date] - # > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...] - def find_by_sql(sql, binds = []) - connection.select_all(sanitize_sql(sql), "#{name} Load", binds).collect! { |record| instantiate(record) } - end - - # Creates an object (or multiple objects) and saves it to the database, if validations pass. - # The resulting object is returned whether the object was saved successfully to the database or not. - # - # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the - # attributes on the objects that are to be created. - # - # +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options - # in the +options+ parameter. - # - # ==== Examples - # # Create a single new object - # User.create(:first_name => 'Jamie') - # - # # Create a single new object using the :admin mass-assignment security role - # User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) - # - # # Create a single new object bypassing mass-assignment security - # User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) - # - # # Create an Array of new objects - # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) - # - # # Create a single object and pass it into a block to set other attributes. - # User.create(:first_name => 'Jamie') do |u| - # u.is_admin = false - # end - # - # # Creating an Array of new objects using a block, where the block is executed for each object: - # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u| - # u.is_admin = false - # end - def create(attributes = nil, options = {}, &block) - if attributes.is_a?(Array) - attributes.collect { |attr| create(attr, options, &block) } - else - object = new(attributes, options, &block) - object.save - object - end - end - - # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. - # The use of this method should be restricted to complicated SQL queries that can't be executed - # using the ActiveRecord::Calculations class methods. Look into those before using this. - # - # ==== Parameters - # - # * +sql+ - An SQL statement which should return a count query from the database, see the example below. - # - # ==== Examples - # - # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id" - def count_by_sql(sql) - sql = sanitize_conditions(sql) - connection.select_value(sql, "#{name} Count").to_i - end - - # Attributes listed as readonly will be used to create a new record but update operations will - # ignore these fields. - def attr_readonly(*attributes) - self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || []) - end - - # Returns an array of all the attributes that have been specified as readonly. - def readonly_attributes - self._attr_readonly - end - - # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, - # then specify the name of that attribute using this method and it will be handled automatically. - # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that - # class on retrieval or SerializationTypeMismatch will be raised. - # - # ==== Parameters - # - # * +attr_name+ - The field name that should be serialized. - # * +class_name+ - Optional, class name that the object type should be equal to. - # - # ==== Example - # # Serialize a preferences attribute - # class User < ActiveRecord::Base - # serialize :preferences - # end - def serialize(attr_name, class_name = Object) - coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) } - class_name - else - Coders::YAMLColumn.new(class_name) - end - - # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy - # has its own hash of own serialized attributes - self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder) - end - - # Guesses the table name (in forced lower-case) based on the name of the class in the - # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy - # looks like: Reply < Message < ActiveRecord::Base, then Message is used - # to guess the table name even when called on Reply. The rules used to do the guess - # are handled by the Inflector class in Active Support, which knows almost all common - # English inflections. You can add new inflections in config/initializers/inflections.rb. - # - # Nested classes are given table names prefixed by the singular form of - # the parent's table name. Enclosing modules are not considered. - # - # ==== Examples - # - # class Invoice < ActiveRecord::Base - # end - # - # file class table_name - # invoice.rb Invoice invoices - # - # class Invoice < ActiveRecord::Base - # class Lineitem < ActiveRecord::Base - # end - # end - # - # file class table_name - # invoice.rb Invoice::Lineitem invoice_lineitems - # - # module Invoice - # class Lineitem < ActiveRecord::Base - # end - # end - # - # file class table_name - # invoice/lineitem.rb Invoice::Lineitem lineitems - # - # Additionally, the class-level +table_name_prefix+ is prepended and the - # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix, - # the table name guess for an Invoice class becomes "myapp_invoices". - # Invoice::Lineitem becomes "myapp_invoice_lineitems". - # - # You can also overwrite this class method to allow for unguessable - # links, such as a Mouse class with a link to a "mice" table. Example: - # - # class Mouse < ActiveRecord::Base - # set_table_name "mice" - # end - def table_name - reset_table_name - end - - # Returns a quoted version of the table name, used to construct SQL statements. - def quoted_table_name - @quoted_table_name ||= connection.quote_table_name(table_name) - end - - # Computes the table name, (re)sets it internally, and returns it. - def reset_table_name #:nodoc: - return if abstract_class? - - self.table_name = compute_table_name - end - - def full_table_name_prefix #:nodoc: - (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix - end - - # Defines the column name for use with single table inheritance. Use - # <tt>set_inheritance_column</tt> to set a different value. - def inheritance_column - @inheritance_column ||= "type" - end - - # Lazy-set the sequence name to the connection's default. This method - # is only ever called once since set_sequence_name overrides it. - def sequence_name #:nodoc: - reset_sequence_name - end - - def reset_sequence_name #:nodoc: - default = connection.default_sequence_name(table_name, primary_key) - set_sequence_name(default) - default - end - - # Sets the table name. If the value is nil or false then the value returned by the given - # block is used. - # - # class Project < ActiveRecord::Base - # set_table_name "project" - # end - def set_table_name(value = nil, &block) - @quoted_table_name = nil - define_attr_method :table_name, value, &block - @arel_table = nil - - @relation = Relation.new(self, arel_table) - end - alias :table_name= :set_table_name - - # Sets the name of the inheritance column to use to the given value, - # or (if the value # is nil or false) to the value returned by the - # given block. - # - # class Project < ActiveRecord::Base - # set_inheritance_column do - # original_inheritance_column + "_id" - # end - # end - def set_inheritance_column(value = nil, &block) - define_attr_method :inheritance_column, value, &block - end - alias :inheritance_column= :set_inheritance_column - - # Sets the name of the sequence to use when generating ids to the given - # value, or (if the value is nil or false) to the value returned by the - # given block. This is required for Oracle and is useful for any - # database which relies on sequences for primary key generation. - # - # If a sequence name is not explicitly set when using Oracle or Firebird, - # it will default to the commonly used pattern of: #{table_name}_seq - # - # If a sequence name is not explicitly set when using PostgreSQL, it - # will discover the sequence corresponding to your primary key for you. - # - # class Project < ActiveRecord::Base - # set_sequence_name "projectseq" # default would have been "project_seq" - # end - def set_sequence_name(value = nil, &block) - define_attr_method :sequence_name, value, &block - end - alias :sequence_name= :set_sequence_name - - # Indicates whether the table associated with this class exists - def table_exists? - connection.table_exists?(table_name) - end - - # Returns an array of column objects for the table associated with this class. - def columns - connection_pool.columns[table_name] - end - - # Returns a hash of column objects for the table associated with this class. - def columns_hash - connection_pool.columns_hash[table_name] - end - - # Returns a hash where the keys are column names and the values are - # default values when instantiating the AR object for this table. - def column_defaults - connection_pool.column_defaults[table_name] - end - - # Returns an array of column names as strings. - def column_names - @column_names ||= columns.map { |column| column.name } - end - - # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", - # and columns used for single table inheritance have been removed. - def content_columns - @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column } - end - - # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key - # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute - # is available. - def column_methods_hash #:nodoc: - @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr| - attr_name = attr.to_s - methods[attr.to_sym] = attr_name - methods["#{attr}=".to_sym] = attr_name - methods["#{attr}?".to_sym] = attr_name - methods["#{attr}_before_type_cast".to_sym] = attr_name - methods - end - end - - # Resets all the cached information about columns, which will cause them - # to be reloaded on the next request. - # - # The most common usage pattern for this method is probably in a migration, - # when just after creating a table you want to populate it with some default - # values, eg: - # - # class CreateJobLevels < ActiveRecord::Migration - # def self.up - # create_table :job_levels do |t| - # t.integer :id - # t.string :name - # - # t.timestamps - # end - # - # JobLevel.reset_column_information - # %w{assistant executive manager director}.each do |type| - # JobLevel.create(:name => type) - # end - # end - # - # def self.down - # drop_table :job_levels - # end - # end - def reset_column_information - connection.clear_cache! - undefine_attribute_methods - connection_pool.clear_table_cache!(table_name) if table_exists? - - @column_names = @content_columns = @dynamic_methods_hash = @inheritance_column = nil - @arel_engine = @relation = nil - end - - def clear_cache! # :nodoc: - connection_pool.clear_cache! - end - - def attribute_method?(attribute) - super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, ''))) - end - - # Returns an array of column names as strings if it's not - # an abstract class and table exists. - # Otherwise it returns an empty array. - def attribute_names - @attribute_names ||= if !abstract_class? && table_exists? - column_names - else - [] - end - end - - # Set the lookup ancestors for ActiveModel. - def lookup_ancestors #:nodoc: - klass = self - classes = [klass] - return classes if klass == ActiveRecord::Base - - while klass != klass.base_class - classes << klass = klass.superclass - end - classes - end - - # Set the i18n scope to overwrite ActiveModel. - def i18n_scope #:nodoc: - :activerecord - end - - # True if this isn't a concrete subclass needing a STI type condition. - def descends_from_active_record? - if superclass.abstract_class? - superclass.descends_from_active_record? - else - superclass == Base || !columns_hash.include?(inheritance_column) - end - end - - def finder_needs_type_condition? #:nodoc: - # This is like this because benchmarking justifies the strange :false stuff - :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) - end - - # Returns a string like 'Post(id:integer, title:string, body:text)' - def inspect - if self == Base - super - elsif abstract_class? - "#{super}(abstract)" - elsif table_exists? - attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', ' - "#{super}(#{attr_list})" - else - "#{super}(Table doesn't exist)" - end - end - - def quote_value(value, column = nil) #:nodoc: - connection.quote(value,column) - end - - # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>. - def sanitize(object) #:nodoc: - connection.quote(object) - end - - # Overwrite the default class equality method to provide support for association proxies. - def ===(object) - object.is_a?(self) - end - - def symbolized_base_class - @symbolized_base_class ||= base_class.to_s.to_sym - end - - def symbolized_sti_name - @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class - end - - # Returns the base AR subclass that this class descends from. If A - # extends AR::Base, A.base_class will return A. If B descends from A - # through some arbitrarily deep hierarchy, B.base_class will return A. - # - # If B < A and C < B and if A is an abstract_class then both B.base_class - # and C.base_class would return B as the answer since A is an abstract_class. - def base_class - class_of_active_record_descendant(self) - end - - # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). - attr_accessor :abstract_class - - # Returns whether this class is an abstract class or not. - def abstract_class? - defined?(@abstract_class) && @abstract_class == true - end - - def respond_to?(method_id, include_private = false) - if match = DynamicFinderMatch.match(method_id) - return true if all_attributes_exists?(match.attribute_names) - elsif match = DynamicScopeMatch.match(method_id) - return true if all_attributes_exists?(match.attribute_names) - end - - super - end - - def sti_name - store_full_sti_class ? name : name.demodulize - end - - def arel_table - @arel_table ||= Arel::Table.new(table_name, arel_engine) - end - - def arel_engine - @arel_engine ||= begin - if self == ActiveRecord::Base - ActiveRecord::Base - else - connection_handler.connection_pools[name] ? self : superclass.arel_engine - end - end - end - - # Returns a scope for this class without taking into account the default_scope. - # - # class Post < ActiveRecord::Base - # def self.default_scope - # where :published => true - # end - # end - # - # Post.all # Fires "SELECT * FROM posts WHERE published = true" - # Post.unscoped.all # Fires "SELECT * FROM posts" - # - # This method also accepts a block meaning that all queries inside the block will - # not use the default_scope: - # - # Post.unscoped { - # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10" - # } - # - # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt> - # does not work. Assuming that <tt>published</tt> is a <tt>scope</tt> following two statements are same. - # - # Post.unscoped.published - # Post.published - def unscoped #:nodoc: - block_given? ? relation.scoping { yield } : relation - end - - def before_remove_const #:nodoc: - self.current_scope = nil - end - - # Finder methods must instantiate through this method to work with the - # single-table inheritance model that makes it possible to create - # objects of different types from the same table. - def instantiate(record) - sti_class = find_sti_class(record[inheritance_column]) - record_id = sti_class.primary_key && record[sti_class.primary_key] - - if ActiveRecord::IdentityMap.enabled? && record_id - if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number? - record_id = record_id.to_i - end - if instance = IdentityMap.get(sti_class, record_id) - instance.reinit_with('attributes' => record) - else - instance = sti_class.allocate.init_with('attributes' => record) - IdentityMap.add(instance) - end - else - instance = sti_class.allocate.init_with('attributes' => record) - end - - instance - end - - private - - def relation #:nodoc: - @relation ||= Relation.new(self, arel_table) - - if finder_needs_type_condition? - @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name) - else - @relation - end - end - - def find_sti_class(type_name) - if type_name.blank? || !columns_hash.include?(inheritance_column) - self - else - begin - if store_full_sti_class - ActiveSupport::Dependencies.constantize(type_name) - else - compute_type(type_name) - end - rescue NameError - raise SubclassNotFound, - "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " + - "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + - "Please rename this column if you didn't intend it to be used for storing the inheritance class " + - "or overwrite #{name}.inheritance_column to use another column for that information." - end - end - end - - def construct_finder_arel(options = {}, scope = nil) - relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options - relation = scope.merge(relation) if scope - relation - end - - def type_condition(table = arel_table) - sti_column = table[inheritance_column.to_sym] - sti_names = ([self] + descendants).map { |model| model.sti_name } - - sti_column.in(sti_names) - end - - # Guesses the table name, but does not decorate it with prefix and suffix information. - def undecorated_table_name(class_name = base_class.name) - table_name = class_name.to_s.demodulize.underscore - table_name = table_name.pluralize if pluralize_table_names - table_name - end - - # Computes and returns a table name according to default conventions. - def compute_table_name - base = base_class - if self == base - # Nested classes are prefixed with singular parent table name. - if parent < ActiveRecord::Base && !parent.abstract_class? - contained = parent.table_name - contained = contained.singularize if parent.pluralize_table_names - contained += '_' - end - "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}" - else - # STI subclasses always use their superclass' table. - base.table_name - end - end - - # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and - # <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders - # section at the top of this file for more detailed information. - # - # It's even possible to use all the additional parameters to +find+. For example, the - # full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>. - # - # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it - # is first invoked, so that future attempts to use it do not run through method_missing. - def method_missing(method_id, *arguments, &block) - if match = (DynamicFinderMatch.match(method_id) || DynamicScopeMatch.match(method_id)) - attribute_names = match.attribute_names - super unless all_attributes_exists?(attribute_names) - if arguments.size < attribute_names.size - method_trace = "#{__FILE__}:#{__LINE__}:in `#{method_id}'" - backtrace = [method_trace] + caller - raise ArgumentError, "wrong number of arguments (#{arguments.size} for #{attribute_names.size})", backtrace - end - if match.respond_to?(:scope?) && match.scope? - self.class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args) - attributes = Hash[[:#{attribute_names.join(',:')}].zip(args)] # attributes = Hash[[:user_name, :password].zip(args)] - # - scoped(:conditions => attributes) # scoped(:conditions => attributes) - end # end - METHOD - send(method_id, *arguments) - elsif match.finder? - options = arguments.extract_options! - relation = options.any? ? scoped(options) : scoped - relation.send :find_by_attributes, match, attribute_names, *arguments, &block - elsif match.instantiator? - scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block - end - else - super - end - end - - # Similar in purpose to +expand_hash_conditions_for_aggregates+. - def expand_attribute_names_for_aggregates(attribute_names) - attribute_names.map { |attribute_name| - unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? - aggregate_mapping(aggregation).map do |field_attr, _| - field_attr.to_sym - end - else - attribute_name.to_sym - end - }.flatten - end - - def all_attributes_exists?(attribute_names) - (expand_attribute_names_for_aggregates(attribute_names) - - column_methods_hash.keys).empty? - end - - protected - # with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be - # <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while - # <tt>:create</tt> parameters are an attributes hash. - # - # class Article < ActiveRecord::Base - # def self.create_with_scope - # with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do - # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 - # a = create(1) - # a.blog_id # => 1 - # end - # end - # end - # - # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of - # <tt>where</tt>, <tt>includes</tt>, and <tt>joins</tt> operations in <tt>Relation</tt>, which are merged. - # - # <tt>joins</tt> operations are uniqued so multiple scopes can join in the same table without table aliasing - # problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the - # array of strings format for your joins. - # - # class Article < ActiveRecord::Base - # def self.find_with_scope - # with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do - # with_scope(:find => limit(10)) do - # all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10 - # end - # with_scope(:find => where(:author_id => 3)) do - # all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1 - # end - # end - # end - # end - # - # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method. - # - # class Article < ActiveRecord::Base - # def self.find_with_exclusive_scope - # with_scope(:find => where(:blog_id => 1).limit(1)) do - # with_exclusive_scope(:find => limit(10)) do - # all # => SELECT * from articles LIMIT 10 - # end - # end - # end - # end - # - # *Note*: the +:find+ scope also has effect on update and deletion methods, like +update_all+ and +delete_all+. - def with_scope(scope = {}, action = :merge, &block) - # If another Active Record class has been passed in, get its current scope - scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope) - - previous_scope = self.current_scope - - if scope.is_a?(Hash) - # Dup first and second level of hash (method and params). - scope = scope.dup - scope.each do |method, params| - scope[method] = params.dup unless params == true - end - - scope.assert_valid_keys([ :find, :create ]) - relation = construct_finder_arel(scope[:find] || {}) - relation.default_scoped = true unless action == :overwrite - - if previous_scope && previous_scope.create_with_value && scope[:create] - scope_for_create = if action == :merge - previous_scope.create_with_value.merge(scope[:create]) - else - scope[:create] - end - - relation = relation.create_with(scope_for_create) - else - scope_for_create = scope[:create] - scope_for_create ||= previous_scope.create_with_value if previous_scope - relation = relation.create_with(scope_for_create) if scope_for_create - end - - scope = relation - end - - scope = previous_scope.merge(scope) if previous_scope && action == :merge - - self.current_scope = scope - begin - yield - ensure - self.current_scope = previous_scope - end - end - - # Works like with_scope, but discards any nested properties. - def with_exclusive_scope(method_scoping = {}, &block) - if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } - raise ArgumentError, <<-MSG -New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: - - User.unscoped.where(:active => true) - -Or call unscoped with a block: - - User.unscoped do - User.where(:active => true).all - end - -MSG - end - with_scope(method_scoping, :overwrite, &block) - end - - def current_scope #:nodoc: - Thread.current["#{self}_current_scope"] - end - - def current_scope=(scope) #:nodoc: - Thread.current["#{self}_current_scope"] = scope - end - - # Use this macro in your model to set a default scope for all operations on - # the model. - # - # class Article < ActiveRecord::Base - # default_scope where(:published => true) - # end - # - # Article.all # => SELECT * FROM articles WHERE published = true - # - # The <tt>default_scope</tt> is also applied while creating/building a record. It is not - # applied while updating a record. - # - # Article.new.published # => true - # Article.create.published # => true - # - # You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated: - # - # class Article < ActiveRecord::Base - # default_scope { where(:published_at => Time.now - 1.week) } - # end - # - # (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt> - # macro, and it will be called when building the default scope.) - # - # If you use multiple <tt>default_scope</tt> declarations in your model then they will - # be merged together: - # - # class Article < ActiveRecord::Base - # default_scope where(:published => true) - # default_scope where(:rating => 'G') - # end - # - # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G' - # - # This is also the case with inheritance and module includes where the parent or module - # defines a <tt>default_scope</tt> and the child or including class defines a second one. - # - # If you need to do more complex things with a default scope, you can alternatively - # define it as a class method: - # - # class Article < ActiveRecord::Base - # def self.default_scope - # # Should return a scope, you can call 'super' here etc. - # end - # end - def default_scope(scope = {}) - scope = Proc.new if block_given? - self.default_scopes = default_scopes + [scope] - end - - def build_default_scope #:nodoc: - if method(:default_scope).owner != Base.singleton_class - evaluate_default_scope { default_scope } - elsif default_scopes.any? - evaluate_default_scope do - default_scopes.inject(relation) do |default_scope, scope| - if scope.is_a?(Hash) - default_scope.apply_finder_options(scope) - elsif !scope.is_a?(Relation) && scope.respond_to?(:call) - default_scope.merge(scope.call) - else - default_scope.merge(scope) - end - end - end - end - end - - def ignore_default_scope? #:nodoc: - Thread.current["#{self}_ignore_default_scope"] - end - - def ignore_default_scope=(ignore) #:nodoc: - Thread.current["#{self}_ignore_default_scope"] = ignore - end - - # The ignore_default_scope flag is used to prevent an infinite recursion situation where - # a default scope references a scope which has a default scope which references a scope... - def evaluate_default_scope - return if ignore_default_scope? - - begin - self.ignore_default_scope = true - yield - ensure - self.ignore_default_scope = false - end - end - - # Returns the class type of the record using the current module as a prefix. So descendants of - # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. - def compute_type(type_name) - if type_name.match(/^::/) - # If the type is prefixed with a scope operator then we assume that - # the type_name is an absolute reference. - ActiveSupport::Dependencies.constantize(type_name) - else - # Build a list of candidates to search for - candidates = [] - name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } - candidates << type_name - - candidates.each do |candidate| - begin - constant = ActiveSupport::Dependencies.constantize(candidate) - return constant if candidate == constant.to_s - rescue NameError => e - # We don't want to swallow NoMethodError < NameError errors - raise e unless e.instance_of?(NameError) - end - end - - raise NameError, "uninitialized constant #{candidates.first}" - end - end - - # Returns the class descending directly from ActiveRecord::Base or an - # abstract class, if any, in the inheritance hierarchy. - def class_of_active_record_descendant(klass) - if klass == Base || klass.superclass == Base || klass.superclass.abstract_class? - klass - elsif klass.superclass.nil? - raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" - else - class_of_active_record_descendant(klass.superclass) - end - end - - # Accepts an array, hash, or string of SQL conditions and sanitizes - # them into a valid SQL fragment for a WHERE clause. - # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" - # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'" - # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'" - def sanitize_sql_for_conditions(condition, table_name = self.table_name) - return nil if condition.blank? - - case condition - when Array; sanitize_sql_array(condition) - when Hash; sanitize_sql_hash_for_conditions(condition, table_name) - else condition - end - end - alias_method :sanitize_sql, :sanitize_sql_for_conditions - - # Accepts an array, hash, or string of SQL conditions and sanitizes - # them into a valid SQL fragment for a SET clause. - # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'" - def sanitize_sql_for_assignment(assignments) - case assignments - when Array; sanitize_sql_array(assignments) - when Hash; sanitize_sql_hash_for_assignment(assignments) - else assignments - end - end - - def aggregate_mapping(reflection) - mapping = reflection.options[:mapping] || [reflection.name, reflection.name] - mapping.first.is_a?(Array) ? mapping : [mapping] - end - - # Accepts a hash of SQL conditions and replaces those attributes - # that correspond to a +composed_of+ relationship with their expanded - # aggregate attribute values. - # Given: - # class Person < ActiveRecord::Base - # composed_of :address, :class_name => "Address", - # :mapping => [%w(address_street street), %w(address_city city)] - # end - # Then: - # { :address => Address.new("813 abc st.", "chicago") } - # # => { :address_street => "813 abc st.", :address_city => "chicago" } - def expand_hash_conditions_for_aggregates(attrs) - expanded_attrs = {} - attrs.each do |attr, value| - unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil? - mapping = aggregate_mapping(aggregation) - mapping.each do |field_attr, aggregate_attr| - if mapping.size == 1 && !value.respond_to?(aggregate_attr) - expanded_attrs[field_attr] = value - else - expanded_attrs[field_attr] = value.send(aggregate_attr) - end - end - else - expanded_attrs[attr] = value - end - end - expanded_attrs - end - - # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause. - # { :name => "foo'bar", :group_id => 4 } - # # => "name='foo''bar' and group_id= 4" - # { :status => nil, :group_id => [1,2,3] } - # # => "status IS NULL and group_id IN (1,2,3)" - # { :age => 13..18 } - # # => "age BETWEEN 13 AND 18" - # { 'other_records.id' => 7 } - # # => "`other_records`.`id` = 7" - # { :other_records => { :id => 7 } } - # # => "`other_records`.`id` = 7" - # And for value objects on a composed_of relationship: - # { :address => Address.new("123 abc st.", "chicago") } - # # => "address_street='123 abc st.' and address_city='chicago'" - def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) - attrs = expand_hash_conditions_for_aggregates(attrs) - - table = Arel::Table.new(table_name).alias(default_table_name) - PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b| - connection.visitor.accept b - }.join(' AND ') - end - alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions - - # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. - # { :status => nil, :group_id => 1 } - # # => "status = NULL , group_id = 1" - def sanitize_sql_hash_for_assignment(attrs) - attrs.map do |attr, value| - "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}" - end.join(', ') - end - - # Accepts an array of conditions. The array has each value - # sanitized and interpolated into the SQL statement. - # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" - def sanitize_sql_array(ary) - statement, *values = ary - if values.first.is_a?(Hash) && statement =~ /:\w+/ - replace_named_bind_variables(statement, values.first) - elsif statement.include?('?') - replace_bind_variables(statement, values) - elsif statement.blank? - statement - else - statement % values.collect { |value| connection.quote_string(value.to_s) } - end - end - - alias_method :sanitize_conditions, :sanitize_sql - - def replace_bind_variables(statement, values) #:nodoc: - raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size) - bound = values.dup - c = connection - statement.gsub('?') { quote_bound_value(bound.shift, c) } - end - - def replace_named_bind_variables(statement, bind_vars) #:nodoc: - statement.gsub(/(:?):([a-zA-Z]\w*)/) do - if $1 == ':' # skip postgresql casts - $& # return the whole match - elsif bind_vars.include?(match = $2.to_sym) - quote_bound_value(bind_vars[match]) - else - raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" - end - end - end - - def expand_range_bind_variables(bind_vars) #:nodoc: - expanded = [] - - bind_vars.each do |var| - next if var.is_a?(Hash) - - if var.is_a?(Range) - expanded << var.first - expanded << var.last - else - expanded << var - end - end - - expanded - end - - def quote_bound_value(value, c = connection) #:nodoc: - if value.respond_to?(:map) && !value.acts_like?(:string) - if value.respond_to?(:empty?) && value.empty? - c.quote(nil) - else - value.map { |v| c.quote(v) }.join(',') - end - else - c.quote(value) - end - end - - def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc: - unless expected == provided - raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" - end - end - - def encode_quoted_value(value) #:nodoc: - quoted_value = connection.quote(value) - quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'") # (for ruby mode) " - quoted_value - end - end - - public - # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with - # attributes but not yet saved (pass a hash with key names matching the associated table column names). - # In both instances, valid attribute keys are determined by the column names of the associated table -- - # hence you can't have attributes that aren't part of the table columns. - # - # +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options - # in the +options+ parameter. - # - # ==== Examples - # # Instantiates a single new object - # User.new(:first_name => 'Jamie') - # - # # Instantiates a single new object using the :admin mass-assignment security role - # User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) - # - # # Instantiates a single new object bypassing mass-assignment security - # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) - def initialize(attributes = nil, options = {}) - @attributes = attributes_from_column_definition - @association_cache = {} - @aggregation_cache = {} - @attributes_cache = {} - @new_record = true - @readonly = false - @destroyed = false - @marked_for_destruction = false - @previously_changed = {} - @changed_attributes = {} - @relation = nil - - ensure_proper_type - set_serialized_attributes - - populate_with_current_scope_attributes - - assign_attributes(attributes, options) if attributes - - yield self if block_given? - run_callbacks :initialize - end - - # Populate +coder+ with attributes about this record that should be - # serialized. The structure of +coder+ defined in this method is - # guaranteed to match the structure of +coder+ passed to the +init_with+ - # method. - # - # Example: - # - # class Post < ActiveRecord::Base - # end - # coder = {} - # Post.new.encode_with(coder) - # coder # => { 'id' => nil, ... } - def encode_with(coder) - coder['attributes'] = attributes - end - - # Initialize an empty model object from +coder+. +coder+ must contain - # the attributes necessary for initializing an empty model object. For - # example: - # - # class Post < ActiveRecord::Base - # end - # - # post = Post.allocate - # post.init_with('attributes' => { 'title' => 'hello world' }) - # post.title # => 'hello world' - def init_with(coder) - @attributes = coder['attributes'] - @relation = nil - - set_serialized_attributes - - @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {} - @association_cache = {} - @aggregation_cache = {} - @readonly = @destroyed = @marked_for_destruction = false - @new_record = false - run_callbacks :find - run_callbacks :initialize - - self - end - - # Returns a String, which Action Pack uses for constructing an URL to this - # object. The default implementation returns this record's id as a String, - # or nil if this record's unsaved. - # - # For example, suppose that you have a User model, and that you have a - # <tt>resources :users</tt> route. Normally, +user_path+ will - # construct a path with the user object's 'id' in it: - # - # user = User.find_by_name('Phusion') - # user_path(user) # => "/users/1" - # - # You can override +to_param+ in your model to make +user_path+ construct - # a path using the user's name instead of the user's id: - # - # class User < ActiveRecord::Base - # def to_param # overridden - # name - # end - # end - # - # user = User.find_by_name('Phusion') - # user_path(user) # => "/users/Phusion" - def to_param - # We can't use alias_method here, because method 'id' optimizes itself on the fly. - id && id.to_s # Be sure to stringify the id for routes - end - - # Returns a cache key that can be used to identify this record. - # - # ==== Examples - # - # Product.new.cache_key # => "products/new" - # Product.find(5).cache_key # => "products/5" (updated_at not available) - # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available) - def cache_key - case - when new_record? - "#{self.class.model_name.cache_key}/new" - when timestamp = self[:updated_at] - timestamp = timestamp.utc.to_s(:number) - "#{self.class.model_name.cache_key}/#{id}-#{timestamp}" - else - "#{self.class.model_name.cache_key}/#{id}" - end - end - - def quoted_id #:nodoc: - quote_value(id, column_for_attribute(self.class.primary_key)) - end - - # Returns true if the given attribute is in the attributes hash - def has_attribute?(attr_name) - @attributes.has_key?(attr_name.to_s) - end - - # Returns an array of names for the attributes available on this object. - def attribute_names - @attributes.keys - end - - # Allows you to set all the attributes at once by passing in a hash with keys - # matching the attribute names (which again matches the column names). - # - # If any attributes are protected by either +attr_protected+ or - # +attr_accessible+ then only settable attributes will be assigned. - # - # class User < ActiveRecord::Base - # attr_protected :is_admin - # end - # - # user = User.new - # user.attributes = { :username => 'Phusion', :is_admin => true } - # user.username # => "Phusion" - # user.is_admin? # => false - def attributes=(new_attributes) - return unless new_attributes.is_a?(Hash) - - assign_attributes(new_attributes) - end - - # Allows you to set all the attributes for a particular mass-assignment - # security role by passing in a hash of attributes with keys matching - # the attribute names (which again matches the column names) and the role - # name using the :as option. - # - # To bypass mass-assignment security you can use the :without_protection => true - # option. - # - # class User < ActiveRecord::Base - # attr_accessible :name - # attr_accessible :name, :is_admin, :as => :admin - # end - # - # user = User.new - # user.assign_attributes({ :name => 'Josh', :is_admin => true }) - # user.name # => "Josh" - # user.is_admin? # => false - # - # user = User.new - # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin) - # user.name # => "Josh" - # user.is_admin? # => true - # - # user = User.new - # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true) - # user.name # => "Josh" - # user.is_admin? # => true - def assign_attributes(new_attributes, options = {}) - return unless new_attributes - - attributes = new_attributes.stringify_keys - multi_parameter_attributes = [] - @mass_assignment_options = options - - unless options[:without_protection] - attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role) - end - - attributes.each do |k, v| - if k.include?("(") - multi_parameter_attributes << [ k, v ] - elsif respond_to?("#{k}=") - send("#{k}=", v) - else - raise(UnknownAttributeError, "unknown attribute: #{k}") - end - end - - @mass_assignment_options = nil - assign_multiparameter_attributes(multi_parameter_attributes) - end - - # Returns a hash of all the attributes with their names as keys and the values of the attributes as values. - def attributes - Hash[@attributes.map { |name, _| [name, read_attribute(name)] }] - end - - # Returns an <tt>#inspect</tt>-like string for the value of the - # attribute +attr_name+. String attributes are truncated upto 50 - # characters, and Date and Time attributes are returned in the - # <tt>:db</tt> format. Other attributes return the value of - # <tt>#inspect</tt> without modification. - # - # person = Person.create!(:name => "David Heinemeier Hansson " * 3) - # - # person.attribute_for_inspect(:name) - # # => '"David Heinemeier Hansson David Heinemeier Hansson D..."' - # - # person.attribute_for_inspect(:created_at) - # # => '"2009-01-12 04:48:57"' - def attribute_for_inspect(attr_name) - value = read_attribute(attr_name) - - if value.is_a?(String) && value.length > 50 - "#{value[0..50]}...".inspect - elsif value.is_a?(Date) || value.is_a?(Time) - %("#{value.to_s(:db)}") - else - value.inspect - end - end - - # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither - # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings). - def attribute_present?(attribute) - !_read_attribute(attribute).blank? - end - - # Returns the column object for the named attribute. - def column_for_attribute(name) - self.class.columns_hash[name.to_s] - end - - # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ - # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+. - # - # Note that new records are different from any other record by definition, unless the - # other record is the receiver itself. Besides, if you fetch existing records with - # +select+ and leave the ID out, you're on your own, this predicate will return false. - # - # Note also that destroying a record preserves its ID in the model instance, so deleted - # models are still comparable. - def ==(comparison_object) - super || - comparison_object.instance_of?(self.class) && - id.present? && - comparison_object.id == id - end - alias :eql? :== - - # Delegates to id in order to allow two records of the same type and id to work with something like: - # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] - def hash - id.hash - end - - # Freeze the attributes hash such that associations are still accessible, even on destroyed records. - def freeze - @attributes.freeze; self - end - - # Returns +true+ if the attributes hash has been frozen. - def frozen? - @attributes.frozen? - end - - # Allows sort on objects - def <=>(other_object) - if other_object.is_a?(self.class) - self.to_key <=> other_object.to_key - else - nil - end - end - - # Backport dup from 1.9 so that initialize_dup() gets called - unless Object.respond_to?(:initialize_dup) - def dup # :nodoc: - copy = super - copy.initialize_dup(self) - copy - end - end - - # Duped objects have no id assigned and are treated as new records. Note - # that this is a "shallow" copy as it copies the object's attributes - # only, not its associations. The extent of a "deep" copy is application - # specific and is therefore left to the application to implement according - # to its need. - # The dup method does not preserve the timestamps (created|updated)_(at|on). - def initialize_dup(other) - cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast) - cloned_attributes.delete(self.class.primary_key) - - @attributes = cloned_attributes - - _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks) - - @changed_attributes = {} - attributes_from_column_definition.each do |attr, orig_value| - @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr]) - end - - @aggregation_cache = {} - @association_cache = {} - @attributes_cache = {} - @new_record = true - - ensure_proper_type - populate_with_current_scope_attributes - super - end - - # Returns +true+ if the record is read only. Records loaded through joins with piggy-back - # attributes will be marked as read only since they cannot be saved. - def readonly? - @readonly - end - - # Marks this record as read only. - def readonly! - @readonly = true - end - - # Returns the contents of the record as a nicely formatted string. - def inspect - inspection = if @attributes - self.class.column_names.collect { |name| - if has_attribute?(name) - "#{name}: #{attribute_for_inspect(name)}" - end - }.compact.join(", ") - else - "not initialized" - end - "#<#{self.class} #{inspection}>" - end - - protected - def clone_attributes(reader_method = :read_attribute, attributes = {}) - attribute_names.each do |name| - attributes[name] = clone_attribute_value(reader_method, name) - end - attributes - end - - def clone_attribute_value(reader_method, attribute_name) - value = send(reader_method, attribute_name) - value.duplicable? ? value.clone : value - rescue TypeError, NoMethodError - value - end - - def mass_assignment_options - @mass_assignment_options ||= {} - end - - def mass_assignment_role - mass_assignment_options[:as] || :default - end - - private - - # 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, - # which significantly impacts upon performance. - # - # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here. - # - # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/ - def to_ary # :nodoc: - nil - end - - def set_serialized_attributes - sattrs = self.class.serialized_attributes - - sattrs.each do |key, coder| - @attributes[key] = coder.load @attributes[key] if @attributes.key?(key) - end - end - - # Sets the attribute used for single table inheritance to this class name if this is not the - # ActiveRecord::Base descendant. - # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to - # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. - # No such attribute would be set for objects of the Message class in that example. - def ensure_proper_type - klass = self.class - if klass.finder_needs_type_condition? - write_attribute(klass.inheritance_column, klass.sti_name) - end - end - - # The primary key and inheritance column can never be set by mass-assignment for security reasons. - def self.attributes_protected_by_default - default = [ primary_key, inheritance_column ] - default << 'id' unless primary_key.eql? 'id' - default - end - - # Returns a copy of the attributes hash where all the values have been safely quoted for use in - # an Arel insert/update method. - def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys) - attrs = {} - klass = self.class - arel_table = klass.arel_table - - attribute_names.each do |name| - if (column = column_for_attribute(name)) && (include_primary_key || !column.primary) - - if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name)) - - value = if coder = klass.serialized_attributes[name] - coder.dump @attributes[name] - else - # FIXME: we need @attributes to be used consistently. - # If the values stored in @attributes were already type - # casted, this code could be simplified - read_attribute(name) - end - - attrs[arel_table[name]] = value - end - end - end - attrs - end - - # Quote strings appropriately for SQL statements. - def quote_value(value, column = nil) - self.class.connection.quote(value, column) - end - - # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done - # by calling new on the column type or aggregation type (through composed_of) object with these parameters. - # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate - # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the - # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, - # f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the - # attribute will be set to nil. - def assign_multiparameter_attributes(pairs) - execute_callstack_for_multiparameter_attributes( - extract_callstack_for_multiparameter_attributes(pairs) - ) - end - - def instantiate_time_object(name, values) - if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name)) - Time.zone.local(*values) - else - Time.time_with_datetime_fallback(@@default_timezone, *values) - end - end - - def execute_callstack_for_multiparameter_attributes(callstack) - errors = [] - callstack.each do |name, values_with_empty_parameters| - begin - send(name + "=", read_value_from_parameter(name, values_with_empty_parameters)) - rescue => ex - errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name}", ex, name) - end - end - unless errors.empty? - raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes" - end - end - - def read_value_from_parameter(name, values_hash_from_param) - klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass - if values_hash_from_param.values.all?{|v|v.nil?} - nil - elsif klass == Time - read_time_parameter_value(name, values_hash_from_param) - elsif klass == Date - read_date_parameter_value(name, values_hash_from_param) - else - read_other_parameter_value(klass, name, values_hash_from_param) - end - end - - def read_time_parameter_value(name, values_hash_from_param) - # If Date bits were not provided, error - raise "Missing Parameter" if [1,2,3].any?{|position| !values_hash_from_param.has_key?(position)} - max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param, 6) - # If Date bits were provided but blank, then return nil - return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} - - set_values = (1..max_position).collect{|position| values_hash_from_param[position] } - # If Time bits are not there, then default to 0 - (3..5).each {|i| set_values[i] = set_values[i].blank? ? 0 : set_values[i]} - instantiate_time_object(name, set_values) - end - - def read_date_parameter_value(name, values_hash_from_param) - return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} - set_values = [values_hash_from_param[1], values_hash_from_param[2], values_hash_from_param[3]] - begin - Date.new(*set_values) - rescue ArgumentError # if Date.new raises an exception on an invalid date - instantiate_time_object(name, set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates - end - end - - def read_other_parameter_value(klass, name, values_hash_from_param) - max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param) - values = (1..max_position).collect do |position| - raise "Missing Parameter" if !values_hash_from_param.has_key?(position) - values_hash_from_param[position] - end - klass.new(*values) - end - - def extract_max_param_for_multiparameter_attributes(values_hash_from_param, upper_cap = 100) - [values_hash_from_param.keys.max,upper_cap].min - end - - def extract_callstack_for_multiparameter_attributes(pairs) - attributes = { } - - pairs.each do |pair| - multiparameter_name, value = pair - attribute_name = multiparameter_name.split("(").first - attributes[attribute_name] = {} unless attributes.include?(attribute_name) - - parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value) - attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value - end - - attributes - end - - def type_cast_attribute_value(multiparameter_name, value) - multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value - end - - def find_parameter_position(multiparameter_name) - multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i - end - - # Returns a comma-separated pair list, like "key1 = val1, key2 = val2". - def comma_pair_list(hash) - hash.map { |k,v| "#{k} = #{v}" }.join(", ") - end - - def quote_columns(quoter, hash) - Hash[hash.map { |name, value| [quoter.quote_column_name(name), value] }] - end - - def quoted_comma_pair_list(quoter, hash) - comma_pair_list(quote_columns(quoter, hash)) - end - - def convert_number_column_value(value) - if value == false - 0 - elsif value == true - 1 - elsif value.is_a?(String) && value.blank? - nil - else - value - end - end - - def populate_with_current_scope_attributes - return unless self.class.scope_attributes? - - self.class.scope_attributes.each do |att,value| - send("#{att}=", value) if respond_to?("#{att}=") - end - end - end - - Base.class_eval do - include ActiveRecord::Persistence - extend ActiveModel::Naming - extend QueryCache::ClassMethods - extend ActiveSupport::Benchmarkable - extend ActiveSupport::DescendantsTracker - - include ActiveModel::Conversion - include Validations - extend CounterCache - include Locking::Optimistic, Locking::Pessimistic - include AttributeMethods - include AttributeMethods::Read, AttributeMethods::Write, AttributeMethods::BeforeTypeCast, AttributeMethods::Query - include AttributeMethods::PrimaryKey - include AttributeMethods::TimeZoneConversion - include AttributeMethods::Dirty - include ActiveModel::MassAssignmentSecurity - include Callbacks, ActiveModel::Observing, Timestamp - include Associations, NamedScope - include IdentityMap - include ActiveModel::SecurePassword - - # AutosaveAssociation needs to be included before Transactions, because we want - # #save_with_autosave_associations to be wrapped inside a transaction. - include AutosaveAssociation, NestedAttributes - include Aggregations, Transactions, Reflection, Serialization - - NilClass.add_whiner(self) if NilClass.respond_to?(:add_whiner) - - # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, - # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). - # (Alias for the protected read_attribute method). - alias [] read_attribute - - # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. - # (Alias for the protected write_attribute method). - alias []= write_attribute - - public :[], :[]= + include ActiveRecord::Model end end -require 'active_record/connection_adapters/abstract/connection_specification' -ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) +ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Model::DeprecationProxy) diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index a175bf003c..a050fabf35 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/array/wrap' - module ActiveRecord # = Active Record Callbacks # @@ -25,7 +23,7 @@ module ActiveRecord # Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and # <tt>after_rollback</tt>. # - # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that + # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that # is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects # are instantiated as well. # @@ -215,24 +213,48 @@ module ActiveRecord # instead of quietly returning +false+. # # == Debugging callbacks - # - # The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support + # + # The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support # <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property # defines what part of the chain the callback runs in. - # - # To find all callbacks in the before_save callback chain: - # + # + # To find all callbacks in the before_save callback chain: + # # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) } - # + # # Returns an array of callback objects that form the before_save chain. - # + # # To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object: - # + # # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead) - # + # # Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model. - # + # module Callbacks + # We can't define callbacks directly on ActiveRecord::Model because + # it is a module. So we queue up the definitions and execute them + # when ActiveRecord::Model is included. + module Register #:nodoc: + def self.extended(base) + base.config_attribute :_callbacks_register + base._callbacks_register = [] + end + + def self.setup(base) + base._callbacks_register.each do |item| + base.send(*item) + end + end + + def define_callbacks(*args) + self._callbacks_register << [:define_callbacks, *args] + end + + def define_model_callbacks(*args) + self._callbacks_register << [:define_model_callbacks, *args] + end + end + extend ActiveSupport::Concern CALLBACKS = [ @@ -242,8 +264,11 @@ module ActiveRecord :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback ] + module ClassMethods + include ActiveModel::Callbacks + end + included do - extend ActiveModel::Callbacks include ActiveModel::Validations::Callbacks define_model_callbacks :initialize, :find, :touch, :only => :after diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb index fb59d9fb07..77af540c3e 100644 --- a/activerecord/lib/active_record/coders/yaml_column.rb +++ b/activerecord/lib/active_record/coders/yaml_column.rb @@ -15,7 +15,7 @@ module ActiveRecord end def dump(obj) - YAML.dump obj + YAML.dump(obj) unless obj.nil? end def load(yaml) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 20863e73aa..d69f02d504 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -1,7 +1,7 @@ require 'thread' require 'monitor' require 'set' -require 'active_support/core_ext/module/synchronization' +require 'active_support/core_ext/module/deprecation' module ActiveRecord # Raised when a connection could not be obtained within the connection @@ -9,6 +9,13 @@ module ActiveRecord class ConnectionTimeoutError < ConnectionNotEstablished end + # Raised when a connection pool is full and another connection is requested + class PoolFullError < ConnectionNotEstablished + def initialize size, timeout + super("Connection pool of size #{size} and timeout #{timeout}s is full") + end + end + module ConnectionAdapters # Connection pool base class for managing Active Record database # connections. @@ -57,10 +64,35 @@ module ActiveRecord # * +wait_timeout+: number of seconds to block and wait for a connection # before giving up and raising a timeout error (default 5 seconds). class ConnectionPool - attr_accessor :automatic_reconnect - attr_reader :spec, :connections - attr_reader :columns, :columns_hash, :primary_keys, :tables - attr_reader :column_defaults + # Every +frequency+ seconds, the reaper will call +reap+ on +pool+. + # A reaper instantiated with a nil frequency will never reap the + # connection pool. + # + # Configure the frequency by setting "reaping_frequency" in your + # database yaml file. + class Reaper + attr_reader :pool, :frequency + + def initialize(pool, frequency) + @pool = pool + @frequency = frequency + end + + def run + return unless frequency + Thread.new(frequency, pool) { |t, p| + while true + sleep t + p.reap + end + } + end + end + + include MonitorMixin + + attr_accessor :automatic_reconnect, :timeout + attr_reader :spec, :connections, :size, :reaper # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification # object which describes database connection information (e.g. adapter, @@ -69,88 +101,22 @@ module ActiveRecord # # The default ConnectionPool maximum size is 5. def initialize(spec) + super() + @spec = spec # The cache of reserved connections mapped to threads @reserved_connections = {} - # The mutex used to synchronize pool access - @connection_mutex = Monitor.new - @queue = @connection_mutex.new_cond @timeout = spec.config[:wait_timeout] || 5 + @reaper = Reaper.new self, spec.config[:reaping_frequency] + @reaper.run # default max pool size to 5 @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5 @connections = [] - @checked_out = [] @automatic_reconnect = true - @tables = {} - @visitor = nil - - @columns = Hash.new do |h, table_name| - h[table_name] = with_connection do |conn| - - # Fetch a list of columns - conn.columns(table_name, "#{table_name} Columns").tap do |columns| - - # set primary key information - columns.each do |column| - column.primary = column.name == primary_keys[table_name] - end - end - end - end - - @columns_hash = Hash.new do |h, table_name| - h[table_name] = Hash[columns[table_name].map { |col| - [col.name, col] - }] - end - - @column_defaults = Hash.new do |h, table_name| - h[table_name] = Hash[columns[table_name].map { |col| - [col.name, col.default] - }] - end - - @primary_keys = Hash.new do |h, table_name| - h[table_name] = with_connection do |conn| - table_exists?(table_name) ? conn.primary_key(table_name) : 'id' - end - end - end - - # A cached lookup for table existence. - def table_exists?(name) - return true if @tables.key? name - - with_connection do |conn| - conn.tables.each { |table| @tables[table] = true } - @tables[name] = true if !@tables.key?(name) && conn.table_exists?(name) - end - - @tables.key? name - end - - # Clears out internal caches: - # - # * columns - # * columns_hash - # * tables - def clear_cache! - @columns.clear - @columns_hash.clear - @column_defaults.clear - @tables.clear - end - - # Clear out internal caches for table with +table_name+. - def clear_table_cache!(table_name) - @columns.delete table_name - @columns_hash.delete table_name - @column_defaults.delete table_name - @primary_keys.delete table_name end # Retrieve the connection associated with the current thread, or call @@ -165,7 +131,7 @@ module ActiveRecord # Check to see if there is an active connection in this connection # pool. def active_connection? - @reserved_connections.key? current_connection_id + active_connections.any? end # Signal that the thread is finished with the current connection. @@ -181,7 +147,7 @@ module ActiveRecord # connection when finished. def with_connection connection_id = current_connection_id - fresh_connection = true unless @reserved_connections[connection_id] + fresh_connection = true unless active_connection? yield connection ensure release_connection(connection_id) if fresh_connection @@ -189,94 +155,80 @@ module ActiveRecord # Returns true if a connection has already been opened. def connected? - !@connections.empty? + synchronize { @connections.any? } end # Disconnects all connections in the pool, and clears the pool. def disconnect! - @reserved_connections.each do |name,conn| - checkin conn - end - @reserved_connections = {} - @connections.each do |conn| - conn.disconnect! + synchronize do + @reserved_connections = {} + @connections.each do |conn| + checkin conn + conn.disconnect! + end + @connections = [] end - @connections = [] end # Clears the cache which maps classes. def clear_reloadable_connections! - @reserved_connections.each do |name, conn| - checkin conn - end - @reserved_connections = {} - @connections.each do |conn| - conn.disconnect! if conn.requires_reloading? - end - @connections.delete_if do |conn| - conn.requires_reloading? + synchronize do + @reserved_connections = {} + @connections.each do |conn| + checkin conn + conn.disconnect! if conn.requires_reloading? + end + @connections.delete_if do |conn| + conn.requires_reloading? + end end end # Verify active connections and remove and disconnect connections # associated with stale threads. def verify_active_connections! #:nodoc: - clear_stale_cached_connections! - @connections.each do |connection| - connection.verify! + synchronize do + @connections.each do |connection| + connection.verify! + end end end - # Return any checked-out connections back to the pool by threads that - # are no longer alive. - def clear_stale_cached_connections! - keys = @reserved_connections.keys - Thread.list.find_all { |t| - t.alive? - }.map { |thread| thread.object_id } - keys.each do |key| - checkin @reserved_connections[key] - @reserved_connections.delete(key) - end + def clear_stale_cached_connections! # :nodoc: end + deprecate :clear_stale_cached_connections! # Check-out a database connection from the pool, indicating that you want # to use it. You should call #checkin when you no longer need this. # - # This is done by either returning an existing connection, or by creating - # a new connection. If the maximum number of connections for this pool has - # already been reached, but the pool is empty (i.e. they're all being used), - # then this method will wait until a thread has checked in a connection. - # The wait time is bounded however: if no connection can be checked out - # within the timeout specified for this pool, then a ConnectionTimeoutError - # exception will be raised. + # This is done by either returning and leasing existing connection, or by + # creating a new connection and leasing it. + # + # If all connections are leased and the pool is at capacity (meaning the + # number of currently leased connections is greater than or equal to the + # size limit set), an ActiveRecord::PoolFullError exception will be raised. # # Returns: an AbstractAdapter object. # # Raises: - # - ConnectionTimeoutError: no connection can be obtained from the pool - # within the timeout period. + # - PoolFullError: no connection can be obtained from the pool. def checkout # Checkout an available connection - @connection_mutex.synchronize do - loop do - conn = if @checked_out.size < @connections.size - checkout_existing_connection - elsif @connections.size < @size - checkout_new_connection - end - return conn if conn - - @queue.wait(@timeout) - - if(@checked_out.size < @connections.size) - next - else - clear_stale_cached_connections! - if @size == @checked_out.size - raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it." - end - end + synchronize do + # Try to find a connection that hasn't been leased, and lease it + conn = connections.find { |c| c.lease } + + # If all connections were leased, and we have room to expand, + # create a new connection and lease it. + if !conn && connections.size < size + conn = checkout_new_connection + conn.lease + end + if conn + checkout_and_verify conn + else + raise PoolFullError.new(size, timeout) end end end @@ -287,56 +239,69 @@ module ActiveRecord # +conn+: an AbstractAdapter object, which was obtained by earlier by # calling +checkout+ on this pool. def checkin(conn) - @connection_mutex.synchronize do + synchronize do conn.run_callbacks :checkin do - @checked_out.delete conn - @queue.signal + conn.expire end end end - synchronize :clear_reloadable_connections!, :verify_active_connections!, - :connected?, :disconnect!, :with => :@connection_mutex + # Remove a connection from the connection pool. The connection will + # remain open and active but will no longer be managed by this pool. + def remove(conn) + synchronize do + @connections.delete conn - private + # FIXME: we might want to store the key on the connection so that removing + # from the reserved hash will be a little easier. + thread_id = @reserved_connections.keys.find { |k| + @reserved_connections[k] == conn + } + @reserved_connections.delete thread_id if thread_id + end + end - def new_connection - connection = ActiveRecord::Base.send(spec.adapter_method, spec.config) + # Removes dead connections from the pool. A dead connection can occur + # if a programmer forgets to close a connection at the end of a thread + # or a thread dies unexpectedly. + def reap + synchronize do + stale = Time.now - @timeout + connections.dup.each do |conn| + remove conn if conn.in_use? && stale > conn.last_use && !conn.active? + end + end + end - # TODO: This is a bit icky, and in the long term we may want to change the method - # signature for connections. Also, if we switch to have one visitor per - # connection (and therefore per thread), we can get rid of the thread-local - # variable in Arel::Visitors::ToSql. - @visitor ||= connection.class.visitor_for(self) - connection.visitor = @visitor + private - connection + def new_connection + ActiveRecord::Base.send(spec.adapter_method, spec.config) end def current_connection_id #:nodoc: - Thread.current.object_id + ActiveRecord::Base.connection_id ||= Thread.current.object_id end def checkout_new_connection raise ConnectionNotEstablished unless @automatic_reconnect c = new_connection + c.pool = self @connections << c - checkout_and_verify(c) - end - - def checkout_existing_connection - c = (@connections - @checked_out).first - checkout_and_verify(c) + c end def checkout_and_verify(c) c.run_callbacks :checkout do c.verify! - @checked_out << c end c end + + def active_connections + @connections.find_all { |c| c.in_use? } + end end # ConnectionHandler is a collection of ConnectionPool objects. It is used @@ -367,10 +332,12 @@ module ActiveRecord def initialize(pools = {}) @connection_pools = pools + @class_to_pool = {} end def establish_connection(name, spec) - @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec) + @connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec) + @class_to_pool[name] = @connection_pools[spec] end # Returns true if there are any active connections among the connection @@ -421,52 +388,24 @@ module ActiveRecord # can be used as an argument for establish_connection, for easily # re-establishing the connection. def remove_connection(klass) - pool = @connection_pools.delete(klass.name) + pool = @class_to_pool.delete(klass.name) return nil unless pool + @connection_pools.delete pool.spec pool.automatic_reconnect = false pool.disconnect! pool.spec.config end def retrieve_connection_pool(klass) - pool = @connection_pools[klass.name] + pool = @class_to_pool[klass.name] return pool if pool - return nil if ActiveRecord::Base == klass - retrieve_connection_pool klass.superclass + return nil if ActiveRecord::Model == klass + retrieve_connection_pool klass.active_record_super end end class ConnectionManagement - class Proxy # :nodoc: - attr_reader :body, :testing - - def initialize(body, testing = false) - @body = body - @testing = testing - end - - def method_missing(method_sym, *arguments, &block) - @body.send(method_sym, *arguments, &block) - end - - def respond_to?(method_sym, include_private = false) - super || @body.respond_to?(method_sym) - end - - def each(&block) - body.each(&block) - end - - def close - body.close if body.respond_to?(:close) - - # Don't return connection (and perform implicit rollback) if - # this request is a part of integration test - ActiveRecord::Base.clear_active_connections! unless testing - end - end - def initialize(app) @app = app end @@ -474,9 +413,12 @@ module ActiveRecord def call(env) testing = env.key?('rack.test') - status, headers, body = @app.call(env) + response = @app.call(env) + response[2] = ::Rack::BodyProxy.new(response[2]) do + ActiveRecord::Base.clear_active_connections! unless testing + end - [status, headers, Proxy.new(body, testing)] + response rescue ActiveRecord::Base.clear_active_connections! unless testing raise diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb deleted file mode 100644 index c08c0263b9..0000000000 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +++ /dev/null @@ -1,153 +0,0 @@ -module ActiveRecord - class Base - class ConnectionSpecification #:nodoc: - attr_reader :config, :adapter_method - def initialize (config, adapter_method) - @config, @adapter_method = config, adapter_method - end - end - - ## - # :singleton-method: - # The connection handler - class_attribute :connection_handler, :instance_writer => false - self.connection_handler = ConnectionAdapters::ConnectionHandler.new - - # Returns the connection currently associated with the class. This can - # also be used to "borrow" the connection to do database work that isn't - # easily done without going straight to SQL. - def connection - self.class.connection - end - - # Establishes the connection to the database. Accepts a hash as input where - # the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case) - # example for regular databases (MySQL, Postgresql, etc): - # - # ActiveRecord::Base.establish_connection( - # :adapter => "mysql", - # :host => "localhost", - # :username => "myuser", - # :password => "mypass", - # :database => "somedatabase" - # ) - # - # Example for SQLite database: - # - # ActiveRecord::Base.establish_connection( - # :adapter => "sqlite", - # :database => "path/to/dbfile" - # ) - # - # Also accepts keys as strings (for parsing from YAML for example): - # - # ActiveRecord::Base.establish_connection( - # "adapter" => "sqlite", - # "database" => "path/to/dbfile" - # ) - # - # Or a URL: - # - # ActiveRecord::Base.establish_connection( - # "postgres://myuser:mypass@localhost/somedatabase" - # ) - # - # The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError - # may be returned on an error. - def self.establish_connection(spec = ENV["DATABASE_URL"]) - case spec - when nil - raise AdapterNotSpecified unless defined?(Rails.env) - establish_connection(Rails.env) - when ConnectionSpecification - self.connection_handler.establish_connection(name, spec) - when Symbol, String - if configuration = configurations[spec.to_s] - establish_connection(configuration) - elsif spec.is_a?(String) && hash = connection_url_to_hash(spec) - establish_connection(hash) - else - raise AdapterNotSpecified, "#{spec} database is not configured" - end - else - spec = spec.symbolize_keys - unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end - - begin - require "active_record/connection_adapters/#{spec[:adapter]}_adapter" - rescue LoadError => e - raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e})" - end - - adapter_method = "#{spec[:adapter]}_connection" - unless respond_to?(adapter_method) - raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter" - end - - remove_connection - establish_connection(ConnectionSpecification.new(spec, adapter_method)) - end - end - - def self.connection_url_to_hash(url) # :nodoc: - config = URI.parse url - adapter = config.scheme - adapter = "postgresql" if adapter == "postgres" - spec = { :adapter => adapter, - :username => config.user, - :password => config.password, - :port => config.port, - :database => config.path.sub(%r{^/},""), - :host => config.host } - spec.reject!{ |_,value| !value } - if config.query - options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys - spec.merge!(options) - end - spec - end - - class << self - # Returns the connection currently associated with the class. This can - # also be used to "borrow" the connection to do database work unrelated - # to any of the specific Active Records. - def connection - retrieve_connection - end - - # Returns the configuration of the associated connection as a hash: - # - # ActiveRecord::Base.connection_config - # # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"} - # - # Please use only for reading. - def connection_config - connection_pool.spec.config - end - - def connection_pool - connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished - end - - def retrieve_connection - connection_handler.retrieve_connection(self) - end - - # Returns true if Active Record is connected. - def connected? - connection_handler.connected?(self) - end - - def remove_connection(klass = self) - connection_handler.remove_connection(klass) - end - - def clear_active_connections! - connection_handler.clear_active_connections! - end - - delegate :clear_reloadable_connections!, - :clear_all_connections!,:verify_active_connections!, :to => :connection_handler - end - end -end 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 dc4a53034b..eb8cff9610 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -130,7 +130,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/savepoints.html + # http://dev.mysql.com/doc/refman/5.0/en/savepoint.html # Savepoints are supported by MySQL and PostgreSQL, but not SQLite3. # # It is safe to call this method if a database transaction is already open, @@ -341,7 +341,7 @@ module ActiveRecord # Send a rollback message to all records after they have been rolled back. If rollback # is false, only rollback records since the last save point. - def rollback_transaction_records(rollback) #:nodoc + def rollback_transaction_records(rollback) if rollback records = @_current_transaction_records.flatten @_current_transaction_records.clear @@ -361,7 +361,7 @@ module ActiveRecord end # Send a commit message to all records after they have been committed. - def commit_transaction_records #:nodoc + def commit_transaction_records records = @_current_transaction_records.flatten @_current_transaction_records.clear unless records.blank? diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb index 27ff13ad89..6ba64bb88f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb @@ -65,18 +65,24 @@ module ActiveRecord end private - def cache_sql(sql, binds) - result = - if @query_cache[sql].key?(binds) - ActiveSupport::Notifications.instrument("sql.active_record", - :sql => sql, :name => "CACHE", :connection_id => object_id) - @query_cache[sql][binds] - else - @query_cache[sql][binds] = yield - end + def cache_sql(sql, binds) + result = + if @query_cache[sql].key?(binds) + ActiveSupport::Notifications.instrument("sql.active_record", + :sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id) + @query_cache[sql][binds] + else + @query_cache[sql][binds] = yield + end + # FIXME: we should guarantee that all cached items are Result + # objects. Then we can avoid this conditional + if ActiveRecord::Result === result + result.dup + else result.collect { |row| row.dup } end + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb index f93c7cd74a..44ac37c498 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb @@ -71,7 +71,8 @@ module ActiveRecord when Date, Time then quoted_date(value) when Symbol then value.to_s else - YAML.dump(value) + to_type = column ? " to #{column.type}" : "" + raise TypeError, "can't cast #{value.class}#{to_type}" end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 82f564e41d..132ca10f79 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -6,7 +6,7 @@ require 'bigdecimal/util' module ActiveRecord module ConnectionAdapters #:nodoc: - class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc: + class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders) #:nodoc: end # Abstract representation of a column definition. Instances of this type @@ -46,13 +46,13 @@ module ActiveRecord # +change_table+ is actually of this type: # # class SomeMigration < ActiveRecord::Migration - # def self.up + # def up # create_table :foo do |t| # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition" # end # end # - # def self.down + # def down # ... # end # end @@ -66,6 +66,7 @@ module ActiveRecord def initialize(base) @columns = [] + @columns_hash = {} @base = base end @@ -86,7 +87,7 @@ module ActiveRecord # Returns a ColumnDefinition for the column with name +name+. def [](name) - @columns.find {|column| column.name.to_s == name.to_s} + @columns_hash[name.to_s] end # Instantiates a new column for the table. @@ -224,35 +225,38 @@ module ActiveRecord # t.references :taggable, :polymorphic => { :default => 'Photo' } # end def column(name, type, options = {}) - column = self[name] || ColumnDefinition.new(@base, name, type) - if options[:limit] - column.limit = options[:limit] - elsif native[type.to_sym].is_a?(Hash) - column.limit = native[type.to_sym][:limit] + name = name.to_s + type = type.to_sym + + column = self[name] || new_column_definition(@base, name, type) + + limit = options.fetch(:limit) do + native[type][:limit] if native[type].is_a?(Hash) end + + column.limit = limit column.precision = options[:precision] - column.scale = options[:scale] - column.default = options[:default] - column.null = options[:null] - @columns << column unless @columns.include? column + column.scale = options[:scale] + column.default = options[:default] + column.null = options[:null] self end %w( string text integer float decimal datetime timestamp time date binary boolean ).each do |column_type| class_eval <<-EOV, __FILE__, __LINE__ + 1 - def #{column_type}(*args) # def string(*args) - options = args.extract_options! # options = args.extract_options! - column_names = args # column_names = args - # - column_names.each { |name| column(name, '#{column_type}', options) } # column_names.each { |name| column(name, 'string', options) } - end # end + def #{column_type}(*args) # def string(*args) + options = args.extract_options! # options = args.extract_options! + column_names = args # column_names = args + type = :'#{column_type}' # type = :string + column_names.each { |name| column(name, type, options) } # column_names.each { |name| column(name, type, options) } + end # end EOV end # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and # <tt>:updated_at</tt> to the table. def timestamps(*args) - options = args.extract_options! + options = { :null => false }.merge(args.extract_options!) column(:created_at, :datetime, options) column(:updated_at, :datetime, options) end @@ -275,9 +279,16 @@ module ActiveRecord end private - def native - @base.native_database_types - end + def new_column_definition(base, name, type) + definition = ColumnDefinition.new base, name, type + @columns << definition + @columns_hash[name] = definition + definition + end + + def native + @base.native_database_types + end end # Represents an SQL table in an abstract way for updating a table. @@ -453,13 +464,13 @@ module ActiveRecord def #{column_type}(*args) # def string(*args) options = args.extract_options! # options = args.extract_options! column_names = args # column_names = args - # + type = :'#{column_type}' # type = :string column_names.each do |name| # column_names.each do |name| - column = ColumnDefinition.new(@base, name, '#{column_type}') # column = ColumnDefinition.new(@base, name, 'string') + column = ColumnDefinition.new(@base, name.to_s, type) # column = ColumnDefinition.new(@base, name, type) if options[:limit] # if options[:limit] column.limit = options[:limit] # column.limit = options[:limit] - elsif native['#{column_type}'.to_sym].is_a?(Hash) # elsif native['string'.to_sym].is_a?(Hash) - column.limit = native['#{column_type}'.to_sym][:limit] # column.limit = native['string'.to_sym][:limit] + elsif native[type].is_a?(Hash) # elsif native[type].is_a?(Hash) + column.limit = native[type][:limit] # column.limit = native[type][:limit] end # end column.precision = options[:precision] # column.precision = options[:precision] column.scale = options[:scale] # column.scale = options[:scale] @@ -479,4 +490,3 @@ module ActiveRecord end end - diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index 8e3ba1297e..1f9321edb6 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -1,8 +1,12 @@ -require 'active_support/core_ext/array/wrap' +require 'active_support/deprecation/reporting' +require 'active_record/schema_migration' +require 'active_record/migration/join_table' module ActiveRecord module ConnectionAdapters # :nodoc: module SchemaStatements + include ActiveRecord::Migration::JoinTable + # Returns a Hash of mappings from the abstract data types to the native # database types. See TableDefinition#column for details on the recognized # abstract data types. @@ -15,8 +19,6 @@ module ActiveRecord table_name[0...table_alias_length].gsub(/\./, '_') end - # def tables(name = nil) end - # Checks to see if the table +table_name+ exists on the database. # # === Example @@ -43,7 +45,7 @@ module ActiveRecord # # Check an index with a custom name exists # index_exists?(:suppliers, :company_id, :name => "idx_company_id" def index_exists?(table_name, column_name, options = {}) - column_names = Array.wrap(column_name) + column_names = Array(column_name) index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, :column => column_names) if options[:unique] indexes(table_name).any?{ |i| i.unique && i.name == index_name } @@ -54,7 +56,7 @@ module ActiveRecord # Returns an array of Column objects for the table specified by +table_name+. # See the concrete implementation for details on the expected parameter values. - def columns(table_name, name = nil) end + def columns(table_name) end # Checks to see if a column exists in a given table. # @@ -113,7 +115,7 @@ module ActiveRecord # Defaults to +id+. If <tt>:id</tt> is false this option is ignored. # # Also note that this just sets the primary key in the table. You additionally - # need to configure the primary key in the model via the +set_primary_key+ macro. + # need to configure the primary key in the model via +self.primary_key=+. # Models do NOT auto-detect the primary key from their table definition. # # [<tt>:options</tt>] @@ -171,6 +173,45 @@ module ActiveRecord execute create_sql end + # Creates a new join table with the name created using the lexical order of the first two + # arguments. These arguments can be be a String or a Symbol. + # + # # Creates a table called 'assemblies_parts' with no id. + # create_join_table(:assemblies, :parts) + # + # You can pass a +options+ hash can include the following keys: + # [<tt>:table_name</tt>] + # Sets the table name overriding the default + # [<tt>:column_options</tt>] + # Any extra options you want appended to the columns definition. + # [<tt>:options</tt>] + # Any extra options you want appended to the table definition. + # [<tt>:temporary</tt>] + # Make a temporary table. + # [<tt>:force</tt>] + # Set to true to drop the table before creating it. + # Defaults to false. + # + # ===== Examples + # ====== Add a backend specific option to the generated SQL (MySQL) + # create_join_table(:assemblies, :parts, :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8') + # generates: + # CREATE TABLE assemblies_parts ( + # assembly_id int NOT NULL, + # part_id int NOT NULL, + # ) ENGINE=InnoDB DEFAULT CHARSET=utf8 + def create_join_table(table_1, table_2, options = {}) + join_table_name = find_join_table_name(table_1, table_2, options) + + column_options = options.delete(:column_options) || {} + column_options.reverse_merge!({:null => false}) + + create_table(join_table_name, options.merge!(:id => false)) do |td| + td.integer :"#{table_1.to_s.singularize}_id", column_options + td.integer :"#{table_2.to_s.singularize}_id", column_options + end + end + # A block for changing columns in +table+. # # === Example @@ -302,15 +343,8 @@ module ActiveRecord # Adds a new index to the table. +column_name+ can be a single Symbol, or # an Array of Symbols. # - # The index will be named after the table and the first column name, - # unless you pass <tt>:name</tt> as an option. - # - # When creating an index on multiple columns, the first column is used as a name - # for the index. For example, when you specify an index on two columns - # [<tt>:first</tt>, <tt>:last</tt>], the DBMS creates an index for both columns as well as an - # index for the first column <tt>:first</tt>. Using just the first name for this index - # makes sense, because you will never have to create a singular index with this - # name. + # The index will be named after the table and the column name(s), unless + # you pass <tt>:name</tt> as an option. # # ===== Examples # @@ -339,6 +373,14 @@ module ActiveRecord # CREATE INDEX by_name_surname ON accounts(name(10), surname(15)) # # Note: SQLite doesn't support index length + # + # ====== Creating an index with a sort order (desc or asc, asc is the default) + # add_index(:accounts, [:branch_id, :party_id, :surname], :order => {:branch_id => :desc, :part_id => :asc}) + # generates + # CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname) + # + # Note: mysql doesn't yet support index order (it accepts the syntax but ignores it) + # def add_index(table_name, column_name, options = {}) index_name, index_type, index_columns = add_index_options(table_name, column_name, options) execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})" @@ -377,7 +419,7 @@ module ActiveRecord def index_name(table_name, options) #:nodoc: if Hash === options # legacy support if options[:column] - "index_#{table_name}_on_#{Array.wrap(options[:column]) * '_and_'}" + "index_#{table_name}_on_#{Array(options[:column]) * '_and_'}" elsif options[:name] options[:name] else @@ -405,37 +447,20 @@ module ActiveRecord def dump_schema_information #:nodoc: sm_table = ActiveRecord::Migrator.schema_migrations_table_name - migrated = select_values("SELECT version FROM #{sm_table}") - migrated.map { |v| "INSERT INTO #{sm_table} (version) VALUES ('#{v}');" }.join("\n\n") + + ActiveRecord::SchemaMigration.order('version').all.map { |sm| + "INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');" + }.join "\n\n" end # Should not be called normally, but this operation is non-destructive. # The migrations module handles this automatically. def initialize_schema_migrations_table - sm_table = ActiveRecord::Migrator.schema_migrations_table_name - - unless table_exists?(sm_table) - create_table(sm_table, :id => false) do |schema_migrations_table| - schema_migrations_table.column :version, :string, :null => false - end - add_index sm_table, :version, :unique => true, - :name => "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}" - - # Backwards-compatibility: if we find schema_info, assume we've - # migrated up to that point: - si_table = Base.table_name_prefix + 'schema_info' + Base.table_name_suffix - - if table_exists?(si_table) - - old_version = select_value("SELECT version FROM #{quote_table_name(si_table)}").to_i - assume_migrated_upto_version(old_version) - drop_table(si_table) - end - end + ActiveRecord::SchemaMigration.create_table end def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths) - migrations_paths = Array.wrap(migrations_paths) + migrations_paths = Array(migrations_paths) version = version.to_i sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name) @@ -507,8 +532,8 @@ module ActiveRecord # ===== Examples # add_timestamps(:suppliers) def add_timestamps(table_name) - add_column table_name, :created_at, :datetime - add_column table_name, :updated_at, :datetime + add_column table_name, :created_at, :datetime, :null => false + add_column table_name, :updated_at, :datetime, :null => false end # Removes the timestamp columns (created_at and updated_at) from the table definition. @@ -520,9 +545,29 @@ module ActiveRecord end protected + def add_index_sort_order(option_strings, column_names, options = {}) + if options.is_a?(Hash) && order = options[:order] + case order + when Hash + column_names.each {|name| option_strings[name] += " #{order[name].to_s.upcase}" if order.has_key?(name)} + when String + column_names.each {|name| option_strings[name] += " #{order.upcase}"} + end + end + + return option_strings + end + # Overridden by the mysql adapter for supporting index lengths def quoted_columns_for_index(column_names, options = {}) - column_names.map {|name| quote_column_name(name) } + option_strings = Hash[column_names.map {|name| [name, '']}] + + # add index sort order if supported + if supports_index_sort_order? + option_strings = add_index_sort_order(option_strings, column_names, options) + end + + column_names.map {|name| quote_column_name(name) + option_strings[name]} end def options_include_default?(options) @@ -530,7 +575,7 @@ module ActiveRecord end def add_index_options(table_name, column_name, options = {}) - column_names = Array.wrap(column_name) + column_names = Array(column_name) index_name = index_name(table_name, :column => column_names) if Hash === options # legacy support, since this param was a string diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 443e61b527..edea414db7 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -3,12 +3,15 @@ require 'bigdecimal' require 'bigdecimal/util' require 'active_support/core_ext/benchmark' require 'active_support/deprecation' +require 'active_record/connection_adapters/schema_cache' +require 'monitor' module ActiveRecord module ConnectionAdapters # :nodoc: extend ActiveSupport::Autoload autoload :Column + autoload :ConnectionSpecification autoload_under 'abstract' do autoload :IndexDefinition, 'active_record/connection_adapters/abstract/schema_definitions' @@ -24,7 +27,6 @@ module ActiveRecord autoload :ConnectionPool autoload :ConnectionHandler, 'active_record/connection_adapters/abstract/connection_pool' autoload :ConnectionManagement, 'active_record/connection_adapters/abstract/connection_pool' - autoload :ConnectionSpecification autoload :QueryCache end @@ -47,39 +49,44 @@ module ActiveRecord include DatabaseLimits include QueryCache include ActiveSupport::Callbacks + include MonitorMixin define_callbacks :checkout, :checkin - attr_accessor :visitor - - def initialize(connection, logger = nil) #:nodoc: - @active = nil - @connection, @logger = connection, logger + attr_accessor :visitor, :pool + attr_reader :schema_cache, :last_use, :in_use + alias :in_use? :in_use + + def initialize(connection, logger = nil, pool = nil) #:nodoc: + super() + + @active = nil + @connection = connection + @in_use = false + @instrumenter = ActiveSupport::Notifications.instrumenter + @last_use = false + @logger = logger + @open_transactions = 0 + @pool = pool + @query_cache = Hash.new { |h,sql| h[sql] = {} } @query_cache_enabled = false - @query_cache = Hash.new { |h,sql| h[sql] = {} } - @open_transactions = 0 - @instrumenter = ActiveSupport::Notifications.instrumenter - @visitor = nil - end - - # Returns a visitor instance for this adaptor, which conforms to the Arel::ToSql interface - def self.visitor_for(pool) # :nodoc: - adapter = pool.spec.config[:adapter] - - if Arel::Visitors::VISITORS[adapter] - ActiveSupport::Deprecation.warn( - "Arel::Visitors::VISITORS is deprecated and will be removed. Database adapters " \ - "should define a visitor_for method which returns the appropriate visitor for " \ - "the database. For example, MysqlAdapter.visitor_for(pool) returns " \ - "Arel::Visitors::MySQL.new(pool)." - ) - - Arel::Visitors::VISITORS[adapter].new(pool) - else - Arel::Visitors::ToSql.new(pool) + @schema_cache = SchemaCache.new self + @visitor = nil + end + + def lease + synchronize do + unless in_use + @in_use = true + @last_use = Time.now + end end end + def expire + @in_use = false + end + # Returns the human-readable name of the adapter. Use mixed case - one # can always use downcase if needed. def adapter_name @@ -130,6 +137,17 @@ module ActiveRecord false end + # Does this adapter support index sort order? + def supports_index_sort_order? + false + end + + # Does this adapter support explain? As of this writing sqlite3, + # mysql2, and postgresql are the only ones that do. + def supports_explain? + false + end + # QUOTING ================================================== # Override to return the quoted table name. Defaults to column quoting. @@ -238,10 +256,19 @@ module ActiveRecord node end + def case_insensitive_comparison(table, attribute, column, value) + table[attribute].lower.eq(table.lower(value)) + end + def current_savepoint_name "active_record_#{open_transactions}" end + # Check the connection back in to the connection pool + def close + pool.checkin self + end + protected def log(sql, name = "SQL", binds = []) 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 4b7c74e0b8..e1dad5b166 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -4,6 +4,13 @@ module ActiveRecord module ConnectionAdapters class AbstractMysqlAdapter < AbstractAdapter class Column < ConnectionAdapters::Column # :nodoc: + attr_reader :collation + + def initialize(name, default, sql_type = nil, null = true, collation = nil) + super(name, default, sql_type, null) + @collation = collation + end + def extract_default(default) if sql_type =~ /blob/i || type == :text if default.blank? @@ -28,6 +35,10 @@ module ActiveRecord raise NotImplementedError end + def case_sensitive? + collation && !collation.match(/_ci$/) + end + private def simplified_type(field_type) @@ -116,10 +127,7 @@ module ActiveRecord super(connection, logger) @connection_options, @config = connection_options, config @quoted_column_names, @quoted_table_names = {}, {} - end - - def self.visitor_for(pool) # :nodoc: - Arel::Visitors::MySQL.new(pool) + @visitor = Arel::Visitors::MySQL.new self end def adapter_name #:nodoc: @@ -144,6 +152,12 @@ module ActiveRecord true end + # Technically MySQL allows to create indexes with the sort order syntax + # but at the moment (5.5) it doesn't yet implement them + def supports_index_sort_order? + true + end + def native_database_types NATIVE_DATABASE_TYPES end @@ -157,8 +171,8 @@ module ActiveRecord end # Overridden by the adapters to instantiate their specific Column type. - def new_column(field, default, type, null) # :nodoc: - Column.new(field, default, type, null) + def new_column(field, default, type, null, collation) # :nodoc: + Column.new(field, default, type, null, collation) end # Must return the Mysql error number from the exception, if the exception has an @@ -298,11 +312,11 @@ module ActiveRecord sql = "SHOW TABLES" end - select_all(sql).map do |table| + select_all(sql).map { |table| table.delete('Table_type') sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}" exec_without_stmt(sql).first['Create Table'] + ";\n\n" - end.join("") + }.join end # Drops the database specified on the +name+ attribute @@ -349,8 +363,10 @@ module ActiveRecord show_variable 'collation_database' end - def tables(name = nil, database = nil) #:nodoc: - sql = ["SHOW TABLES", database].compact.join(' IN ') + def tables(name = nil, database = nil, like = nil) #:nodoc: + sql = "SHOW TABLES " + sql << "IN #{database} " if database + sql << "LIKE #{quote(like)}" if like execute_and_free(sql, 'SCHEMA') do |result| result.collect { |field| field.first } @@ -358,7 +374,8 @@ module ActiveRecord end def table_exists?(name) - return true if super + return false unless name + return true if tables(nil, nil, name).any? name = name.to_s schema, table = name.split('.', 2) @@ -368,7 +385,7 @@ module ActiveRecord schema = nil end - tables(nil, schema).include? table + tables(nil, schema, table).any? end # Returns an array of indexes for the given table. @@ -392,11 +409,11 @@ module ActiveRecord end # Returns an array of +Column+ objects for the table specified by +table_name+. - def columns(table_name, name = nil)#:nodoc: - sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}" + def columns(table_name)#:nodoc: + sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}" execute_and_free(sql, 'SCHEMA') do |result| each_hash(result).map do |field| - new_column(field[:Field], field[:Default], field[:Type], field[:Null] == "YES") + new_column(field[:Field], field[:Default], field[:Type], field[:Null] == "YES", field[:Collation]) end end end @@ -485,9 +502,14 @@ module ActiveRecord # Returns a table's primary key and belonging sequence. def pk_and_sequence_for(table) - execute_and_free("DESCRIBE #{quote_table_name(table)}", 'SCHEMA') do |result| - keys = each_hash(result).select { |row| row[:Key] == 'PRI' }.map { |row| row[:Field] } - keys.length == 1 ? [keys.first, nil] : nil + execute_and_free("SHOW CREATE TABLE #{quote_table_name(table)}", 'SCHEMA') do |result| + create_table = each_hash(result).first[:"Create Table"] + if create_table.to_s =~ /PRIMARY KEY\s+\((.+)\)/ + keys = $1.split(",").map { |key| key.gsub(/[`"]/, "") } + keys.length == 1 ? [keys.first, nil] : nil + else + nil + end end end @@ -501,23 +523,43 @@ module ActiveRecord Arel::Nodes::Bin.new(node) end + def case_insensitive_comparison(table, attribute, column, value) + if column.case_sensitive? + super + else + table[attribute].eq(value) + end + end + def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key) where_sql end protected + def add_index_length(option_strings, column_names, options = {}) + if options.is_a?(Hash) && length = options[:length] + case length + when Hash + column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name) && length[name].present?} + when Fixnum + column_names.each {|name| option_strings[name] += "(#{length})"} + end + end + + return option_strings + end + def quoted_columns_for_index(column_names, options = {}) - length = options[:length] if options.is_a?(Hash) + option_strings = Hash[column_names.map {|name| [name, '']}] - case length - when Hash - column_names.map {|name| length[name] ? "#{quote_column_name(name)}(#{length[name]})" : quote_column_name(name) } - when Fixnum - column_names.map {|name| "#{quote_column_name(name)}(#{length})"} - else - column_names.map {|name| quote_column_name(name) } - end + # add index length + option_strings = add_index_length(option_strings, column_names, options) + + # add index sort order + option_strings = add_index_sort_order(option_strings, column_names, options) + + column_names.map {|name| quote_column_name(name) + option_strings[name]} end def translate_exception(exception, message) diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb index a7856539b7..2ecb198edb 100644 --- a/activerecord/lib/active_record/connection_adapters/column.rb +++ b/activerecord/lib/active_record/connection_adapters/column.rb @@ -5,8 +5,8 @@ module ActiveRecord module ConnectionAdapters # An abstract definition of a column in a table. class Column - TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set - FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set + TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set + FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set module Format ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/ @@ -80,9 +80,10 @@ module ActiveRecord when :decimal then klass.value_to_decimal(value) when :datetime, :timestamp then klass.string_to_time(value) when :time then klass.string_to_dummy_time(value) - when :date then klass.string_to_date(value) + when :date then klass.value_to_date(value) when :binary then klass.binary_to_string(value) when :boolean then klass.value_to_boolean(value) + when :hstore then klass.cast_hstore(value) else value end end @@ -97,9 +98,10 @@ module ActiveRecord when :decimal then "#{klass}.value_to_decimal(#{var_name})" when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})" when :time then "#{klass}.string_to_dummy_time(#{var_name})" - when :date then "#{klass}.string_to_date(#{var_name})" + when :date then "#{klass}.value_to_date(#{var_name})" when :binary then "#{klass}.binary_to_string(#{var_name})" when :boolean then "#{klass}.value_to_boolean(#{var_name})" + when :hstore then "#{klass}.cast_hstore(#{var_name})" else var_name end end @@ -132,11 +134,15 @@ module ActiveRecord value end - def string_to_date(string) - return string unless string.is_a?(String) - return nil if string.empty? - - fast_string_to_date(string) || fallback_string_to_date(string) + def value_to_date(value) + if value.is_a?(String) + return nil if value.empty? + fast_string_to_date(value) || fallback_string_to_date(value) + elsif value.respond_to?(:to_date) + value.to_date + else + value + end end def string_to_time(string) diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb new file mode 100644 index 0000000000..8491d42b86 --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -0,0 +1,83 @@ +module ActiveRecord + module ConnectionAdapters + class ConnectionSpecification #:nodoc: + attr_reader :config, :adapter_method + + def initialize(config, adapter_method) + @config, @adapter_method = config, adapter_method + end + + def initialize_dup(original) + @config = original.config.dup + end + + ## + # Builds a ConnectionSpecification from user input + class Resolver # :nodoc: + attr_reader :config, :klass, :configurations + + def initialize(config, configurations) + @config = config + @configurations = configurations + end + + def spec + case config + when nil + raise AdapterNotSpecified unless defined?(Rails.env) + resolve_string_connection Rails.env + when Symbol, String + resolve_string_connection config.to_s + when Hash + resolve_hash_connection config + end + end + + private + def resolve_string_connection(spec) # :nodoc: + hash = configurations.fetch(spec) do |k| + connection_url_to_hash(k) + end + + raise(AdapterNotSpecified, "#{spec} database is not configured") unless hash + + resolve_hash_connection hash + end + + def resolve_hash_connection(spec) # :nodoc: + spec = spec.symbolize_keys + + raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter) + + begin + require "active_record/connection_adapters/#{spec[:adapter]}_adapter" + rescue LoadError => e + raise LoadError, "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e.message})", e.backtrace + end + + adapter_method = "#{spec[:adapter]}_connection" + + ConnectionSpecification.new(spec, adapter_method) + end + + def connection_url_to_hash(url) # :nodoc: + config = URI.parse url + adapter = config.scheme + adapter = "postgresql" if adapter == "postgres" + spec = { :adapter => adapter, + :username => config.user, + :password => config.password, + :port => config.port, + :database => config.path.sub(%r{^/},""), + :host => config.host } + spec.reject!{ |_,value| !value } + if config.query + options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys + spec.merge!(options) + end + spec + end + end + end + end +end diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 8b574518e5..c1332fde1a 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -1,12 +1,12 @@ require 'active_record/connection_adapters/abstract_mysql_adapter' -gem 'mysql2', '~> 0.3.6' +gem 'mysql2', '~> 0.3.10' require 'mysql2' module ActiveRecord - class Base + module ConnectionHandling # Establishes a connection to the database that's used by all Active Record objects. - def self.mysql2_connection(config) + def mysql2_connection(config) config[:username] = 'root' if config[:username].nil? if Mysql2::Client.const_defined? :FOUND_ROWS @@ -35,6 +35,10 @@ module ActiveRecord configure_connection end + def supports_explain? + true + end + # HELPER METHODS =========================================== def each_hash(result) # :nodoc: @@ -47,8 +51,8 @@ module ActiveRecord end end - def new_column(field, default, type, null) # :nodoc: - Column.new(field, default, type, null) + def new_column(field, default, type, null, collation) # :nodoc: + Column.new(field, default, type, null, collation) end def error_number(exception) @@ -93,6 +97,80 @@ module ActiveRecord # DATABASE STATEMENTS ====================================== + def explain(arel, binds = []) + sql = "EXPLAIN #{to_sql(arel)}" + start = Time.now + result = exec_query(sql, 'EXPLAIN', binds) + elapsed = Time.now - start + + ExplainPrettyPrinter.new.pp(result, elapsed) + end + + class ExplainPrettyPrinter # :nodoc: + # Pretty prints the result of a EXPLAIN in a way that resembles the output of the + # MySQL shell: + # + # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ + # | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | + # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ + # | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | | + # | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where | + # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ + # 2 rows in set (0.00 sec) + # + # This is an exercise in Ruby hyperrealism :). + def pp(result, elapsed) + widths = compute_column_widths(result) + separator = build_separator(widths) + + pp = [] + + pp << separator + pp << build_cells(result.columns, widths) + pp << separator + + result.rows.each do |row| + pp << build_cells(row, widths) + end + + pp << separator + pp << build_footer(result.rows.length, elapsed) + + pp.join("\n") + "\n" + end + + private + + def compute_column_widths(result) + [].tap do |widths| + result.columns.each_with_index do |column, i| + cells_in_column = [column] + result.rows.map {|r| r[i].nil? ? 'NULL' : r[i].to_s} + widths << cells_in_column.map(&:length).max + end + end + end + + def build_separator(widths) + padding = 1 + '+' + widths.map {|w| '-' * (w + (padding*2))}.join('+') + '+' + end + + def build_cells(items, widths) + cells = [] + items.each_with_index do |item, i| + item = 'NULL' if item.nil? + justifier = item.is_a?(Numeric) ? 'rjust' : 'ljust' + cells << item.to_s.send(justifier, widths[i]) + end + '| ' + cells.join(' | ') + ' |' + end + + def build_footer(nrows, elapsed) + rows_label = nrows == 1 ? 'row' : 'rows' + "#{nrows} #{rows_label} in set (%.2f sec)" % elapsed + end + end + # FIXME: re-enable the following once a "better" query_cache solution is in core # # The overrides below perform much better than the originals in AbstractAdapter @@ -147,7 +225,7 @@ module ActiveRecord # column values as values. def select(sql, name = nil, binds = []) binds = binds.dup - exec_query(sql.gsub("\0") { quote(*binds.shift.reverse) }, name).to_a + exec_query(sql.gsub("\0") { quote(*binds.shift.reverse) }, name) end def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index a1824fe396..5905242747 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -18,9 +18,9 @@ class Mysql end module ActiveRecord - class Base + module ConnectionHandling # Establishes a connection to the database that's used by all Active Record objects. - def self.mysql_connection(config) # :nodoc: + def mysql_connection(config) # :nodoc: config = config.symbolize_keys host = config[:host] port = config[:port] @@ -150,8 +150,8 @@ module ActiveRecord end end - def new_column(field, default, type, null) # :nodoc: - Column.new(field, default, type, null) + def new_column(field, default, type, null, collation) # :nodoc: + Column.new(field, default, type, null, collation) end def error_number(exception) # :nodoc: @@ -224,52 +224,48 @@ module ActiveRecord @statements.clear end - if "<3".respond_to?(:encode) - # Taken from here: - # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb - # Author: TOMITA Masahiro <tommy@tmtm.org> - ENCODINGS = { - "armscii8" => nil, - "ascii" => Encoding::US_ASCII, - "big5" => Encoding::Big5, - "binary" => Encoding::ASCII_8BIT, - "cp1250" => Encoding::Windows_1250, - "cp1251" => Encoding::Windows_1251, - "cp1256" => Encoding::Windows_1256, - "cp1257" => Encoding::Windows_1257, - "cp850" => Encoding::CP850, - "cp852" => Encoding::CP852, - "cp866" => Encoding::IBM866, - "cp932" => Encoding::Windows_31J, - "dec8" => nil, - "eucjpms" => Encoding::EucJP_ms, - "euckr" => Encoding::EUC_KR, - "gb2312" => Encoding::EUC_CN, - "gbk" => Encoding::GBK, - "geostd8" => nil, - "greek" => Encoding::ISO_8859_7, - "hebrew" => Encoding::ISO_8859_8, - "hp8" => nil, - "keybcs2" => nil, - "koi8r" => Encoding::KOI8_R, - "koi8u" => Encoding::KOI8_U, - "latin1" => Encoding::ISO_8859_1, - "latin2" => Encoding::ISO_8859_2, - "latin5" => Encoding::ISO_8859_9, - "latin7" => Encoding::ISO_8859_13, - "macce" => Encoding::MacCentEuro, - "macroman" => Encoding::MacRoman, - "sjis" => Encoding::SHIFT_JIS, - "swe7" => nil, - "tis620" => Encoding::TIS_620, - "ucs2" => Encoding::UTF_16BE, - "ujis" => Encoding::EucJP_ms, - "utf8" => Encoding::UTF_8, - "utf8mb4" => Encoding::UTF_8, - } - else - ENCODINGS = Hash.new { |h,k| h[k] = k } - end + # Taken from here: + # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb + # Author: TOMITA Masahiro <tommy@tmtm.org> + ENCODINGS = { + "armscii8" => nil, + "ascii" => Encoding::US_ASCII, + "big5" => Encoding::Big5, + "binary" => Encoding::ASCII_8BIT, + "cp1250" => Encoding::Windows_1250, + "cp1251" => Encoding::Windows_1251, + "cp1256" => Encoding::Windows_1256, + "cp1257" => Encoding::Windows_1257, + "cp850" => Encoding::CP850, + "cp852" => Encoding::CP852, + "cp866" => Encoding::IBM866, + "cp932" => Encoding::Windows_31J, + "dec8" => nil, + "eucjpms" => Encoding::EucJP_ms, + "euckr" => Encoding::EUC_KR, + "gb2312" => Encoding::EUC_CN, + "gbk" => Encoding::GBK, + "geostd8" => nil, + "greek" => Encoding::ISO_8859_7, + "hebrew" => Encoding::ISO_8859_8, + "hp8" => nil, + "keybcs2" => nil, + "koi8r" => Encoding::KOI8_R, + "koi8u" => Encoding::KOI8_U, + "latin1" => Encoding::ISO_8859_1, + "latin2" => Encoding::ISO_8859_2, + "latin5" => Encoding::ISO_8859_9, + "latin7" => Encoding::ISO_8859_13, + "macce" => Encoding::MacCentEuro, + "macroman" => Encoding::MacRoman, + "sjis" => Encoding::SHIFT_JIS, + "swe7" => nil, + "tis620" => Encoding::TIS_620, + "ucs2" => Encoding::UTF_16BE, + "ujis" => Encoding::EucJP_ms, + "utf8" => Encoding::UTF_8, + "utf8mb4" => Encoding::UTF_8, + } # Get the client encoding for this database def client_encoding @@ -412,7 +408,7 @@ module ActiveRecord def select(sql, name = nil, binds = []) @connection.query_with_result = true - rows = exec_query(sql, name, binds).to_a + rows = exec_query(sql, name, binds) @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped rows end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 5402918b1d..fe77eb725e 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -7,24 +7,26 @@ gem 'pg', '~> 0.11' require 'pg' module ActiveRecord - class Base + module ConnectionHandling # Establishes a connection to the database that's used by all Active Record objects - def self.postgresql_connection(config) # :nodoc: - config = config.symbolize_keys - host = config[:host] - port = config[:port] || 5432 - username = config[:username].to_s if config[:username] - password = config[:password].to_s if config[:password] + def postgresql_connection(config) # :nodoc: + conn_params = config.symbolize_keys - if config.key?(:database) - database = config[:database] - else - raise ArgumentError, "No database specified. Missing argument: database." + # Forward any unused config params to PGconn.connect. + [:statement_limit, :encoding, :min_messages, :schema_search_path, + :schema_order, :adapter, :pool, :wait_timeout, + :reaping_frequency].each do |key| + conn_params.delete key end + conn_params.delete_if { |k,v| v.nil? } + + # Map ActiveRecords param names to PGs. + conn_params[:user] = conn_params.delete(:username) if conn_params[:username] + conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database] # The postgres drivers don't allow the creation of an unconnected PGconn object, # so just pass a nil connection object for the time being. - ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, [host, port, nil, nil, database, username, password], config) + ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config) end end @@ -49,6 +51,42 @@ module ActiveRecord super end end + + def cast_hstore(object) + if Hash === object + object.map { |k,v| + "#{escape_hstore(k)}=>#{escape_hstore(v)}" + }.join ', ' + else + kvs = object.scan(/(?<!\\)".*?(?<!\\)"/).map { |o| + unescape_hstore(o[1...-1]) + } + Hash[kvs.each_slice(2).to_a] + end + end + + private + HSTORE_ESCAPE = { + ' ' => '\\ ', + '\\' => '\\\\', + '"' => '\\"', + '=' => '\\=', + } + HSTORE_ESCAPE_RE = Regexp.union(HSTORE_ESCAPE.keys) + HSTORE_UNESCAPE = HSTORE_ESCAPE.invert + HSTORE_UNESCAPE_RE = Regexp.union(HSTORE_UNESCAPE.keys) + + def unescape_hstore(value) + value.gsub(HSTORE_UNESCAPE_RE) do |match| + HSTORE_UNESCAPE[match] + end + end + + def escape_hstore(value) + value.gsub(HSTORE_ESCAPE_RE) do |match| + HSTORE_ESCAPE[match] + end + end end # :startdoc: @@ -79,67 +117,69 @@ module ActiveRecord # Maps PostgreSQL-specific data types to logical Rails types. def simplified_type(field_type) case field_type - # Numeric and monetary types - when /^(?:real|double precision)$/ - :float - # Monetary types - when 'money' - :decimal - # Character types - when /^(?:character varying|bpchar)(?:\(\d+\))?$/ - :string - # Binary data types - when 'bytea' - :binary - # Date/time types - when /^timestamp with(?:out)? time zone$/ - :datetime - when 'interval' - :string - # Geometric types - when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/ - :string - # Network address types - when /^(?:cidr|inet|macaddr)$/ - :string - # Bit strings - when /^bit(?: varying)?(?:\(\d+\))?$/ - :string - # XML type - when 'xml' - :xml - # tsvector type - when 'tsvector' - :tsvector - # Arrays - when /^\D+\[\]$/ - :string - # Object identifier types - when 'oid' - :integer - # UUID type - when 'uuid' - :string - # Small and big integer types - when /^(?:small|big)int$/ - :integer - # Pass through all types that are not specific to PostgreSQL. - else - super + # Numeric and monetary types + when /^(?:real|double precision)$/ + :float + # Monetary types + when 'money' + :decimal + when 'hstore' + :hstore + # Character types + when /^(?:character varying|bpchar)(?:\(\d+\))?$/ + :string + # Binary data types + when 'bytea' + :binary + # Date/time types + when /^timestamp with(?:out)? time zone$/ + :datetime + when 'interval' + :string + # Geometric types + when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/ + :string + # Network address types + when /^(?:cidr|inet|macaddr)$/ + :string + # Bit strings + when /^bit(?: varying)?(?:\(\d+\))?$/ + :string + # XML type + when 'xml' + :xml + # tsvector type + when 'tsvector' + :tsvector + # Arrays + when /^\D+\[\]$/ + :string + # Object identifier types + when 'oid' + :integer + # UUID type + when 'uuid' + :string + # Small and big integer types + when /^(?:small|big)int$/ + :integer + # Pass through all types that are not specific to PostgreSQL. + else + super end end # Extracts the value from a PostgreSQL column default definition. def self.extract_value_from_default(default) + # This is a performance optimization for Ruby 1.9.2 in development. + # If the value is nil, we return nil straight away without checking + # the regular expressions. If we check each regular expression, + # Regexp#=== will call NilClass#to_str, which will trigger + # method_missing (defined by whiny nil in ActiveSupport) which + # makes this method very very slow. + return default unless default + case default - # This is a performance optimization for Ruby 1.9.2 in development. - # If the value is nil, we return nil straight away without checking - # the regular expressions. If we check each regular expression, - # Regexp#=== will call NilClass#to_str, which will trigger - # method_missing (defined by whiny nil in ActiveSupport) which - # makes this method very very slow. - when NilClass - nil # Numeric types when /\A\(?(-?\d+(\.\d*)?\)?)\z/ $1 @@ -188,22 +228,29 @@ module ActiveRecord end end - # The PostgreSQL adapter works both with the native C (http://ruby.scripting.ca/postgres/) and the pure - # Ruby (available both as gem and from http://rubyforge.org/frs/?group_id=234&release_id=1944) drivers. + # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver. # # Options: # - # * <tt>:host</tt> - Defaults to "localhost". + # * <tt>:host</tt> - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets, + # the default is to connect to localhost. # * <tt>:port</tt> - Defaults to 5432. - # * <tt>:username</tt> - Defaults to nothing. - # * <tt>:password</tt> - Defaults to nothing. - # * <tt>:database</tt> - The name of the database. No default, must be provided. + # * <tt>:username</tt> - Defaults to be the same as the operating system name of the user running the application. + # * <tt>:password</tt> - Password to be used if the server demands password authentication. + # * <tt>:database</tt> - Defaults to be the same as the user name. # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given # as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option. # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO # <encoding></tt> call on the connection. # * <tt>:min_messages</tt> - An optional client min messages that is used in a # <tt>SET client_min_messages TO <min_messages></tt> call on the connection. + # + # Any further options are used as connection parameters to libpq. See + # http://www.postgresql.org/docs/9.1/static/libpq-connect.html for the + # list of parameters. + # + # In addition, default connection parameters of libpq can be set per environment variables. + # See http://www.postgresql.org/docs/9.1/static/libpq-envars.html . class PostgreSQLAdapter < AbstractAdapter class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition def xml(*args) @@ -215,6 +262,10 @@ module ActiveRecord options = args.extract_options! column(args[0], 'tsvector', options) end + + def hstore(name, options = {}) + column(name, 'hstore', options) + end end ADAPTER_NAME = 'PostgreSQL' @@ -247,6 +298,10 @@ module ActiveRecord true end + def supports_index_sort_order? + true + end + class StatementPool < ConnectionAdapters::StatementPool def initialize(connection, max) super @@ -278,13 +333,24 @@ module ActiveRecord cache.clear end + def delete(sql_key) + dealloc cache[sql_key] + cache.delete sql_key + end + private def cache @cache[$$] end def dealloc(key) - @connection.query "DEALLOCATE #{key}" + @connection.query "DEALLOCATE #{key}" if connection_active? + end + + def connection_active? + @connection.status == PGconn::CONNECTION_OK + rescue PGError + false end end @@ -292,6 +358,7 @@ module ActiveRecord def initialize(connection, logger, connection_parameters, config) super(connection, logger) @connection_parameters, @config = connection_parameters, config + @visitor = Arel::Visitors::PostgreSQL.new self # @local_tz is initialized as nil to avoid warnings when connect tries to use it @local_tz = nil @@ -308,10 +375,6 @@ module ActiveRecord @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"] end - def self.visitor_for(pool) # :nodoc: - Arel::Visitors::PostgreSQL.new(pool) - end - # Clears the prepared statements cache. def clear_cache! @statements.clear @@ -378,6 +441,11 @@ module ActiveRecord true end + # Returns true. + def supports_explain? + true + end + # Returns the configured supported identifier length supported by PostgreSQL def table_alias_length @table_alias_length ||= query('SHOW max_identifier_length')[0][0].to_i @@ -387,14 +455,14 @@ module ActiveRecord # Escapes binary strings for bytea input to the database. def escape_bytea(value) - @connection.escape_bytea(value) if value + PGconn.escape_bytea(value) if value end # Unescapes bytea output from a database to the binary string it represents. # NOTE: This is NOT an inverse of escape_bytea! This is only to be used # on escaped binary output from database drive. def unescape_bytea(value) - @connection.unescape_bytea(value) if value + PGconn.unescape_bytea(value) if value end # Quotes PostgreSQL-specific data types for SQL input. @@ -502,6 +570,48 @@ module ActiveRecord # DATABASE STATEMENTS ====================================== + def explain(arel, binds = []) + sql = "EXPLAIN #{to_sql(arel)}" + ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds)) + end + + class ExplainPrettyPrinter # :nodoc: + # Pretty prints the result of a EXPLAIN in a way that resembles the output of the + # PostgreSQL shell: + # + # QUERY PLAN + # ------------------------------------------------------------------------------ + # Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0) + # Join Filter: (posts.user_id = users.id) + # -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4) + # Index Cond: (id = 1) + # -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4) + # Filter: (posts.user_id = 1) + # (6 rows) + # + def pp(result) + header = result.columns.first + lines = result.rows.map(&:first) + + # We add 2 because there's one char of padding at both sides, note + # the extra hyphens in the example above. + width = [header, *lines].map(&:length).max + 2 + + pp = [] + + pp << header.center(width).rstrip + pp << '-' * width + + pp += lines.map {|line| " #{line}"} + + nrows = result.rows.length + rows_label = nrows == 1 ? 'row' : 'rows' + pp << "(#{nrows} #{rows_label})" + + pp.join("\n") + "\n" + end + end + # Executes a SELECT query and returns an array of rows. Each row is an # array of field values. def select_rows(sql, name = nil) @@ -743,16 +853,15 @@ module ActiveRecord # Returns an array of indexes for the given table. def indexes(table_name, name = nil) - schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',') result = query(<<-SQL, name) - SELECT distinct i.relname, d.indisunique, d.indkey, t.oid + SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid FROM pg_class t INNER JOIN pg_index d ON t.oid = d.indrelid INNER JOIN pg_class i ON d.indexrelid = i.oid WHERE i.relkind = 'i' AND d.indisprimary = 'f' AND t.relname = '#{table_name}' - AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname IN (#{schemas}) ) + AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) ) ORDER BY i.relname SQL @@ -761,7 +870,8 @@ module ActiveRecord index_name = row[0] unique = row[1] == 't' indkey = row[2].split(" ") - oid = row[3] + inddef = row[3] + oid = row[4] columns = Hash[query(<<-SQL, "Columns for index #{row[0]} on #{table_name}")] SELECT a.attnum, a.attname @@ -771,12 +881,17 @@ module ActiveRecord SQL column_names = columns.values_at(*indkey).compact - column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names) + + # add info on sort order for columns (only desc order is explicitly specified, asc is the default) + desc_order_columns = inddef.scan(/(\w+) DESC/).flatten + orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {} + + column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names, [], orders) end.compact end # Returns the list of all column definitions for a table. - def columns(table_name, name = nil) + def columns(table_name) # Limit, precision, and scale are all handled by the superclass. column_definitions(table_name).collect do |column_name, type, default, notnull| PostgreSQLColumn.new(column_name, default, type, notnull == 'f') @@ -815,7 +930,7 @@ module ActiveRecord # Returns the active schema search path. def schema_search_path - @schema_search_path ||= query('SHOW search_path')[0][0] + @schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0] end # Returns the current client message level. @@ -911,12 +1026,14 @@ module ActiveRecord # Example: # rename_table('octopuses', 'octopi') def rename_table(name, new_name) + clear_cache! execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}" end # Adds a new column to the named table. # See TableDefinition#column for details of the options you can use. def add_column(table_name, column_name, type, options = {}) + clear_cache! add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" add_column_options!(add_column_sql, options) @@ -925,6 +1042,7 @@ module ActiveRecord # Changes the column of a table. def change_column(table_name, column_name, type, options = {}) + clear_cache! quoted_table_name = quote_table_name(table_name) execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" @@ -935,10 +1053,12 @@ module ActiveRecord # Changes the default value of a table column. def change_column_default(table_name, column_name, default) + clear_cache! execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}" end def change_column_null(table_name, column_name, null, default = nil) + clear_cache! unless null || default.nil? execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end @@ -947,6 +1067,7 @@ module ActiveRecord # Renames a column in a table. def rename_column(table_name, column_name, new_column_name) + clear_cache! execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}" end @@ -1030,26 +1151,54 @@ module ActiveRecord end private + FEATURE_NOT_SUPPORTED = "0A000" # :nodoc: + def exec_no_cache(sql, binds) @connection.async_exec(sql) end def exec_cache(sql, binds) - unless @statements.key? sql - nextkey = @statements.next_key - @connection.prepare nextkey, sql - @statements[sql] = nextkey + begin + stmt_key = prepare_statement sql + + # Clear the queue + @connection.get_last_result + @connection.send_query_prepared(stmt_key, binds.map { |col, val| + type_cast(val, col) + }) + @connection.block + @connection.get_last_result + rescue PGError => e + # Get the PG code for the failure. Annoyingly, the code for + # prepared statements whose return value may have changed is + # FEATURE_NOT_SUPPORTED. Check here for more details: + # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573 + code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE) + if FEATURE_NOT_SUPPORTED == code + @statements.delete sql_key(sql) + retry + else + raise e + end end + end - key = @statements[sql] + # Returns the statement identifier for the client side cache + # of statements + def sql_key(sql) + "#{schema_search_path}-#{sql}" + end - # Clear the queue - @connection.get_last_result - @connection.send_query_prepared(key, binds.map { |col, val| - type_cast(val, col) - }) - @connection.block - @connection.get_last_result + # Prepare the statement if it hasn't been prepared, return + # the statement key. + def prepare_statement(sql) + sql_key = sql_key(sql) + unless @statements.key? sql_key + nextkey = @statements.next_key + @connection.prepare nextkey, sql + @statements[sql_key] = nextkey + end + @statements[sql_key] end # The internal PostgreSQL identifier of the money data type. @@ -1060,7 +1209,7 @@ module ActiveRecord # Connects to a PostgreSQL server and sets up the adapter depending on the # connected server's characteristics. def connect - @connection = PGconn.connect(*@connection_parameters) + @connection = PGconn.connect(@connection_parameters) # Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of # PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision @@ -1100,7 +1249,7 @@ module ActiveRecord # Executes a SELECT query and returns the results, performing any data type # conversions that are required to be performed here instead of in PostgreSQLColumn. def select(sql, name = nil, binds = []) - exec_query(sql, name, binds).to_a + exec_query(sql, name, binds) end def select_raw(sql, name = nil) diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb new file mode 100644 index 0000000000..962718da56 --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb @@ -0,0 +1,50 @@ +module ActiveRecord + module ConnectionAdapters + class SchemaCache + attr_reader :columns, :columns_hash, :primary_keys, :tables + attr_reader :connection + + def initialize(conn) + @connection = conn + @tables = {} + + @columns = Hash.new do |h, table_name| + h[table_name] = conn.columns(table_name) + end + + @columns_hash = Hash.new do |h, table_name| + h[table_name] = Hash[columns[table_name].map { |col| + [col.name, col] + }] + end + + @primary_keys = Hash.new do |h, table_name| + h[table_name] = table_exists?(table_name) ? conn.primary_key(table_name) : nil + end + end + + # A cached lookup for table existence. + def table_exists?(name) + return @tables[name] if @tables.key? name + + @tables[name] = connection.table_exists?(name) + end + + # Clears out internal caches + def clear! + @columns.clear + @columns_hash.clear + @primary_keys.clear + @tables.clear + end + + # Clear out internal caches for table with +table_name+. + def clear_table_cache!(table_name) + @columns.delete table_name + @columns_hash.delete table_name + @primary_keys.delete table_name + @tables.delete table_name + end + end + end +end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 0a0da0b5d3..ee5d10859c 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -1,12 +1,12 @@ require 'active_record/connection_adapters/sqlite_adapter' -gem 'sqlite3', '~> 1.3.4' +gem 'sqlite3', '~> 1.3.5' require 'sqlite3' module ActiveRecord - class Base + module ConnectionHandling # sqlite3 adapter reuses sqlite_connection. - def self.sqlite3_connection(config) # :nodoc: + def sqlite3_connection(config) # :nodoc: # Require database. unless config[:database] raise ArgumentError, "No database file specified. Missing argument: database" @@ -47,11 +47,7 @@ module ActiveRecord # Returns the current database encoding format as a string, eg: 'UTF-8' def encoding - if @connection.respond_to?(:encoding) - @connection.encoding.to_s - else - @connection.execute('PRAGMA encoding')[0]['encoding'] - end + @connection.encoding.to_s end end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb index 1932a849ee..55eca48efe 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb @@ -6,26 +6,11 @@ module ActiveRecord module ConnectionAdapters #:nodoc: class SQLiteColumn < Column #:nodoc: class << self - def string_to_binary(value) - value.gsub(/\0|\%/n) do |b| - case b - when "\0" then "%00" - when "%" then "%25" - end - end - end - def binary_to_string(value) - if value.respond_to?(:force_encoding) && value.encoding != Encoding::ASCII_8BIT + if value.encoding != Encoding::ASCII_8BIT value = value.force_encoding(Encoding::ASCII_8BIT) end - - value.gsub(/%00|%25/n) do |b| - case b - when "%00" then "\0" - when "%25" then "%" - end - end + value end end end @@ -89,10 +74,7 @@ module ActiveRecord @statements = StatementPool.new(@connection, config.fetch(:statement_limit) { 1000 }) @config = config - end - - def self.visitor_for(pool) # :nodoc: - Arel::Visitors::SQLite.new(pool) + @visitor = Arel::Visitors::SQLite.new self end def adapter_name #:nodoc: @@ -125,6 +107,11 @@ module ActiveRecord true end + # Returns true. + def supports_explain? + true + end + def requires_reloading? true end @@ -157,6 +144,10 @@ module ActiveRecord sqlite_version >= '3.1.0' end + def supports_index_sort_order? + sqlite_version >= '3.3.0' + end + def native_database_types #:nodoc: { :primary_key => default_primary_key_type, @@ -195,29 +186,40 @@ module ActiveRecord end end - if "<3".encoding_aware? - def type_cast(value, column) # :nodoc: - return value.to_f if BigDecimal === value - return super unless String === value - return super unless column && value + def type_cast(value, column) # :nodoc: + return value.to_f if BigDecimal === value + return super unless String === value + return super unless column && value - value = super - if column.type == :string && value.encoding == Encoding::ASCII_8BIT - @logger.error "Binary data inserted for `string` type on column `#{column.name}`" - value.encode! 'utf-8' - end - value - end - else - def type_cast(value, column) # :nodoc: - return super unless BigDecimal === value - - value.to_f + value = super + if column.type == :string && value.encoding == Encoding::ASCII_8BIT + @logger.error "Binary data inserted for `string` type on column `#{column.name}`" + value.encode! 'utf-8' end + value end # DATABASE STATEMENTS ====================================== + def explain(arel, binds = []) + sql = "EXPLAIN QUERY PLAN #{to_sql(arel)}" + ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds)) + end + + class ExplainPrettyPrinter + # Pretty prints the result of a EXPLAIN QUERY PLAN in a way that resembles + # the output of the SQLite shell: + # + # 0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?) (~1 rows) + # 0|1|1|SCAN TABLE posts (~100000 rows) + # + def pp(result) # :nodoc: + result.rows.map do |row| + row.join('|') + end.join("\n") + "\n" + end + end + def exec_query(sql, name = nil, binds = []) log(sql, name, binds) do @@ -304,20 +306,25 @@ module ActiveRecord # SCHEMA STATEMENTS ======================================== - def tables(name = 'SCHEMA') #:nodoc: + def tables(name = 'SCHEMA', table_name = nil) #:nodoc: sql = <<-SQL SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence' SQL + sql << " AND name = #{quote_table_name(table_name)}" if table_name exec_query(sql, name).map do |row| row['name'] end end + def table_exists?(name) + name && tables('SCHEMA', name).any? + end + # Returns an array of +SQLiteColumn+ objects for the table specified by +table_name+. - def columns(table_name, name = nil) #:nodoc: + def columns(table_name) #:nodoc: table_structure(table_name).map do |field| case field["dflt_value"] when /^null$/i @@ -413,6 +420,8 @@ module ActiveRecord self.limit = options[:limit] if options.include?(:limit) self.default = options[:default] if include_default self.null = options[:null] if options.include?(:null) + self.precision = options[:precision] if options.include?(:precision) + self.scale = options[:scale] if options.include?(:scale) end end end @@ -430,7 +439,7 @@ module ActiveRecord protected def select(sql, name = nil, binds = []) #:nodoc: - exec_query(sql, name, binds).to_a + exec_query(sql, name, binds) end def table_structure(table_name) @@ -467,6 +476,7 @@ module ActiveRecord @definition.column(column_name, column.type, :limit => column.limit, :default => column.default, + :precision => column.precision, :scale => column.scale, :null => column.null) end @definition.primary_key(primary_key(from)) if primary_key(from) diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb new file mode 100644 index 0000000000..d7746826a9 --- /dev/null +++ b/activerecord/lib/active_record/connection_handling.rb @@ -0,0 +1,96 @@ +require 'active_support/core_ext/module/delegation' + +module ActiveRecord + module ConnectionHandling + # Establishes the connection to the database. Accepts a hash as input where + # the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case) + # example for regular databases (MySQL, Postgresql, etc): + # + # ActiveRecord::Base.establish_connection( + # :adapter => "mysql", + # :host => "localhost", + # :username => "myuser", + # :password => "mypass", + # :database => "somedatabase" + # ) + # + # Example for SQLite database: + # + # ActiveRecord::Base.establish_connection( + # :adapter => "sqlite", + # :database => "path/to/dbfile" + # ) + # + # Also accepts keys as strings (for parsing from YAML for example): + # + # ActiveRecord::Base.establish_connection( + # "adapter" => "sqlite", + # "database" => "path/to/dbfile" + # ) + # + # Or a URL: + # + # ActiveRecord::Base.establish_connection( + # "postgres://myuser:mypass@localhost/somedatabase" + # ) + # + # The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError + # may be returned on an error. + def establish_connection(spec = ENV["DATABASE_URL"]) + resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new spec, configurations + spec = resolver.spec + + unless respond_to?(spec.adapter_method) + raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter" + end + + remove_connection + connection_handler.establish_connection name, spec + end + + # Returns the connection currently associated with the class. This can + # also be used to "borrow" the connection to do database work unrelated + # to any of the specific Active Records. + def connection + retrieve_connection + end + + def connection_id + Thread.current['ActiveRecord::Base.connection_id'] + end + + def connection_id=(connection_id) + Thread.current['ActiveRecord::Base.connection_id'] = connection_id + end + + # Returns the configuration of the associated connection as a hash: + # + # ActiveRecord::Base.connection_config + # # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"} + # + # Please use only for reading. + def connection_config + connection_pool.spec.config + end + + def connection_pool + connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished + end + + def retrieve_connection + connection_handler.retrieve_connection(self) + end + + # Returns true if Active Record is connected. + def connected? + connection_handler.connected?(self) + end + + def remove_connection(klass = self) + connection_handler.remove_connection(klass) + end + + delegate :clear_active_connections!, :clear_reloadable_connections!, + :clear_all_connections!, :verify_active_connections!, :to => :connection_handler + end +end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb new file mode 100644 index 0000000000..a2ce620354 --- /dev/null +++ b/activerecord/lib/active_record/core.rb @@ -0,0 +1,356 @@ +require 'active_support/concern' +require 'thread' + +module ActiveRecord + module Core + extend ActiveSupport::Concern + + included do + ## + # :singleton-method: + # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, + # which is then passed on to any new database connections made and which can be retrieved on both + # a class and instance level by calling +logger+. + config_attribute :logger, :global => true + + ## + # :singleton-method: + # Contains the database configuration - as is typically stored in config/database.yml - + # as a Hash. + # + # For example, the following database.yml... + # + # development: + # adapter: sqlite3 + # database: db/development.sqlite3 + # + # production: + # adapter: sqlite3 + # database: db/production.sqlite3 + # + # ...would result in ActiveRecord::Base.configurations to look like this: + # + # { + # 'development' => { + # 'adapter' => 'sqlite3', + # 'database' => 'db/development.sqlite3' + # }, + # 'production' => { + # 'adapter' => 'sqlite3', + # 'database' => 'db/production.sqlite3' + # } + # } + config_attribute :configurations, :global => true + self.configurations = {} + + ## + # :singleton-method: + # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling + # dates and times from the database. This is set to :utc by default. + config_attribute :default_timezone, :global => true + self.default_timezone = :utc + + ## + # :singleton-method: + # Specifies the format to use when dumping the database schema with Rails' + # Rakefile. If :sql, the schema is dumped as (potentially database- + # specific) SQL statements. If :ruby, the schema is dumped as an + # ActiveRecord::Schema file which can be loaded into any database that + # supports migrations. Use :ruby if you want to have different database + # adapters for, e.g., your development and test environments. + config_attribute :schema_format, :global => true + self.schema_format = :ruby + + ## + # :singleton-method: + # Specify whether or not to use timestamps for migration versions + config_attribute :timestamped_migrations, :global => true + self.timestamped_migrations = true + + ## + # :singleton-method: + # The connection handler + config_attribute :connection_handler + self.connection_handler = ConnectionAdapters::ConnectionHandler.new + + ## + # :singleton-method: + # Specifies wether or not has_many or has_one association option + # :dependent => :restrict raises an exception. If set to true, the + # ActiveRecord::DeleteRestrictionError exception will be raised + # along with a DEPRECATION WARNING. If set to false, an error would + # be added to the model instead. + config_attribute :dependent_restrict_raises, :global => true + self.dependent_restrict_raises = true + end + + module ClassMethods + def inherited(child_class) #:nodoc: + child_class.initialize_generated_modules + super + end + + def initialize_generated_modules + @attribute_methods_mutex = Mutex.new + + # force attribute methods to be higher in inheritance hierarchy than other generated methods + generated_attribute_methods + generated_feature_methods + end + + def generated_feature_methods + @generated_feature_methods ||= begin + mod = const_set(:GeneratedFeatureMethods, Module.new) + include mod + mod + end + end + + # Returns a string like 'Post(id:integer, title:string, body:text)' + def inspect + if self == Base + super + elsif abstract_class? + "#{super}(abstract)" + elsif table_exists? + attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', ' + "#{super}(#{attr_list})" + else + "#{super}(Table doesn't exist)" + end + end + + # Overwrite the default class equality method to provide support for association proxies. + def ===(object) + object.is_a?(self) + end + + def arel_table + @arel_table ||= Arel::Table.new(table_name, arel_engine) + end + + def arel_engine + @arel_engine ||= connection_handler.connection_pools[name] ? self : active_record_super.arel_engine + end + + private + + def relation #:nodoc: + @relation ||= Relation.new(self, arel_table) + + if finder_needs_type_condition? + @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name) + else + @relation + end + end + end + + # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with + # attributes but not yet saved (pass a hash with key names matching the associated table column names). + # In both instances, valid attribute keys are determined by the column names of the associated table -- + # hence you can't have attributes that aren't part of the table columns. + # + # +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options + # in the +options+ parameter. + # + # ==== Examples + # # Instantiates a single new object + # User.new(:first_name => 'Jamie') + # + # # Instantiates a single new object using the :admin mass-assignment security role + # User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) + # + # # Instantiates a single new object bypassing mass-assignment security + # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) + def initialize(attributes = nil, options = {}) + @attributes = self.class.initialize_attributes(self.class.column_defaults.dup) + + init_internals + + ensure_proper_type + + populate_with_current_scope_attributes + + assign_attributes(attributes, options) if attributes + + yield self if block_given? + run_callbacks :initialize + end + + # Initialize an empty model object from +coder+. +coder+ must contain + # the attributes necessary for initializing an empty model object. For + # example: + # + # class Post < ActiveRecord::Base + # end + # + # post = Post.allocate + # post.init_with('attributes' => { 'title' => 'hello world' }) + # post.title # => 'hello world' + def init_with(coder) + @attributes = self.class.initialize_attributes(coder['attributes']) + + init_internals + + @new_record = false + + run_callbacks :find + run_callbacks :initialize + + self + end + + # Duped objects have no id assigned and are treated as new records. Note + # that this is a "shallow" copy as it copies the object's attributes + # only, not its associations. The extent of a "deep" copy is application + # specific and is therefore left to the application to implement according + # to its need. + # The dup method does not preserve the timestamps (created|updated)_(at|on). + def initialize_dup(other) + cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast) + cloned_attributes.delete(self.class.primary_key) + + @attributes = cloned_attributes + @attributes[self.class.primary_key] = nil + + run_callbacks(:initialize) if _initialize_callbacks.any? + + @changed_attributes = {} + self.class.column_defaults.each do |attr, orig_value| + @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr]) + end + + @aggregation_cache = {} + @association_cache = {} + @attributes_cache = {} + + @new_record = true + + ensure_proper_type + populate_with_current_scope_attributes + super + end + + # Populate +coder+ with attributes about this record that should be + # serialized. The structure of +coder+ defined in this method is + # guaranteed to match the structure of +coder+ passed to the +init_with+ + # method. + # + # Example: + # + # class Post < ActiveRecord::Base + # end + # coder = {} + # Post.new.encode_with(coder) + # coder # => { 'id' => nil, ... } + def encode_with(coder) + coder['attributes'] = attributes + end + + # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ + # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+. + # + # Note that new records are different from any other record by definition, unless the + # other record is the receiver itself. Besides, if you fetch existing records with + # +select+ and leave the ID out, you're on your own, this predicate will return false. + # + # Note also that destroying a record preserves its ID in the model instance, so deleted + # models are still comparable. + def ==(comparison_object) + super || + comparison_object.instance_of?(self.class) && + id.present? && + comparison_object.id == id + end + alias :eql? :== + + # Delegates to id in order to allow two records of the same type and id to work with something like: + # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] + def hash + id.hash + end + + # Freeze the attributes hash such that associations are still accessible, even on destroyed records. + def freeze + @attributes.freeze; self + end + + # Returns +true+ if the attributes hash has been frozen. + def frozen? + @attributes.frozen? + end + + # Allows sort on objects + def <=>(other_object) + if other_object.is_a?(self.class) + self.to_key <=> other_object.to_key + else + nil + end + end + + # Returns +true+ if the record is read only. Records loaded through joins with piggy-back + # attributes will be marked as read only since they cannot be saved. + def readonly? + @readonly + end + + # Marks this record as read only. + def readonly! + @readonly = true + end + + # Returns the connection currently associated with the class. This can + # also be used to "borrow" the connection to do database work that isn't + # easily done without going straight to SQL. + def connection + self.class.connection + end + + # Returns the contents of the record as a nicely formatted string. + def inspect + inspection = if @attributes + self.class.column_names.collect { |name| + if has_attribute?(name) + "#{name}: #{attribute_for_inspect(name)}" + end + }.compact.join(", ") + else + "not initialized" + end + "#<#{self.class} #{inspection}>" + end + + private + + # 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, + # which significantly impacts upon performance. + # + # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here. + # + # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/ + def to_ary # :nodoc: + nil + end + + def init_internals + pk = self.class.primary_key + + @attributes[pk] = nil unless @attributes.key?(pk) + + @relation = nil + @aggregation_cache = {} + @association_cache = {} + @attributes_cache = {} + @previously_changed = {} + @changed_attributes = {} + @readonly = false + @destroyed = false + @marked_for_destruction = false + @new_record = true + end + end +end diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb index 3c7defedac..224f5276eb 100644 --- a/activerecord/lib/active_record/counter_cache.rb +++ b/activerecord/lib/active_record/counter_cache.rb @@ -19,15 +19,10 @@ module ActiveRecord counters.each do |association| has_many_association = reflect_on_association(association.to_sym) - expected_name = if has_many_association.options[:as] - has_many_association.options[:as].to_s.classify - else - self.name - end - + foreign_key = has_many_association.foreign_key.to_s child_class = has_many_association.klass belongs_to = child_class.reflect_on_all_associations(:belongs_to) - reflection = belongs_to.find { |e| e.class_name == expected_name } + reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key } counter_name = reflection.counter_cache_column stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({ @@ -65,7 +60,7 @@ module ActiveRecord # Post.update_counters [10, 15], :comment_count => 1 # # Executes the following SQL: # # UPDATE posts - # # SET comment_count = COALESCE(comment_count, 0) + 1, + # # SET comment_count = COALESCE(comment_count, 0) + 1 # # WHERE id IN (10, 15) def update_counters(id, counters) updates = counters.map do |counter_name, value| diff --git a/activerecord/lib/active_record/dynamic_finder_match.rb b/activerecord/lib/active_record/dynamic_finder_match.rb index b309df9b1b..38dbbef5fc 100644 --- a/activerecord/lib/active_record/dynamic_finder_match.rb +++ b/activerecord/lib/active_record/dynamic_finder_match.rb @@ -6,33 +6,23 @@ module ActiveRecord # class DynamicFinderMatch def self.match(method) - finder = :first - bang = false - instantiator = nil - - case method.to_s - when /^find_(all_|last_)?by_([_a-zA-Z]\w*)$/ - finder = :last if $1 == 'last_' - finder = :all if $1 == 'all_' - names = $2 - when /^find_by_([_a-zA-Z]\w*)\!$/ - bang = true - names = $1 - when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/ - instantiator = $1 == 'initialize' ? :new : :create - names = $2 - else - return nil + method = method.to_s + klass = [FindBy, FindByBang, FindOrInitializeCreateBy].find do |_klass| + _klass.matches?(method) end + klass.new(method) if klass + end - new(finder, instantiator, bang, names.split('_and_')) + def self.matches?(method) + method =~ self::METHOD_PATTERN end - def initialize(finder, instantiator, bang, attribute_names) - @finder = finder - @instantiator = instantiator - @bang = bang - @attribute_names = attribute_names + def initialize(method) + @finder = :first + @instantiator = nil + match_data = method.match(self.class::METHOD_PATTERN) + @attribute_names = match_data[-1].split("_and_") + initialize_from_match_data(match_data) end attr_reader :finder, :attribute_names, :instantiator @@ -41,16 +31,54 @@ module ActiveRecord @finder && !@instantiator end + def creator? + @finder == :first && @instantiator == :create + end + def instantiator? - @finder == :first && @instantiator + @instantiator end - def creator? - @finder == :first && @instantiator == :create + def bang? + false + end + + def valid_arguments?(arguments) + arguments.size >= @attribute_names.size end + private + + def initialize_from_match_data(match_data) + end + end + + class FindBy < DynamicFinderMatch + METHOD_PATTERN = /^find_(all_|last_)?by_([_a-zA-Z]\w*)$/ + + def initialize_from_match_data(match_data) + @finder = :last if match_data[1] == 'last_' + @finder = :all if match_data[1] == 'all_' + end + end + + class FindByBang < DynamicFinderMatch + METHOD_PATTERN = /^find_by_([_a-zA-Z]\w*)\!$/ + def bang? - @bang + true + end + end + + class FindOrInitializeCreateBy < DynamicFinderMatch + METHOD_PATTERN = /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/ + + def initialize_from_match_data(match_data) + @instantiator = match_data[1] == 'initialize' ? :new : :create + end + + def valid_arguments?(arguments) + arguments.size == 1 && arguments.first.is_a?(Hash) || super end end end diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb new file mode 100644 index 0000000000..60ce3dd4f1 --- /dev/null +++ b/activerecord/lib/active_record/dynamic_matchers.rb @@ -0,0 +1,79 @@ +module ActiveRecord + module DynamicMatchers + def respond_to?(method_id, include_private = false) + if match = DynamicFinderMatch.match(method_id) + return true if all_attributes_exists?(match.attribute_names) + elsif match = DynamicScopeMatch.match(method_id) + return true if all_attributes_exists?(match.attribute_names) + end + + super + end + + private + + # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and + # <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders + # section at the top of this file for more detailed information. + # + # It's even possible to use all the additional parameters to +find+. For example, the + # full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>. + # + # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it + # is first invoked, so that future attempts to use it do not run through method_missing. + def method_missing(method_id, *arguments, &block) + if match = (DynamicFinderMatch.match(method_id) || DynamicScopeMatch.match(method_id)) + attribute_names = match.attribute_names + super unless all_attributes_exists?(attribute_names) + unless match.valid_arguments?(arguments) + method_trace = "#{__FILE__}:#{__LINE__}:in `#{method_id}'" + backtrace = [method_trace] + caller + raise ArgumentError, "wrong number of arguments (#{arguments.size} for #{attribute_names.size})", backtrace + end + if match.respond_to?(:scope?) && match.scope? + self.class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args) + attributes = Hash[[:#{attribute_names.join(',:')}].zip(args)] # attributes = Hash[[:user_name, :password].zip(args)] + # + scoped(:conditions => attributes) # scoped(:conditions => attributes) + end # end + METHOD + send(method_id, *arguments) + elsif match.finder? + options = arguments.extract_options! + relation = options.any? ? scoped(options) : scoped + relation.send :find_by_attributes, match, attribute_names, *arguments, &block + elsif match.instantiator? + scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block + end + else + super + end + end + + # Similar in purpose to +expand_hash_conditions_for_aggregates+. + def expand_attribute_names_for_aggregates(attribute_names) + attribute_names.map { |attribute_name| + unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? + aggregate_mapping(aggregation).map do |field_attr, _| + field_attr.to_sym + end + else + attribute_name.to_sym + end + }.flatten + end + + def all_attributes_exists?(attribute_names) + (expand_attribute_names_for_aggregates(attribute_names) - + column_methods_hash.keys).empty? + end + + def aggregate_mapping(reflection) + mapping = reflection.options[:mapping] || [reflection.name, reflection.name] + mapping.first.is_a?(Array) ? mapping : [mapping] + end + + + end +end diff --git a/activerecord/lib/active_record/dynamic_scope_match.rb b/activerecord/lib/active_record/dynamic_scope_match.rb index c832e927d6..a502155aac 100644 --- a/activerecord/lib/active_record/dynamic_scope_match.rb +++ b/activerecord/lib/active_record/dynamic_scope_match.rb @@ -19,5 +19,9 @@ module ActiveRecord attr_reader :scope, :attribute_names alias :scope? :scope + + def valid_arguments?(arguments) + arguments.size >= @attribute_names.size + end end end diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index ad7d8cd63c..fc80f3081e 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -99,6 +99,16 @@ module ActiveRecord # # Read more about optimistic locking in ActiveRecord::Locking module RDoc. class StaleObjectError < ActiveRecordError + attr_reader :record, :attempted_action + + def initialize(record, attempted_action) + @record = record + @attempted_action = attempted_action + end + + def message + "Attempted to #{attempted_action} a stale object: #{record.class.name}" + end end # Raised when association is being configured improperly or @@ -169,4 +179,17 @@ module ActiveRecord @errors = errors end end + + # Raised when a primary key is needed, but there is not one specified in the schema or model. + class UnknownPrimaryKey < ActiveRecordError + attr_reader :model + + def initialize(model) + @model = model + end + + def message + "Unknown primary key for table #{model.table_name} in model #{model}." + end + end end diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb new file mode 100644 index 0000000000..01cacf6153 --- /dev/null +++ b/activerecord/lib/active_record/explain.rb @@ -0,0 +1,82 @@ +require 'active_support/core_ext/class/attribute' + +module ActiveRecord + module Explain + def self.extended(base) + # If a query takes longer than these many seconds we log its query plan + # automatically. nil disables this feature. + base.config_attribute :auto_explain_threshold_in_seconds, :global => true + end + + # If auto explain is enabled, this method triggers EXPLAIN logging for the + # queries triggered by the block if it takes more than the threshold as a + # whole. That is, the threshold is not checked against each individual + # query, but against the duration of the entire block. This approach is + # convenient for relations. + # + # The available_queries_for_explain thread variable collects the queries + # to be explained. If the value is nil, it means queries are not being + # currently collected. A false value indicates collecting is turned + # off. Otherwise it is an array of queries. + def logging_query_plan # :nodoc: + return yield unless logger + + threshold = auto_explain_threshold_in_seconds + current = Thread.current + if threshold && current[:available_queries_for_explain].nil? + begin + queries = current[:available_queries_for_explain] = [] + start = Time.now + result = yield + logger.warn(exec_explain(queries)) if Time.now - start > threshold + result + ensure + current[:available_queries_for_explain] = nil + end + else + yield + end + end + + # Relation#explain needs to be able to collect the queries regardless of + # whether auto explain is enabled. This method serves that purpose. + def collecting_queries_for_explain # :nodoc: + current = Thread.current + original, current[:available_queries_for_explain] = current[:available_queries_for_explain], [] + return yield, current[:available_queries_for_explain] + ensure + # Note that the return value above does not depend on this assigment. + current[:available_queries_for_explain] = original + end + + # Makes the adapter execute EXPLAIN for the tuples of queries and bindings. + # Returns a formatted string ready to be logged. + def exec_explain(queries) # :nodoc: + queries && queries.map do |sql, bind| + [].tap do |msg| + msg << "EXPLAIN for: #{sql}" + unless bind.empty? + bind_msg = bind.map {|col, val| [col.name, val]}.inspect + msg.last << " #{bind_msg}" + end + msg << connection.explain(sql, bind) + end.join("\n") + end.join("\n") + end + + # Silences automatic EXPLAIN logging for the duration of the block. + # + # This has high priority, no EXPLAINs will be run even if downwards + # the threshold is set to 0. + # + # As the name of the method suggests this only applies to automatic + # EXPLAINs, manual calls to +ActiveRecord::Relation#explain+ run. + def silence_auto_explain + current = Thread.current + original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false + yield + ensure + current[:available_queries_for_explain] = original + end + end +end diff --git a/activerecord/lib/active_record/explain_subscriber.rb b/activerecord/lib/active_record/explain_subscriber.rb new file mode 100644 index 0000000000..fc76410499 --- /dev/null +++ b/activerecord/lib/active_record/explain_subscriber.rb @@ -0,0 +1,21 @@ +require 'active_support/notifications' + +module ActiveRecord + class ExplainSubscriber # :nodoc: + def call(*args) + if queries = Thread.current[:available_queries_for_explain] + payload = args.last + queries << payload.values_at(:sql, :binds) unless ignore_payload?(payload) + end + end + + # SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on + # our own EXPLAINs now matter how loopingly beautiful that would be. + IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN) + def ignore_payload?(payload) + payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) + end + + ActiveSupport::Notifications.subscribe("sql.active_record", new) + end +end diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 6f1ec7f9b3..cf315b687c 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -1,16 +1,8 @@ require 'erb' - -begin - require 'psych' -rescue LoadError -end - require 'yaml' require 'zlib' require 'active_support/dependencies' -require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/logger' require 'active_support/ordered_hash' require 'active_record/fixtures/file' @@ -22,8 +14,6 @@ else end end -class FixturesFileNotFound < StandardError; end - module ActiveRecord # \Fixtures are a way of organizing data that you want to test against; in short, sample data. # @@ -391,10 +381,15 @@ module ActiveRecord @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} } - def self.find_table_name(table_name) # :nodoc: + def self.default_fixture_model_name(fixture_name) # :nodoc: ActiveRecord::Base.pluralize_table_names ? - table_name.to_s.singularize.camelize : - table_name.to_s.camelize + fixture_name.singularize.camelize : + fixture_name.camelize + end + + def self.default_fixture_table_name(fixture_name) # :nodoc: + "#{ActiveRecord::Base.table_name_prefix}"\ + "#{fixture_name.tr('/', '_')}#{ActiveRecord::Base.table_name_suffix}".to_sym end def self.reset_cache @@ -443,10 +438,8 @@ module ActiveRecord self.all_loaded_fixtures = {} def self.create_fixtures(fixtures_directory, table_names, class_names = {}) - table_names = [table_names].flatten.map { |n| n.to_s } - table_names.each { |n| - class_names[n.tr('/', '_').to_sym] = n.classify if n.include?('/') - } + table_names = Array(table_names).map(&:to_s) + class_names = class_names.stringify_keys # FIXME: Apparently JK uses this. connection = block_given? ? yield : ActiveRecord::Base.connection @@ -460,12 +453,12 @@ module ActiveRecord fixtures_map = {} fixture_files = files_to_read.map do |path| - table_name = path.tr '/', '_' + fixture_name = path - fixtures_map[path] = ActiveRecord::Fixtures.new( + fixtures_map[fixture_name] = new( # ActiveRecord::Fixtures.new connection, - table_name, - class_names[table_name.to_sym] || table_name.classify, + fixture_name, + class_names[fixture_name.to_s] || default_fixture_model_name(fixture_name), ::File.join(fixtures_directory, path)) end @@ -489,8 +482,8 @@ module ActiveRecord # Cap primary key sequences to max(pk). if connection.respond_to?(:reset_pk_sequence!) - table_names.each do |table_name| - connection.reset_pk_sequence!(table_name.tr('/', '_')) + fixture_files.each do |ff| + connection.reset_pk_sequence!(ff.table_name) end end end @@ -509,25 +502,27 @@ module ActiveRecord attr_reader :table_name, :name, :fixtures, :model_class - def initialize(connection, table_name, class_name, fixture_path) + def initialize(connection, fixture_name, class_name, fixture_path) @connection = connection - @table_name = table_name @fixture_path = fixture_path - @name = table_name # preserve fixture base name + @name = fixture_name @class_name = class_name @fixtures = ActiveSupport::OrderedHash.new - @table_name = "#{ActiveRecord::Base.table_name_prefix}#{@table_name}#{ActiveRecord::Base.table_name_suffix}" # Should be an AR::Base type class if class_name.is_a?(Class) - @table_name = class_name.table_name - @connection = class_name.connection - @model_class = class_name + @model_class = class_name else - @model_class = class_name.constantize rescue nil + @model_class = class_name.constantize rescue nil end + @connection = model_class.connection if model_class && model_class.respond_to?(:connection) + + @table_name = ( model_class.respond_to?(:table_name) ? + model_class.table_name : + self.class.default_fixture_table_name(fixture_name) ) + read_fixture_files end @@ -562,7 +557,7 @@ module ActiveRecord rows[table_name] = fixtures.map do |label, fixture| row = fixture.to_hash - if model_class && model_class < ActiveRecord::Base + if model_class && model_class < ActiveRecord::Model # fill in timestamp columns if they aren't specified and the model is set to record_timestamps if model_class.record_timestamps timestamp_column_names.each do |name| @@ -644,14 +639,6 @@ module ActiveRecord end def read_fixture_files - if ::File.file?(yaml_file_path) - read_yaml_fixture_files - else - raise FixturesFileNotFound, "Could not find #{yaml_file_path}" - end - end - - def read_yaml_fixture_files yaml_files = Dir["#{@fixture_path}/**/*.yml"].select { |f| ::File.file?(f) } + [yaml_file_path] @@ -734,20 +721,37 @@ module ActiveRecord self.use_instantiated_fixtures = false self.pre_loaded_fixtures = false - self.fixture_class_names = Hash.new do |h, table_name| - h[table_name] = ActiveRecord::Fixtures.find_table_name(table_name) + self.fixture_class_names = Hash.new do |h, fixture_name| + fixture_name = fixture_name.to_s + h[fixture_name] = ActiveRecord::Fixtures.default_fixture_model_name(fixture_name) end end module ClassMethods + # Sets the model class for a fixture when the class name cannot be inferred from the fixture name. + # + # Examples: + # + # set_fixture_class :some_fixture => SomeModel, + # 'namespaced/fixture' => Another::Model + # + # The keys must be the fixture names, that coincide with the short paths to the fixture files. + #-- + # It is also possible to pass the class name instead of the class: + # set_fixture_class 'some_fixture' => 'SomeModel' + # I think this option is redundant, i propose to deprecate it. + # Isn't it easier to always pass the class itself? + # (2011-12-20 alexeymuranov) + #++ def set_fixture_class(class_names = {}) - self.fixture_class_names = self.fixture_class_names.merge(class_names) + self.fixture_class_names = self.fixture_class_names.merge(class_names.stringify_keys) end def fixtures(*fixture_names) if fixture_names.first == :all - fixture_names = Dir["#{fixture_path}/**/*.{yml}"] - fixture_names.map! { |f| f[(fixture_path.size + 1)..-5] } + fixture_names = Dir["#{fixture_path}/**/*.yml"].map { |f| + File.basename f, '.yml' + } else fixture_names = fixture_names.flatten.map { |n| n.to_s } end @@ -778,12 +782,13 @@ module ActiveRecord end def setup_fixture_accessors(fixture_names = nil) - fixture_names = Array.wrap(fixture_names || fixture_table_names) + fixture_names = Array(fixture_names || fixture_table_names) methods = Module.new do fixture_names.each do |fixture_name| - fixture_name = fixture_name.to_s.tr('./', '_') + fixture_name = fixture_name.to_s + accessor_name = fixture_name.tr('/', '_').to_sym - define_method(fixture_name) do |*fixtures| + define_method(accessor_name) do |*fixtures| force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload @fixture_cache[fixture_name] ||= {} @@ -796,13 +801,13 @@ module ActiveRecord @fixture_cache[fixture_name][fixture] ||= @loaded_fixtures[fixture_name][fixture.to_s].find end else - raise StandardError, "No fixture with name '#{fixture}' found for table '#{fixture_name}'" + raise StandardError, "No entry named '#{fixture}' found for fixture collection '#{fixture_name}'" end end instances.size == 1 ? instances.first : instances end - private fixture_name + private accessor_name end end include methods @@ -832,6 +837,7 @@ module ActiveRecord end @fixture_cache = {} + @fixture_connections = [] @@already_loaded_fixtures ||= {} # Load fixtures once and begin transaction. @@ -842,9 +848,12 @@ module ActiveRecord @loaded_fixtures = load_fixtures @@already_loaded_fixtures[self.class] = @loaded_fixtures end - ActiveRecord::Base.connection.increment_open_transactions - ActiveRecord::Base.connection.transaction_joinable = false - ActiveRecord::Base.connection.begin_db_transaction + @fixture_connections = enlist_fixture_connections + @fixture_connections.each do |connection| + connection.increment_open_transactions + connection.transaction_joinable = false + connection.begin_db_transaction + end # Load fixtures for every test. else ActiveRecord::Fixtures.reset_cache @@ -864,13 +873,22 @@ module ActiveRecord end # Rollback changes if a transaction is active. - if run_in_transaction? && ActiveRecord::Base.connection.open_transactions != 0 - ActiveRecord::Base.connection.rollback_db_transaction - ActiveRecord::Base.connection.decrement_open_transactions + if run_in_transaction? + @fixture_connections.each do |connection| + if connection.open_transactions != 0 + connection.rollback_db_transaction + connection.decrement_open_transactions + end + end + @fixture_connections.clear end ActiveRecord::Base.clear_active_connections! end + def enlist_fixture_connections + ActiveRecord::Base.connection_handler.connection_pools.values.map(&:connection) + end + private def load_fixtures fixtures = ActiveRecord::Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names) diff --git a/activerecord/lib/active_record/fixtures/file.rb b/activerecord/lib/active_record/fixtures/file.rb index 6bad36abb9..6547791144 100644 --- a/activerecord/lib/active_record/fixtures/file.rb +++ b/activerecord/lib/active_record/fixtures/file.rb @@ -1,8 +1,3 @@ -begin - require 'psych' -rescue LoadError -end - require 'erb' require 'yaml' diff --git a/activerecord/lib/active_record/identity_map.rb b/activerecord/lib/active_record/identity_map.rb index b15b5a8133..d9777bb2f6 100644 --- a/activerecord/lib/active_record/identity_map.rb +++ b/activerecord/lib/active_record/identity_map.rb @@ -111,37 +111,18 @@ module ActiveRecord # model object. def reinit_with(coder) @attributes_cache = {} - dirty = @changed_attributes.keys - @attributes.update(coder['attributes'].except(*dirty)) + dirty = @changed_attributes.keys + attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty)) + @attributes.update(attributes) @changed_attributes.update(coder['attributes'].slice(*dirty)) @changed_attributes.delete_if{|k,v| v.eql? @attributes[k]} - set_serialized_attributes - run_callbacks :find self end class Middleware - class Body #:nodoc: - def initialize(target, original) - @target = target - @original = original - end - - def each(&block) - @target.each(&block) - end - - def close - @target.close if @target.respond_to?(:close) - ensure - IdentityMap.enabled = @original - IdentityMap.clear - end - end - def initialize(app) @app = app end @@ -149,8 +130,14 @@ module ActiveRecord def call(env) enabled = IdentityMap.enabled IdentityMap.enabled = true - status, headers, body = @app.call(env) - [status, headers, Body.new(body, enabled)] + + response = @app.call(env) + response[2] = Rack::BodyProxy.new(response[2]) do + IdentityMap.enabled = enabled + IdentityMap.clear + end + + response end end end diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb new file mode 100644 index 0000000000..eaa7deac5a --- /dev/null +++ b/activerecord/lib/active_record/inheritance.rb @@ -0,0 +1,182 @@ +require 'active_support/concern' + +module ActiveRecord + module Inheritance + extend ActiveSupport::Concern + + included do + # Determine whether to store the full constant name including namespace when using STI + config_attribute :store_full_sti_class + self.store_full_sti_class = true + end + + module ClassMethods + # True if this isn't a concrete subclass needing a STI type condition. + def descends_from_active_record? + sup = active_record_super + + if sup.abstract_class? + sup.descends_from_active_record? + elsif self == Base + false + else + [Base, Model].include?(sup) || !columns_hash.include?(inheritance_column) + end + end + + def finder_needs_type_condition? #:nodoc: + # This is like this because benchmarking justifies the strange :false stuff + :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) + end + + def symbolized_base_class + @symbolized_base_class ||= base_class.to_s.to_sym + end + + def symbolized_sti_name + @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class + end + + # Returns the base AR subclass that this class descends from. If A + # extends AR::Base, A.base_class will return A. If B descends from A + # through some arbitrarily deep hierarchy, B.base_class will return A. + # + # If B < A and C < B and if A is an abstract_class then both B.base_class + # and C.base_class would return B as the answer since A is an abstract_class. + def base_class + class_of_active_record_descendant(self) + end + + # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). + attr_accessor :abstract_class + + # Returns whether this class is an abstract class or not. + def abstract_class? + defined?(@abstract_class) && @abstract_class == true + end + + def sti_name + store_full_sti_class ? name : name.demodulize + end + + # Finder methods must instantiate through this method to work with the + # single-table inheritance model that makes it possible to create + # objects of different types from the same table. + def instantiate(record) + sti_class = find_sti_class(record[inheritance_column]) + record_id = sti_class.primary_key && record[sti_class.primary_key] + + if ActiveRecord::IdentityMap.enabled? && record_id + if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number? + record_id = record_id.to_i + end + if instance = IdentityMap.get(sti_class, record_id) + instance.reinit_with('attributes' => record) + else + instance = sti_class.allocate.init_with('attributes' => record) + IdentityMap.add(instance) + end + else + instance = sti_class.allocate.init_with('attributes' => record) + end + + instance + end + + # For internal use. + # + # If this class includes ActiveRecord::Model then it won't have a + # superclass. So this provides a way to get to the 'root' (ActiveRecord::Model). + def active_record_super #:nodoc: + superclass < Model ? superclass : Model + end + + protected + + # Returns the class descending directly from ActiveRecord::Base or an + # abstract class, if any, in the inheritance hierarchy. + def class_of_active_record_descendant(klass) + unless klass < Model + raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" + end + + sup = klass.active_record_super + if [Base, Model].include?(klass) || [Base, Model].include?(sup) || sup.abstract_class? + klass + else + class_of_active_record_descendant(sup) + end + end + + # Returns the class type of the record using the current module as a prefix. So descendants of + # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. + def compute_type(type_name) + if type_name.match(/^::/) + # If the type is prefixed with a scope operator then we assume that + # the type_name is an absolute reference. + ActiveSupport::Dependencies.constantize(type_name) + else + # Build a list of candidates to search for + candidates = [] + name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } + candidates << type_name + + candidates.each do |candidate| + begin + constant = ActiveSupport::Dependencies.constantize(candidate) + return constant if candidate == constant.to_s + rescue NameError => e + # We don't want to swallow NoMethodError < NameError errors + raise e unless e.instance_of?(NameError) + end + end + + raise NameError, "uninitialized constant #{candidates.first}" + end + end + + private + + def find_sti_class(type_name) + if type_name.blank? || !columns_hash.include?(inheritance_column) + self + else + begin + if store_full_sti_class + ActiveSupport::Dependencies.constantize(type_name) + else + compute_type(type_name) + end + rescue NameError + raise SubclassNotFound, + "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " + + "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + + "Please rename this column if you didn't intend it to be used for storing the inheritance class " + + "or overwrite #{name}.inheritance_column to use another column for that information." + end + end + end + + def type_condition(table = arel_table) + sti_column = table[inheritance_column.to_sym] + sti_names = ([self] + descendants).map { |model| model.sti_name } + + sti_column.in(sti_names) + end + end + + private + + # Sets the attribute used for single table inheritance to this class name if this is not the + # ActiveRecord::Base descendant. + # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to + # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. + # No such attribute would be set for objects of the Message class in that example. + def ensure_proper_type + klass = self.class + if klass.finder_needs_type_condition? + write_attribute(klass.inheritance_column, klass.sti_name) + end + end + end +end diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb new file mode 100644 index 0000000000..2c42f4cca5 --- /dev/null +++ b/activerecord/lib/active_record/integration.rb @@ -0,0 +1,49 @@ +module ActiveRecord + module Integration + # Returns a String, which Action Pack uses for constructing an URL to this + # object. The default implementation returns this record's id as a String, + # or nil if this record's unsaved. + # + # For example, suppose that you have a User model, and that you have a + # <tt>resources :users</tt> route. Normally, +user_path+ will + # construct a path with the user object's 'id' in it: + # + # user = User.find_by_name('Phusion') + # user_path(user) # => "/users/1" + # + # You can override +to_param+ in your model to make +user_path+ construct + # a path using the user's name instead of the user's id: + # + # class User < ActiveRecord::Base + # def to_param # overridden + # name + # end + # end + # + # user = User.find_by_name('Phusion') + # user_path(user) # => "/users/Phusion" + def to_param + # We can't use alias_method here, because method 'id' optimizes itself on the fly. + id && id.to_s # Be sure to stringify the id for routes + end + + # Returns a cache key that can be used to identify this record. + # + # ==== Examples + # + # Product.new.cache_key # => "products/new" + # Product.find(5).cache_key # => "products/5" (updated_at not available) + # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available) + def cache_key + case + when new_record? + "#{self.class.model_name.cache_key}/new" + when timestamp = self[:updated_at] + timestamp = timestamp.utc.to_s(:number) + "#{self.class.model_name.cache_key}/#{id}-#{timestamp}" + else + "#{self.class.model_name.cache_key}/#{id}" + end + end + end +end diff --git a/activerecord/lib/active_record/locale/en.yml b/activerecord/lib/active_record/locale/en.yml index 44328f63b6..896132d566 100644 --- a/activerecord/lib/active_record/locale/en.yml +++ b/activerecord/lib/active_record/locale/en.yml @@ -10,6 +10,9 @@ en: messages: taken: "has already been taken" record_invalid: "Validation failed: %{errors}" + restrict_dependent_destroy: + one: "Cannot delete record because a dependent %{record} exists" + many: "Cannot delete record because dependent %{record} exist" # Append your own errors here or at the model/attributes scope. # You can define own errors for models or model attributes. diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index d9ad7e4132..4d73cdd37a 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -37,21 +37,22 @@ module ActiveRecord # You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, # or otherwise apply the business logic needed to resolve the conflict. # - # You must ensure that your database schema defaults the +lock_version+ column to 0. + # This locking mechanism will function inside a single Ruby process. To make it work across all + # web requests, the recommended approach is to add +lock_version+ as a hidden field to your form. # # This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>. - # To override the name of the +lock_version+ column, invoke the <tt>set_locking_column</tt> method. - # This method uses the same syntax as <tt>set_table_name</tt> + # To override the name of the +lock_version+ column, set the <tt>locking_column</tt> class attribute: + # + # class Person < ActiveRecord::Base + # self.locking_column = :lock_person + # end + # module Optimistic extend ActiveSupport::Concern included do - cattr_accessor :lock_optimistically, :instance_writer => false + config_attribute :lock_optimistically, :global => true self.lock_optimistically = true - - class << self - alias_method :locking_column=, :set_locking_column - end end def locking_enabled? #:nodoc: @@ -65,21 +66,6 @@ module ActiveRecord send(lock_col + '=', previous_lock_value + 1) end - def attributes_from_column_definition - result = super - - # If the locking column has no default value set, - # start the lock version at zero. Note we can't use - # <tt>locking_enabled?</tt> at this point as - # <tt>@attributes</tt> may not have been initialized yet. - - if result.key?(self.class.locking_column) && lock_optimistically - result[self.class.locking_column] ||= 0 - end - - result - end - def update(attribute_names = @attributes.keys) #:nodoc: return super unless locking_enabled? return 0 if attribute_names.empty? @@ -103,7 +89,7 @@ module ActiveRecord affected_rows = connection.update stmt unless affected_rows == 1 - raise ActiveRecord::StaleObjectError, "Attempted to update a stale object: #{self.class.name}" + raise ActiveRecord::StaleObjectError.new(self, "update") end affected_rows @@ -127,7 +113,7 @@ module ActiveRecord affected_rows = self.class.unscoped.where(predicate).delete_all unless affected_rows == 1 - raise ActiveRecord::StaleObjectError, "Attempted to delete a stale object: #{self.class.name}" + raise ActiveRecord::StaleObjectError.new(self, "destroy") end end @@ -146,14 +132,15 @@ module ActiveRecord end # Set the column to use for optimistic locking. Defaults to +lock_version+. - def set_locking_column(value = nil, &block) - define_attr_method :locking_column, value, &block - value + def locking_column=(value) + @original_locking_column = @locking_column if defined?(@locking_column) + @locking_column = value.to_s end # The version column used for optimistic locking. Defaults to +lock_version+. def locking_column - reset_locking_column + reset_locking_column unless defined?(@locking_column) + @locking_column end # Quote the column name used for optimistic locking. @@ -163,7 +150,7 @@ module ActiveRecord # Reset the column used for optimistic locking back to the +lock_version+ default. def reset_locking_column - set_locking_column DEFAULT_LOCKING_COLUMN + self.locking_column = DEFAULT_LOCKING_COLUMN end # Make sure the lock version column gets updated when counters are @@ -172,6 +159,18 @@ module ActiveRecord counters = counters.merge(locking_column => 1) if locking_enabled? super end + + # If the locking column has no default value set, + # start the lock version at zero. Note we can't use + # <tt>locking_enabled?</tt> at this point as + # <tt>@attributes</tt> may not have been initialized yet. + def initialize_attributes(attributes) #:nodoc: + if attributes.key?(locking_column) && lock_optimistically + attributes[locking_column] ||= 0 + end + + attributes + end end end end diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb index 66994e4797..58af92f0b1 100644 --- a/activerecord/lib/active_record/locking/pessimistic.rb +++ b/activerecord/lib/active_record/locking/pessimistic.rb @@ -38,6 +38,18 @@ module ActiveRecord # account2.save! # end # + # You can start a transaction and acquire the lock in one go by calling + # <tt>with_lock</tt> with a block. The block is called from within + # a transaction, the object is already locked. Example: + # + # account = Account.first + # account.with_lock do + # # This block is called within a transaction, + # # account is already locked. + # account.balance -= 100 + # account.save! + # end + # # Database-specific information on row locking: # MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html # PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE @@ -50,6 +62,16 @@ module ActiveRecord reload(:lock => lock) if persisted? self end + + # Wraps the passed block in a transaction, locking the object + # before yielding. You pass can the SQL locking clause + # as argument (see <tt>lock!</tt>). + def with_lock(lock = true) + transaction do + lock!(lock) + yield + end + end end end end diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb index 3a015ee8c2..a25f2c7bca 100644 --- a/activerecord/lib/active_record/log_subscriber.rb +++ b/activerecord/lib/active_record/log_subscriber.rb @@ -26,9 +26,9 @@ module ActiveRecord return if 'SCHEMA' == payload[:name] - name = '%s (%.1fms)' % [payload[:name], event.duration] - sql = payload[:sql].squeeze(' ') - binds = nil + name = '%s (%.1fms)' % [payload[:name], event.duration] + sql = payload[:sql].squeeze(' ') + binds = nil unless (payload[:binds] || []).empty? binds = " " + payload[:binds].map { |col,v| diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 7166f1b82a..2a9139749d 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -1,6 +1,8 @@ require "active_support/core_ext/module/delegation" require "active_support/core_ext/class/attribute_accessors" -require "active_support/core_ext/array/wrap" +require 'active_support/deprecation' +require 'active_record/schema_migration' +require 'set' module ActiveRecord # Exception that can be raised to stop migrations from going backwards. @@ -112,12 +114,13 @@ module ActiveRecord # a column but keeps the type and content. # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes # the column to a different type using the same parameters as add_column. - # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named - # +column_name+ from the table called +table_name+. + # * <tt>remove_column(table_name, column_names)</tt>: Removes the column listed in + # +column_names+ from the table called +table_name+. # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index # with the name of the column. Other options include - # <tt>:name</tt> and <tt>:unique</tt> (e.g. - # <tt>{ :name => "users_name_index", :unique => true }</tt>). + # <tt>:name</tt>, <tt>:unique</tt> (e.g. + # <tt>{ :name => "users_name_index", :unique => true }</tt>) and <tt>:order</tt> + # (e.g. { :order => {:name => :desc} }</tt>). # * <tt>remove_index(table_name, :column => column_name)</tt>: Removes the index # specified by +column_name+. # * <tt>remove_index(table_name, :name => index_name)</tt>: Removes the index @@ -301,7 +304,7 @@ module ActiveRecord # # class TenderloveMigration < ActiveRecord::Migration # def change - # create_table(:horses) do + # create_table(:horses) do |t| # t.column :content, :text # t.column :remind_at, :datetime # end @@ -340,16 +343,28 @@ module ActiveRecord attr_accessor :name, :version - def initialize - @name = self.class.name - @version = nil + def initialize(name = self.class.name, version = nil) + @name = name + @version = version @connection = nil + @reverting = false end # instantiate the delegate object after initialize is defined self.verbose = true self.delegate = new + def revert + @reverting = true + yield + ensure + @reverting = false + end + + def reverting? + @reverting + end + def up self.class.delegate = self return unless self.class.respond_to?(:up) @@ -383,9 +398,11 @@ module ActiveRecord end @connection = conn time = Benchmark.measure { - recorder.inverse.each do |cmd, args| - send(cmd, *args) - end + self.revert { + recorder.inverse.each do |cmd, args| + send(cmd, *args) + end + } } else time = Benchmark.measure { change } @@ -440,8 +457,11 @@ module ActiveRecord arg_list = arguments.map{ |a| a.inspect } * ', ' say_with_time "#{method}(#{arg_list})" do - unless arguments.empty? || method == :execute - arguments[0] = Migrator.proper_table_name(arguments.first) + unless reverting? + unless arguments.empty? || method == :execute + arguments[0] = Migrator.proper_table_name(arguments.first) + arguments[1] = Migrator.proper_table_name(arguments.second) if method == :rename_table + end end return super unless connection.respond_to?(method) connection.send(method, *arguments, &block) @@ -455,26 +475,28 @@ module ActiveRecord destination_migrations = ActiveRecord::Migrator.migrations(destination) last = destination_migrations.last - sources.each do |name, path| + sources.each do |scope, path| source_migrations = ActiveRecord::Migrator.migrations(path) source_migrations.each do |migration| source = File.read(migration.filename) - source = "# This migration comes from #{name} (originally #{migration.version})\n#{source}" + source = "# This migration comes from #{scope} (originally #{migration.version})\n#{source}" if duplicate = destination_migrations.detect { |m| m.name == migration.name } - options[:on_skip].call(name, migration) if File.read(duplicate.filename) != source && options[:on_skip] + if options[:on_skip] && duplicate.scope != scope.to_s + options[:on_skip].call(scope, migration) + end next end migration.version = next_migration_number(last ? last.version + 1 : 0).to_i - new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.rb") + new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb") old_path, migration.filename = migration.filename, new_path last = migration - FileUtils.cp(old_path, migration.filename) + File.open(migration.filename, "w") { |f| f.write source } copied << migration - options[:on_copy].call(name, migration, old_path) if options[:on_copy] + options[:on_copy].call(scope, migration, old_path) if options[:on_copy] destination_migrations << migration end end @@ -493,9 +515,9 @@ module ActiveRecord # MigrationProxy is used to defer loading of the actual migration classes # until they are needed - class MigrationProxy < Struct.new(:name, :version, :filename) + class MigrationProxy < Struct.new(:name, :version, :filename, :scope) - def initialize(name, version, filename) + def initialize(name, version, filename, scope) super @migration = nil end @@ -504,7 +526,7 @@ module ActiveRecord File.basename(filename) end - delegate :migrate, :announce, :write, :to=>:migration + delegate :migrate, :announce, :write, :to => :migration private @@ -524,16 +546,16 @@ module ActiveRecord attr_writer :migrations_paths alias :migrations_path= :migrations_paths= - def migrate(migrations_paths, target_version = nil) + def migrate(migrations_paths, target_version = nil, &block) case - when target_version.nil? - up(migrations_paths, target_version) - when current_version == 0 && target_version == 0 - [] - when current_version > target_version - down(migrations_paths, target_version) - else - up(migrations_paths, target_version) + when target_version.nil? + up(migrations_paths, target_version, &block) + when current_version == 0 && target_version == 0 + [] + when current_version > target_version + down(migrations_paths, target_version, &block) + else + up(migrations_paths, target_version, &block) end end @@ -546,24 +568,33 @@ module ActiveRecord end def up(migrations_paths, target_version = nil) - self.new(:up, migrations_paths, target_version).migrate + migrations = migrations(migrations_paths) + migrations.select! { |m| yield m } if block_given? + + self.new(:up, migrations, target_version).migrate end - def down(migrations_paths, target_version = nil) - self.new(:down, migrations_paths, target_version).migrate + def down(migrations_paths, target_version = nil, &block) + migrations = migrations(migrations_paths) + migrations.select! { |m| yield m } if block_given? + + self.new(:down, migrations, target_version).migrate end def run(direction, migrations_paths, target_version) - self.new(direction, migrations_paths, target_version).run + self.new(direction, migrations(migrations_paths), target_version).run + end + + def open(migrations_paths) + self.new(:up, migrations(migrations_paths), nil) end def schema_migrations_table_name - Base.table_name_prefix + 'schema_migrations' + Base.table_name_suffix + SchemaMigration.table_name end def get_all_versions - table = Arel::Table.new(schema_migrations_table_name) - Base.connection.select_values(table.project(table['version'])).map{ |v| v.to_i }.sort + SchemaMigration.all.map { |x| x.version.to_i }.sort end def current_version @@ -583,7 +614,7 @@ module ActiveRecord def migrations_paths @migrations_paths ||= ['db/migrate'] # just to not break things if someone uses: migration_path = some_string - Array.wrap(@migrations_paths) + Array(@migrations_paths) end def migrations_path @@ -591,25 +622,18 @@ module ActiveRecord end def migrations(paths) - paths = Array.wrap(paths) - - files = Dir[*paths.map { |p| "#{p}/[0-9]*_*.rb" }] + paths = Array(paths) - seen = Hash.new false + files = Dir[*paths.map { |p| "#{p}/**/[0-9]*_*.rb" }] migrations = files.map do |file| - version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first + version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?.rb/).first raise IllegalMigrationNameError.new(file) unless version version = version.to_i name = name.camelize - raise DuplicateMigrationVersionError.new(version) if seen[version] - raise DuplicateMigrationNameError.new(name) if seen[name] - - seen[version] = seen[name] = true - - MigrationProxy.new(name, version, file) + MigrationProxy.new(name, version, file, scope) end migrations.sort_by(&:version) @@ -618,7 +642,7 @@ module ActiveRecord private def move(direction, migrations_paths, steps) - migrator = self.new(direction, migrations_paths) + migrator = self.new(direction, migrations(migrations_paths)) start_index = migrator.migrations.index(migrator.current_migration) if start_index @@ -629,19 +653,33 @@ module ActiveRecord end end - def initialize(direction, migrations_paths, target_version = nil) + def initialize(direction, migrations, target_version = nil) raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations? - Base.connection.initialize_schema_migrations_table - @direction, @migrations_paths, @target_version = direction, migrations_paths, target_version + + @direction = direction + @target_version = target_version + @migrated_versions = nil + + if Array(migrations).grep(String).empty? + @migrations = migrations + else + ActiveSupport::Deprecation.warn "instantiate this class with a list of migrations" + @migrations = self.class.migrations(migrations) + end + + validate(@migrations) + + ActiveRecord::SchemaMigration.create_table end def current_version - migrated.last || 0 + migrated.sort.last || 0 end def current_migration migrations.detect { |m| m.version == current_version } end + alias :current :current_migration def run target = migrations.detect { |m| m.version == @target_version } @@ -653,96 +691,108 @@ module ActiveRecord end def migrate - current = migrations.detect { |m| m.version == current_version } - target = migrations.detect { |m| m.version == @target_version } - - if target.nil? && @target_version && @target_version > 0 + if !target && @target_version && @target_version > 0 raise UnknownMigrationVersionError.new(@target_version) end - start = up? ? 0 : (migrations.index(current) || 0) - finish = migrations.index(target) || migrations.size - 1 - runnable = migrations[start..finish] + running = runnable - # skip the last migration if we're headed down, but not ALL the way down - runnable.pop if down? && target + if block_given? + ActiveSupport::Deprecation.warn(<<-eomsg) +block argument to migrate is deprecated, please filter migrations before constructing the migrator + eomsg + running.select! { |m| yield m } + end - ran = [] - runnable.each do |migration| + running.each do |migration| Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger - seen = migrated.include?(migration.version.to_i) - - # On our way up, we skip migrating the ones we've already migrated - next if up? && seen - - # On our way down, we skip reverting the ones we've never migrated - if down? && !seen - migration.announce 'never migrated, skipping'; migration.write - next - end - begin ddl_transaction do migration.migrate(@direction) record_version_state_after_migrating(migration.version) end - ran << migration rescue => e canceled_msg = Base.connection.supports_ddl_transactions? ? "this and " : "" raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace end end - ran end - def migrations - @migrations ||= begin - migrations = self.class.migrations(@migrations_paths) - down? ? migrations.reverse : migrations + def runnable + runnable = migrations[start..finish] + if up? + runnable.reject { |m| ran?(m) } + else + # skip the last migration if we're headed down, but not ALL the way down + runnable.pop if target + runnable.find_all { |m| ran?(m) } end end + def migrations + down? ? @migrations.reverse : @migrations.sort_by(&:version) + end + def pending_migrations already_migrated = migrated - migrations.reject { |m| already_migrated.include?(m.version.to_i) } + migrations.reject { |m| already_migrated.include?(m.version) } end def migrated - @migrated_versions ||= self.class.get_all_versions + @migrated_versions ||= Set.new(self.class.get_all_versions) end private - def record_version_state_after_migrating(version) - table = Arel::Table.new(self.class.schema_migrations_table_name) - - @migrated_versions ||= [] - if down? - @migrated_versions.delete(version) - stmt = table.where(table["version"].eq(version.to_s)).compile_delete - Base.connection.delete stmt - else - @migrated_versions.push(version).sort! - stmt = table.compile_insert table["version"] => version.to_s - Base.connection.insert stmt - end - end + def ran?(migration) + migrated.include?(migration.version.to_i) + end - def up? - @direction == :up - end + def target + migrations.detect { |m| m.version == @target_version } + end + + def finish + migrations.index(target) || migrations.size - 1 + end - def down? - @direction == :down + def start + up? ? 0 : (migrations.index(current) || 0) + end + + def validate(migrations) + name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 } + raise DuplicateMigrationNameError.new(name) if name + + version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 } + raise DuplicateMigrationVersionError.new(version) if version + end + + def record_version_state_after_migrating(version) + if down? + migrated.delete(version) + ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all + else + migrated << version + ActiveRecord::SchemaMigration.create!(:version => version.to_s) end + end - # Wrap the migration in a transaction only if supported by the adapter. - def ddl_transaction(&block) - if Base.connection.supports_ddl_transactions? - Base.transaction { block.call } - else - block.call - end + def up? + @direction == :up + end + + def down? + @direction == :down + end + + # Wrap the migration in a transaction only if supported by the adapter. + def ddl_transaction + if Base.connection.supports_ddl_transactions? + Base.transaction { yield } + else + yield end + end end end diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb index ffee5a081a..96b62fdd61 100644 --- a/activerecord/lib/active_record/migration/command_recorder.rb +++ b/activerecord/lib/active_record/migration/command_recorder.rb @@ -8,11 +8,14 @@ module ActiveRecord # * add_index # * add_timestamps # * create_table + # * create_join_table # * remove_timestamps # * rename_column # * rename_index # * rename_table class CommandRecorder + include JoinTable + attr_accessor :commands, :delegate def initialize(delegate = nil) @@ -48,7 +51,7 @@ module ActiveRecord super || delegate.respond_to?(*args) end - [:create_table, :change_table, :rename_table, :add_column, :remove_column, :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps, :change_column, :change_column_default].each do |method| + [:create_table, :create_join_table, :change_table, :rename_table, :add_column, :remove_column, :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps, :change_column, :change_column_default].each do |method| class_eval <<-EOV, __FILE__, __LINE__ + 1 def #{method}(*args) # def create_table(*args) record(:"#{method}", args) # record(:create_table, args) @@ -59,7 +62,13 @@ module ActiveRecord private def invert_create_table(args) - [:drop_table, args] + [:drop_table, [args.first]] + end + + def invert_create_join_table(args) + table_name = find_join_table_name(*args) + + [:drop_table, [table_name]] end def invert_rename_table(args) @@ -99,7 +108,6 @@ module ActiveRecord rescue NoMethodError => e raise e, e.message.sub(/ for #<.*$/, " via proxy for #{@delegate}") end - end end end diff --git a/activerecord/lib/active_record/migration/join_table.rb b/activerecord/lib/active_record/migration/join_table.rb new file mode 100644 index 0000000000..01a580781b --- /dev/null +++ b/activerecord/lib/active_record/migration/join_table.rb @@ -0,0 +1,17 @@ +module ActiveRecord + class Migration + module JoinTable #:nodoc: + private + + def find_join_table_name(table_1, table_2, options = {}) + options.delete(:table_name) { join_table_name(table_1, table_2) } + end + + def join_table_name(table_1, table_2) + tables_names = [table_1, table_2].map(&:to_s).sort + + tables_names.join("_").to_sym + end + end + end +end diff --git a/activerecord/lib/active_record/model.rb b/activerecord/lib/active_record/model.rb new file mode 100644 index 0000000000..86de5ab2fa --- /dev/null +++ b/activerecord/lib/active_record/model.rb @@ -0,0 +1,109 @@ +require 'active_support/deprecation' + +module ActiveRecord + # <tt>ActiveRecord::Model</tt> can be included into a class to add Active Record persistence. + # This is an alternative to inheriting from <tt>ActiveRecord::Base</tt>. Example: + # + # class Post + # include ActiveRecord::Model + # end + # + module Model + module ClassMethods #:nodoc: + include ActiveSupport::Callbacks::ClassMethods + include ActiveModel::Naming + include QueryCache::ClassMethods + include ActiveSupport::Benchmarkable + include ActiveSupport::DescendantsTracker + + include Querying + include Translation + include DynamicMatchers + include CounterCache + include Explain + include ConnectionHandling + end + + def self.included(base) + return if base.singleton_class < ClassMethods + + base.class_eval do + extend ClassMethods + Callbacks::Register.setup(self) + initialize_generated_modules unless self == Base + end + end + + extend ActiveModel::Configuration + extend ActiveModel::Callbacks + extend ActiveModel::MassAssignmentSecurity::ClassMethods + extend ActiveModel::AttributeMethods::ClassMethods + extend Callbacks::Register + extend Explain + extend ConnectionHandling + + def self.extend(*modules) + ClassMethods.send(:include, *modules) + end + + include Persistence + include ReadonlyAttributes + include ModelSchema + include Inheritance + include Scoping + include Sanitization + include Integration + include AttributeAssignment + include ActiveModel::Conversion + include Validations + include Locking::Optimistic, Locking::Pessimistic + include AttributeMethods + include Callbacks, ActiveModel::Observing, Timestamp + include Associations + include IdentityMap + include ActiveModel::SecurePassword + include AutosaveAssociation, NestedAttributes + include Aggregations, Transactions, Reflection, Serialization, Store + include Core + + class << self + def arel_engine + self + end + + def abstract_class? + false + end + + def inheritance_column + 'type' + end + end + + module DeprecationProxy #:nodoc: + class << self + instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$|^instance_eval$/ } + + def method_missing(name, *args, &block) + if Model.respond_to?(name) + Model.send(name, *args, &block) + else + ActiveSupport::Deprecation.warn( + "The object passed to the active_record load hook was previously ActiveRecord::Base " \ + "(a Class). Now it is ActiveRecord::Model (a Module). You have called `#{name}' which " \ + "is only defined on ActiveRecord::Base. Please change your code so that it works with " \ + "a module rather than a class. (Model is included in Base, so anything added to Model " \ + "will be available on Base as well.)" + ) + Base.send(name, *args, &block) + end + end + + alias send method_missing + end + end + end + + # Load Base at this point, because the active_record load hook is run in that file. + Base +end diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb new file mode 100644 index 0000000000..61f82af0c3 --- /dev/null +++ b/activerecord/lib/active_record/model_schema.rb @@ -0,0 +1,307 @@ +require 'active_support/concern' +require 'active_support/core_ext/class/attribute_accessors' + +module ActiveRecord + module ModelSchema + extend ActiveSupport::Concern + + included do + ## + # :singleton-method: + # Accessor for the prefix type that will be prepended to every primary key column name. + # The options are :table_name and :table_name_with_underscore. If the first is specified, + # the Product class will look for "productid" instead of "id" as the primary column. If the + # latter is specified, the Product class will look for "product_id" instead of "id". Remember + # that this is a global setting for all Active Records. + config_attribute :primary_key_prefix_type, :global => true + + ## + # :singleton-method: + # Accessor for the name of the prefix string to prepend to every table name. So if set + # to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people", + # etc. This is a convenient way of creating a namespace for tables in a shared database. + # By default, the prefix is the empty string. + # + # If you are organising your models within modules you can add a prefix to the models within + # a namespace by defining a singleton method in the parent module called table_name_prefix which + # returns your chosen prefix. + config_attribute :table_name_prefix + self.table_name_prefix = "" + + ## + # :singleton-method: + # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", + # "people_basecamp"). By default, the suffix is the empty string. + config_attribute :table_name_suffix + self.table_name_suffix = "" + + ## + # :singleton-method: + # Indicates whether table names should be the pluralized versions of the corresponding class names. + # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. + # See table_name for the full rules on table/class naming. This is true, by default. + config_attribute :pluralize_table_names + self.pluralize_table_names = true + end + + module ClassMethods + # Guesses the table name (in forced lower-case) based on the name of the class in the + # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy + # looks like: Reply < Message < ActiveRecord::Base, then Message is used + # to guess the table name even when called on Reply. The rules used to do the guess + # are handled by the Inflector class in Active Support, which knows almost all common + # English inflections. You can add new inflections in config/initializers/inflections.rb. + # + # Nested classes are given table names prefixed by the singular form of + # the parent's table name. Enclosing modules are not considered. + # + # ==== Examples + # + # class Invoice < ActiveRecord::Base + # end + # + # file class table_name + # invoice.rb Invoice invoices + # + # class Invoice < ActiveRecord::Base + # class Lineitem < ActiveRecord::Base + # end + # end + # + # file class table_name + # invoice.rb Invoice::Lineitem invoice_lineitems + # + # module Invoice + # class Lineitem < ActiveRecord::Base + # end + # end + # + # file class table_name + # invoice/lineitem.rb Invoice::Lineitem lineitems + # + # Additionally, the class-level +table_name_prefix+ is prepended and the + # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix, + # the table name guess for an Invoice class becomes "myapp_invoices". + # Invoice::Lineitem becomes "myapp_invoice_lineitems". + # + # You can also set your own table name explicitly: + # + # class Mouse < ActiveRecord::Base + # self.table_name = "mice" + # end + # + # Alternatively, you can override the table_name method to define your + # own computation. (Possibly using <tt>super</tt> to manipulate the default + # table name.) Example: + # + # class Post < ActiveRecord::Base + # def self.table_name + # "special_" + super + # end + # end + # Post.table_name # => "special_posts" + def table_name + reset_table_name unless defined?(@table_name) + @table_name + end + + # Sets the table name explicitly. Example: + # + # class Project < ActiveRecord::Base + # self.table_name = "project" + # end + # + # You can also just define your own <tt>self.table_name</tt> method; see + # the documentation for ActiveRecord::Base#table_name. + def table_name=(value) + @original_table_name = @table_name if defined?(@table_name) + @table_name = value && value.to_s + @quoted_table_name = nil + @arel_table = nil + @relation = Relation.new(self, arel_table) + end + + # Returns a quoted version of the table name, used to construct SQL statements. + def quoted_table_name + @quoted_table_name ||= connection.quote_table_name(table_name) + end + + # Computes the table name, (re)sets it internally, and returns it. + def reset_table_name #:nodoc: + if abstract_class? + self.table_name = if active_record_super == Base || active_record_super.abstract_class? + nil + else + active_record_super.table_name + end + elsif active_record_super.abstract_class? + self.table_name = active_record_super.table_name || compute_table_name + else + self.table_name = compute_table_name + end + end + + def full_table_name_prefix #:nodoc: + (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix + end + + # The name of the column containing the object's class when Single Table Inheritance is used + def inheritance_column + (@inheritance_column ||= nil) || active_record_super.inheritance_column + end + + # Sets the value of inheritance_column + def inheritance_column=(value) + @original_inheritance_column = inheritance_column + @inheritance_column = value.to_s + end + + def sequence_name + if base_class == self + @sequence_name ||= reset_sequence_name + else + (@sequence_name ||= nil) || base_class.sequence_name + end + end + + def reset_sequence_name #:nodoc: + self.sequence_name = connection.default_sequence_name(table_name, primary_key) + end + + # Sets the name of the sequence to use when generating ids to the given + # value, or (if the value is nil or false) to the value returned by the + # given block. This is required for Oracle and is useful for any + # database which relies on sequences for primary key generation. + # + # If a sequence name is not explicitly set when using Oracle or Firebird, + # it will default to the commonly used pattern of: #{table_name}_seq + # + # If a sequence name is not explicitly set when using PostgreSQL, it + # will discover the sequence corresponding to your primary key for you. + # + # class Project < ActiveRecord::Base + # self.sequence_name = "projectseq" # default would have been "project_seq" + # end + def sequence_name=(value) + @original_sequence_name = @sequence_name if defined?(@sequence_name) + @sequence_name = value.to_s + end + + # Indicates whether the table associated with this class exists + def table_exists? + connection.schema_cache.table_exists?(table_name) + end + + # Returns an array of column objects for the table associated with this class. + def columns + @columns ||= connection.schema_cache.columns[table_name].map do |col| + col = col.dup + col.primary = (col.name == primary_key) + col + end + end + + # Returns a hash of column objects for the table associated with this class. + def columns_hash + @columns_hash ||= Hash[columns.map { |c| [c.name, c] }] + end + + # Returns a hash where the keys are column names and the values are + # default values when instantiating the AR object for this table. + def column_defaults + @column_defaults ||= Hash[columns.map { |c| [c.name, c.default] }] + end + + # Returns an array of column names as strings. + def column_names + @column_names ||= columns.map { |column| column.name } + end + + # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", + # and columns used for single table inheritance have been removed. + def content_columns + @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column } + end + + # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key + # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute + # is available. + def column_methods_hash #:nodoc: + @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr| + attr_name = attr.to_s + methods[attr.to_sym] = attr_name + methods["#{attr}=".to_sym] = attr_name + methods["#{attr}?".to_sym] = attr_name + methods["#{attr}_before_type_cast".to_sym] = attr_name + methods + end + end + + # Resets all the cached information about columns, which will cause them + # to be reloaded on the next request. + # + # The most common usage pattern for this method is probably in a migration, + # when just after creating a table you want to populate it with some default + # values, eg: + # + # class CreateJobLevels < ActiveRecord::Migration + # def up + # create_table :job_levels do |t| + # t.integer :id + # t.string :name + # + # t.timestamps + # end + # + # JobLevel.reset_column_information + # %w{assistant executive manager director}.each do |type| + # JobLevel.create(:name => type) + # end + # end + # + # def down + # drop_table :job_levels + # end + # end + def reset_column_information + connection.clear_cache! + undefine_attribute_methods + connection.schema_cache.clear_table_cache!(table_name) if table_exists? + + @column_names = @content_columns = @column_defaults = @columns = @columns_hash = nil + @dynamic_methods_hash = @inheritance_column = nil + @arel_engine = @relation = nil + end + + def clear_cache! # :nodoc: + connection.schema_cache.clear! + end + + private + + # Guesses the table name, but does not decorate it with prefix and suffix information. + def undecorated_table_name(class_name = base_class.name) + table_name = class_name.to_s.demodulize.underscore + table_name = table_name.pluralize if pluralize_table_names + table_name + end + + # Computes and returns a table name according to default conventions. + def compute_table_name + base = base_class + if self == base + # Nested classes are prefixed with singular parent table name. + if parent < ActiveRecord::Model && !parent.abstract_class? + contained = parent.table_name + contained = contained.singularize if parent.pluralize_table_names + contained += '_' + end + "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}" + else + # STI subclasses always use their superclass' table. + base.table_name + end + end + end + end +end diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb deleted file mode 100644 index 0313abe456..0000000000 --- a/activerecord/lib/active_record/named_scope.rb +++ /dev/null @@ -1,200 +0,0 @@ -require 'active_support/core_ext/array' -require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/kernel/singleton_class' -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/class/attribute' - -module ActiveRecord - # = Active Record Named \Scopes - module NamedScope - extend ActiveSupport::Concern - - module ClassMethods - # Returns an anonymous \scope. - # - # posts = Post.scoped - # posts.size # Fires "select count(*) from posts" and returns the count - # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects - # - # fruits = Fruit.scoped - # fruits = fruits.where(:color => 'red') if options[:red_only] - # fruits = fruits.limit(10) if limited? - # - # Anonymous \scopes tend to be useful when procedurally generating complex - # queries, where passing intermediate values (\scopes) around as first-class - # objects is convenient. - # - # You can define a \scope that applies to all finders using - # ActiveRecord::Base.default_scope. - def scoped(options = nil) - if options - scoped.apply_finder_options(options) - else - if current_scope - current_scope.clone - else - scope = relation.clone - scope.default_scoped = true - scope - end - 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: - if current_scope - current_scope.scope_for_create - else - scope = relation.clone - scope.default_scoped = true - scope.scope_for_create - end - 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>. - # - # class Shirt < ActiveRecord::Base - # scope :red, where(:color => 'red') - # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) - # end - # - # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, - # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. - # - # Note that this is simply 'syntactic sugar' for defining an actual class method: - # - # class Shirt < ActiveRecord::Base - # def self.red - # where(:color => 'red') - # end - # end - # - # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it - # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance, - # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>. - # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable; - # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> - # all behave as if Shirt.red really was an Array. - # - # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce - # all shirts that are both red and dry clean only. - # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> - # returns the number of garments for which these criteria obtain. Similarly with - # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. - # - # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which - # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If, - # - # class Person < ActiveRecord::Base - # has_many :shirts - # end - # - # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean - # only shirts. - # - # Named \scopes can also be procedural: - # - # class Shirt < ActiveRecord::Base - # scope :colored, lambda { |color| where(:color => color) } - # end - # - # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. - # - # On Ruby 1.9 you can use the 'stabby lambda' syntax: - # - # scope :colored, ->(color) { where(:color => color) } - # - # Note that scopes defined with \scope will be evaluated when they are defined, rather than - # when they are used. For example, the following would be incorrect: - # - # class Post < ActiveRecord::Base - # scope :recent, where('published_at >= ?', Time.now - 1.week) - # end - # - # The example above would be 'frozen' to the <tt>Time.now</tt> value when the <tt>Post</tt> - # class was defined, and so the resultant SQL query would always be the same. The correct - # way to do this would be via a lambda, which will re-evaluate the scope each time - # it is called: - # - # class Post < ActiveRecord::Base - # scope :recent, lambda { where('published_at >= ?', Time.now - 1.week) } - # end - # - # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: - # - # class Shirt < ActiveRecord::Base - # scope :red, where(:color => 'red') do - # def dom_id - # 'red_shirts' - # end - # end - # end - # - # Scopes can also be used while creating/building a record. - # - # class Article < ActiveRecord::Base - # scope :published, where(:published => true) - # end - # - # Article.published.new.published # => true - # Article.published.create.published # => true - # - # Class methods on your model are automatically available - # on scopes. Assuming the following setup: - # - # class Article < ActiveRecord::Base - # scope :published, where(:published => true) - # scope :featured, where(:featured => true) - # - # def self.latest_article - # order('published_at desc').first - # end - # - # def self.titles - # map(&:title) - # end - # - # end - # - # We are able to call the methods like this: - # - # Article.published.featured.latest_article - # Article.featured.titles - - def scope(name, scope_options = {}) - name = name.to_sym - valid_scope_name?(name) - extension = Module.new(&Proc.new) if block_given? - - scope_proc = lambda do |*args| - options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options - options = scoped.apply_finder_options(options) if options.is_a?(Hash) - - relation = scoped.merge(options) - - extension ? relation.extending(extension) : relation - end - - singleton_class.send(:redefine_method, name, &scope_proc) - end - - protected - - def valid_scope_name?(name) - if respond_to?(name, true) - logger.warn "Creating scope :#{name}. " \ - "Overwriting existing method #{self.name}.#{name}." - end - end - end - end -end diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index 2dbebfcaf8..9e21039c4f 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -12,7 +12,7 @@ module ActiveRecord extend ActiveSupport::Concern included do - class_attribute :nested_attributes_options, :instance_writer => false + config_attribute :nested_attributes_options self.nested_attributes_options = {} end @@ -220,7 +220,7 @@ module ActiveRecord # validates_presence_of :member # end module ClassMethods - REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |_, value| value.blank? } } + REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } } # Defines an attributes writer for the specified association(s). If you # are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you @@ -239,7 +239,8 @@ module ActiveRecord # is specified, a record will be built for all attribute hashes that # do not have a <tt>_destroy</tt> value that evaluates to true. # Passing <tt>:all_blank</tt> instead of a Proc will create a proc - # that will reject a record where all the attributes are blank. + # that will reject a record where all the attributes are blank excluding + # any value for _destroy. # [:limit] # Allows you to specify the maximum number of the associated records that # can be processed with the nested attributes. If the size of the @@ -381,7 +382,7 @@ module ActiveRecord if attributes_collection.is_a? Hash keys = attributes_collection.keys attributes_collection = if keys.include?('id') || keys.include?(:id) - Array.wrap(attributes_collection) + [attributes_collection] else attributes_collection.values end diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb new file mode 100644 index 0000000000..60c37ac2b7 --- /dev/null +++ b/activerecord/lib/active_record/null_relation.rb @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- + +module ActiveRecord + # = Active Record Null Relation + class NullRelation < Relation + def exec_queries + @records = [] + end + end +end
\ No newline at end of file diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 5e65e46a7d..09ee2ba61d 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -1,6 +1,53 @@ +require 'active_support/concern' + module ActiveRecord # = Active Record Persistence module Persistence + extend ActiveSupport::Concern + + module ClassMethods + # Creates an object (or multiple objects) and saves it to the database, if validations pass. + # The resulting object is returned whether the object was saved successfully to the database or not. + # + # The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the + # attributes on the objects that are to be created. + # + # +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options + # in the +options+ parameter. + # + # ==== Examples + # # Create a single new object + # User.create(:first_name => 'Jamie') + # + # # Create a single new object using the :admin mass-assignment security role + # User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) + # + # # Create a single new object bypassing mass-assignment security + # User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) + # + # # Create an Array of new objects + # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) + # + # # Create a single object and pass it into a block to set other attributes. + # User.create(:first_name => 'Jamie') do |u| + # u.is_admin = false + # end + # + # # Creating an Array of new objects using a block, where the block is executed for each object: + # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u| + # u.is_admin = false + # end + def create(attributes = nil, options = {}, &block) + if attributes.is_a?(Array) + attributes.collect { |attr| create(attr, options, &block) } + else + object = new(attributes, options, &block) + object.save + object + end + end + end + # Returns true if this object hasn't been saved yet -- that is, a record # for the object doesn't exist in the data store yet; otherwise, returns false. def new_record? @@ -12,8 +59,8 @@ module ActiveRecord @destroyed end - # Returns if the record is persisted, i.e. it's not a new record and it was - # not destroyed. + # 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?) end @@ -114,6 +161,7 @@ module ActiveRecord became.instance_variable_set("@attributes_cache", @attributes_cache) became.instance_variable_set("@new_record", new_record?) became.instance_variable_set("@destroyed", destroyed?) + became.instance_variable_set("@errors", errors) became.type = klass.name unless self.class.descends_from_active_record? became end @@ -161,7 +209,7 @@ module ActiveRecord # The following transaction covers any possible database side-effects of the # attributes assignment. For example, setting the IDs of a child collection. with_transaction_returning_status do - self.assign_attributes(attributes, options) + assign_attributes(attributes, options) save end end @@ -172,7 +220,7 @@ module ActiveRecord # The following transaction covers any possible database side-effects of the # attributes assignment. For example, setting the IDs of a child collection. with_transaction_returning_status do - self.assign_attributes(attributes, options) + assign_attributes(attributes, options) save! end end @@ -237,7 +285,7 @@ module ActiveRecord clear_association_cache IdentityMap.without do - fresh_object = self.class.unscoped { self.class.find(self.id, options) } + fresh_object = self.class.unscoped { self.class.find(id, options) } @attributes.update(fresh_object.instance_variable_get('@attributes')) end @@ -320,13 +368,5 @@ module ActiveRecord @new_record = false id end - - # Initializes the attributes array with keys matching the columns from the linked table and - # the values matching the corresponding default value of that column, so - # that a new instance, or one populated from a passed-in Hash, still has all the attributes - # that instances loaded from the database would. - def attributes_from_column_definition - self.class.column_defaults.dup - end end end diff --git a/activerecord/lib/active_record/query_cache.rb b/activerecord/lib/active_record/query_cache.rb index 10c0dc6f2a..9701898415 100644 --- a/activerecord/lib/active_record/query_cache.rb +++ b/activerecord/lib/active_record/query_cache.rb @@ -27,45 +27,22 @@ module ActiveRecord @app = app end - class BodyProxy # :nodoc: - def initialize(original_cache_value, target) - @original_cache_value = original_cache_value - @target = target - end - - def method_missing(method_sym, *arguments, &block) - @target.send(method_sym, *arguments, &block) - end - - def respond_to?(method_sym, include_private = false) - super || @target.respond_to?(method_sym) - end - - def each(&block) - @target.each(&block) - end + def call(env) + enabled = ActiveRecord::Base.connection.query_cache_enabled + connection_id = ActiveRecord::Base.connection_id + ActiveRecord::Base.connection.enable_query_cache! - def close - @target.close if @target.respond_to?(:close) - ensure + response = @app.call(env) + response[2] = Rack::BodyProxy.new(response[2]) do + ActiveRecord::Base.connection_id = connection_id ActiveRecord::Base.connection.clear_query_cache - unless @original_cache_value - ActiveRecord::Base.connection.disable_query_cache! - end + ActiveRecord::Base.connection.disable_query_cache! unless enabled end - end - def call(env) - old = ActiveRecord::Base.connection.query_cache_enabled - ActiveRecord::Base.connection.enable_query_cache! - - status, headers, body = @app.call(env) - [status, headers, BodyProxy.new(old, body)] + response rescue Exception => e ActiveRecord::Base.connection.clear_query_cache - unless old - ActiveRecord::Base.connection.disable_query_cache! - end + ActiveRecord::Base.connection.disable_query_cache! unless enabled raise e end end diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb new file mode 100644 index 0000000000..5945b05190 --- /dev/null +++ b/activerecord/lib/active_record/querying.rb @@ -0,0 +1,59 @@ +require 'active_support/core_ext/module/delegation' + +module ActiveRecord + module Querying + delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped + delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped + delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped + delegate :find_each, :find_in_batches, :to => :scoped + delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, + :where, :preload, :eager_load, :includes, :from, :lock, :readonly, + :having, :create_with, :uniq, :references, :none, :to => :scoped + delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :to => :scoped + + # Executes a custom SQL query against your database and returns all the results. The results will + # be returned as an array with columns requested encapsulated as attributes of the model you call + # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in + # a Product object with the attributes you specified in the SQL query. + # + # If you call a complicated SQL query which spans multiple tables the columns specified by the + # SELECT will be attributes of the model, whether or not they are columns of the corresponding + # table. + # + # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be + # no database agnostic conversions performed. This should be a last resort because using, for example, + # MySQL specific terms will lock you to using that particular database engine or require you to + # change your call if you switch engines. + # + # ==== Examples + # # A simple SQL query spanning multiple tables + # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" + # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] + # + # # You can use the same string replacement techniques as you can with ActiveRecord#find + # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date] + # > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...] + def find_by_sql(sql, binds = []) + logging_query_plan do + result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds) + result_set.map { |record| instantiate(record) } + end + end + + # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. + # The use of this method should be restricted to complicated SQL queries that can't be executed + # using the ActiveRecord::Calculations class methods. Look into those before using this. + # + # ==== Parameters + # + # * +sql+ - An SQL statement which should return a count query from the database, see the example below. + # + # ==== Examples + # + # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id" + def count_by_sql(sql) + sql = sanitize_conditions(sql) + connection.select_value(sql, "#{name} Count").to_i + end + end +end diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index 47133e77e8..058dd58efb 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -22,6 +22,13 @@ module ActiveRecord config.app_middleware.insert_after "::ActionDispatch::Callbacks", "ActiveRecord::ConnectionAdapters::ConnectionManagement" + config.action_dispatch.rescue_responses.merge!( + 'ActiveRecord::RecordNotFound' => :not_found, + 'ActiveRecord::StaleObjectError' => :conflict, + 'ActiveRecord::RecordInvalid' => :unprocessable_entity, + 'ActiveRecord::RecordNotSaved' => :unprocessable_entity + ) + rake_tasks do load "active_record/railties/databases.rake" end @@ -31,7 +38,8 @@ module ActiveRecord # first time. Also, make it output to STDERR. console do |app| require "active_record/railties/console_sandbox" if app.sandbox? - ActiveRecord::Base.logger = Logger.new(STDERR) + console = ActiveSupport::Logger.new(STDERR) + Rails.logger.extend ActiveSupport::Logger.broadcast console end initializer "active_record.initialize_timezone" do @@ -78,18 +86,30 @@ module ActiveRecord end end - initializer "active_record.set_dispatch_hooks", :before => :set_clear_dependencies_hook do |app| - ActiveSupport.on_load(:active_record) do - ActionDispatch::Reloader.to_cleanup do - ActiveRecord::Base.clear_reloadable_connections! - ActiveRecord::Base.clear_cache! + initializer "active_record.set_reloader_hooks" do |app| + hook = lambda do + ActiveRecord::Base.clear_reloadable_connections! + ActiveRecord::Base.clear_cache! + end + + if app.config.reload_classes_only_on_change + ActiveSupport.on_load(:active_record) do + ActionDispatch::Reloader.to_prepare(&hook) + end + else + ActiveSupport.on_load(:active_record) do + ActionDispatch::Reloader.to_cleanup(&hook) end end end + initializer "active_record.add_watchable_files" do |app| + config.watchable_files.concat ["#{app.root}/db/schema.rb", "#{app.root}/db/structure.sql"] + end + config.after_initialize do ActiveSupport.on_load(:active_record) do - instantiate_observers + ActiveRecord::Base.instantiate_observers ActionDispatch::Reloader.to_prepare do ActiveRecord::Base.instantiate_observers diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index b3316fd1a2..822b51e838 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -1,8 +1,8 @@ require 'active_support/core_ext/object/inclusion' +require 'active_record' db_namespace = namespace :db do task :load_config => :rails_env do - require 'active_record' ActiveRecord::Base.configurations = Rails.application.config.database_configuration ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a @@ -37,11 +37,8 @@ db_namespace = namespace :db do desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)' task :create => :load_config do - # Make the test database at the same time as the development one, if it exists - if Rails.env.development? && ActiveRecord::Base.configurations['test'] - create_database(ActiveRecord::Base.configurations['test']) - end - create_database(ActiveRecord::Base.configurations[Rails.env]) + configs_for_environment.each { |config| create_database(config) } + ActiveRecord::Base.establish_connection(configs_for_environment.first) end def mysql_creation_options(config) @@ -115,8 +112,7 @@ db_namespace = namespace :db do end end else - # Bug with 1.9.2 Calling return within begin still executes else - $stderr.puts "#{config['database']} already exists" unless config['adapter'] =~ /sqlite/ + $stderr.puts "#{config['database']} already exists" end end @@ -138,12 +134,7 @@ db_namespace = namespace :db do desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)' task :drop => :load_config do - config = ActiveRecord::Base.configurations[Rails.env || 'development'] - begin - drop_database(config) - rescue Exception => e - $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}" - end + configs_for_environment.each { |config| drop_database_and_rescue(config) } end def local_database?(config, &block) @@ -158,8 +149,19 @@ db_namespace = namespace :db do desc "Migrate the database (options: VERSION=x, VERBOSE=false)." task :migrate => [:environment, :load_config] do ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true - ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) - db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) do |migration| + ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) + end + db_namespace['_dump'].invoke + end + + task :_dump do + case ActiveRecord::Base.schema_format + when :ruby then db_namespace["schema:dump"].invoke + when :sql then db_namespace["structure:dump"].invoke + else + raise "unknown schema format #{ActiveRecord::Base.schema_format}" + end end namespace :migrate do @@ -182,7 +184,7 @@ db_namespace = namespace :db do version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil raise 'VERSION is required' unless version ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end # desc 'Runs the "down" for a given migration VERSION.' @@ -190,7 +192,7 @@ db_namespace = namespace :db do version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil raise 'VERSION is required' unless version ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_paths, version) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end desc 'Display status of migrations' @@ -230,18 +232,21 @@ db_namespace = namespace :db do task :rollback => [:environment, :load_config] do step = ENV['STEP'] ? ENV['STEP'].to_i : 1 ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).' task :forward => [:environment, :load_config] do step = ENV['STEP'] ? ENV['STEP'].to_i : 1 ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.' - task :reset => [ 'db:drop', 'db:setup' ] + task :reset => :environment do + db_namespace["drop"].invoke + db_namespace["setup"].invoke + end # desc "Retrieves the charset for the current environment's database" task :charset => :environment do @@ -280,24 +285,23 @@ db_namespace = namespace :db do # desc "Raises an error if there are pending migrations" task :abort_if_pending_migrations => :environment do - if defined? ActiveRecord - pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations + pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations - if pending_migrations.any? - puts "You have #{pending_migrations.size} pending migrations:" - pending_migrations.each do |pending_migration| - puts ' %4d %s' % [pending_migration.version, pending_migration.name] - end - abort %{Run "rake db:migrate" to update your database then try again.} + if pending_migrations.any? + puts "You have #{pending_migrations.size} pending migrations:" + pending_migrations.each do |pending_migration| + puts ' %4d %s' % [pending_migration.version, pending_migration.name] end + abort %{Run `rake db:migrate` to update your database then try again.} end end desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)' - task :setup => [ 'db:create', 'db:schema:load', 'db:seed' ] + task :setup => ['db:schema:load_if_ruby', 'db:structure:load_if_sql', :seed] desc 'Load the seed data from db/seeds.rb' - task :seed => 'db:abort_if_pending_migrations' do + task :seed do + db_namespace['abort_if_pending_migrations'].invoke Rails.application.load_seed end @@ -341,7 +345,7 @@ db_namespace = namespace :db do namespace :schema do desc 'Create a db/schema.rb file that can be portably used against any DB supported by AR' - task :dump => :load_config do + task :dump => [:environment, :load_config] do require 'active_record/schema_dumper' filename = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb" File.open(filename, "w:utf-8") do |file| @@ -357,93 +361,125 @@ db_namespace = namespace :db do if File.exists?(file) load(file) else - abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded} + abort %{#{file} doesn't exist yet. Run `rake db:migrate` to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded} end end + + task :load_if_ruby => 'db:create' do + db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby + end end namespace :structure do - desc 'Dump the database structure to an SQL file' + desc 'Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql' task :dump => :environment do abcs = ActiveRecord::Base.configurations + filename = ENV['DB_STRUCTURE'] || File.join(Rails.root, "db", "structure.sql") case abcs[Rails.env]['adapter'] when /mysql/, 'oci', 'oracle' ActiveRecord::Base.establish_connection(abcs[Rails.env]) - File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump } + File.open(filename, "w:utf-8") { |f| f << ActiveRecord::Base.connection.structure_dump } when /postgresql/ - ENV['PGHOST'] = abcs[Rails.env]['host'] if abcs[Rails.env]['host'] - ENV['PGPORT'] = abcs[Rails.env]["port"].to_s if abcs[Rails.env]['port'] - ENV['PGPASSWORD'] = abcs[Rails.env]['password'].to_s if abcs[Rails.env]['password'] + set_psql_env(abcs[Rails.env]) search_path = abcs[Rails.env]['schema_search_path'] unless search_path.blank? search_path = search_path.split(",").map{|search_path_part| "--schema=#{search_path_part.strip}" }.join(" ") end - `pg_dump -i -U "#{abcs[Rails.env]['username']}" -s -x -O -f db/#{Rails.env}_structure.sql #{search_path} #{abcs[Rails.env]['database']}` + `pg_dump -i -s -x -O -f #{filename} #{search_path} #{abcs[Rails.env]['database']}` raise 'Error dumping database' if $?.exitstatus == 1 when /sqlite/ - dbfile = abcs[Rails.env]['database'] || abcs[Rails.env]['dbfile'] - `sqlite3 #{dbfile} .schema > db/#{Rails.env}_structure.sql` + dbfile = abcs[Rails.env]['database'] + `sqlite3 #{dbfile} .schema > #{filename}` when 'sqlserver' - `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f db\\#{Rails.env}_structure.sql -A -U` + `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f #{filename} -A -U` when "firebird" set_firebird_env(abcs[Rails.env]) db_string = firebird_db_string(abcs[Rails.env]) - sh "isql -a #{db_string} > #{Rails.root}/db/#{Rails.env}_structure.sql" + sh "isql -a #{db_string} > #{filename}" else raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'" end if ActiveRecord::Base.connection.supports_migrations? - File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information } + File.open(filename, "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information } end end - end - - namespace :test do - # desc "Recreate the test database from the current schema.rb" - task :load => 'db:test:purge' do - ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test']) - ActiveRecord::Schema.verbose = false - db_namespace['schema:load'].invoke - end - # desc "Recreate the test database from the current environment's database schema" - task :clone => %w(db:schema:dump db:test:load) + # desc "Recreate the databases from the structure.sql file" + task :load => [:environment, :load_config] do + env = ENV['RAILS_ENV'] || 'test' - # desc "Recreate the test databases from the development structure" - task :clone_structure => [ 'db:structure:dump', 'db:test:purge' ] do abcs = ActiveRecord::Base.configurations - case abcs['test']['adapter'] + filename = ENV['DB_STRUCTURE'] || File.join(Rails.root, "db", "structure.sql") + case abcs[env]['adapter'] when /mysql/ - ActiveRecord::Base.establish_connection(:test) + ActiveRecord::Base.establish_connection(abcs[env]) ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0') - IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split("\n\n").each do |table| + IO.read(filename).split("\n\n").each do |table| ActiveRecord::Base.connection.execute(table) end when /postgresql/ - ENV['PGHOST'] = abcs['test']['host'] if abcs['test']['host'] - ENV['PGPORT'] = abcs['test']['port'].to_s if abcs['test']['port'] - ENV['PGPASSWORD'] = abcs['test']['password'].to_s if abcs['test']['password'] - `psql -U "#{abcs['test']['username']}" -f #{Rails.root}/db/#{Rails.env}_structure.sql #{abcs['test']['database']} #{abcs['test']['template']}` + set_psql_env(abcs[env]) + `psql -f "#{filename}" #{abcs[env]['database']} #{abcs[env]['template']}` when /sqlite/ - dbfile = abcs['test']['database'] || abcs['test']['dbfile'] - `sqlite3 #{dbfile} < #{Rails.root}/db/#{Rails.env}_structure.sql` + dbfile = abcs[env]['database'] + `sqlite3 #{dbfile} < "#{filename}"` when 'sqlserver' - `sqlcmd -S #{abcs['test']['host']} -d #{abcs['test']['database']} -U #{abcs['test']['username']} -P #{abcs['test']['password']} -i db\\#{Rails.env}_structure.sql` + `sqlcmd -S #{abcs[env]['host']} -d #{abcs[env]['database']} -U #{abcs[env]['username']} -P #{abcs[env]['password']} -i #{filename}` when 'oci', 'oracle' - ActiveRecord::Base.establish_connection(:test) - IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split(";\n\n").each do |ddl| + ActiveRecord::Base.establish_connection(abcs[env]) + IO.read(filename).split(";\n\n").each do |ddl| ActiveRecord::Base.connection.execute(ddl) end when 'firebird' - set_firebird_env(abcs['test']) - db_string = firebird_db_string(abcs['test']) - sh "isql -i #{Rails.root}/db/#{Rails.env}_structure.sql #{db_string}" + set_firebird_env(abcs[env]) + db_string = firebird_db_string(abcs[env]) + sh "isql -i #{filename} #{db_string}" else - raise "Task not supported by '#{abcs['test']['adapter']}'" + raise "Task not supported by '#{abcs[env]['adapter']}'" end end + task :load_if_sql => 'db:create' do + db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql + end + end + + namespace :test do + + # desc "Recreate the test database from the current schema" + task :load => 'db:test:purge' do + case ActiveRecord::Base.schema_format + when :ruby + db_namespace["test:load_schema"].invoke + when :sql + db_namespace["test:load_structure"].invoke + end + end + + # desc "Recreate the test database from an existent structure.sql file" + task :load_structure => 'db:test:purge' do + begin + old_env, ENV['RAILS_ENV'] = ENV['RAILS_ENV'], 'test' + db_namespace["structure:load"].invoke + ensure + ENV['RAILS_ENV'] = old_env + end + end + + # desc "Recreate the test database from an existent schema.rb file" + task :load_schema => 'db:test:purge' do + ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test']) + ActiveRecord::Schema.verbose = false + db_namespace["schema:load"].invoke + end + + # desc "Recreate the test database from a fresh schema.rb file" + task :clone => %w(db:schema:dump db:test:load_schema) + + # desc "Recreate the test database from a fresh structure.sql file" + task :clone_structure => [ "db:structure:dump", "db:test:load_structure" ] + # desc "Empty the test database" task :purge => :environment do abcs = ActiveRecord::Base.configurations @@ -456,7 +492,7 @@ db_namespace = namespace :db do drop_database(abcs['test']) create_database(abcs['test']) when /sqlite/ - dbfile = abcs['test']['database'] || abcs['test']['dbfile'] + dbfile = abcs['test']['database'] File.delete(dbfile) if File.exist?(dbfile) when 'sqlserver' test = abcs.deep_dup['test'] @@ -479,7 +515,7 @@ db_namespace = namespace :db do # desc 'Check for pending migrations and load the test schema' task :prepare => 'db:abort_if_pending_migrations' do - if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank? + unless ActiveRecord::Base.configurations.blank? db_namespace[{ :sql => 'test:clone_structure', :ruby => 'test:load' }[ActiveRecord::Base.schema_format]].invoke end end @@ -503,7 +539,7 @@ end namespace :railties do namespace :install do - # desc "Copies missing migrations from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2" + # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2" task :migrations => :'db:load_config' do to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip } railties = ActiveSupport::OrderedHash.new @@ -548,6 +584,20 @@ def drop_database(config) end end +def drop_database_and_rescue(config) + begin + drop_database(config) + rescue Exception => e + $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}" + end +end + +def configs_for_environment + environments = [Rails.env] + environments << 'test' if Rails.env.development? + ActiveRecord::Base.configurations.values_at(*environments).compact.reject { |config| config['database'].blank? } +end + def session_table_name ActiveRecord::SessionStore::Session.table_name end @@ -560,3 +610,10 @@ end def firebird_db_string(config) FireRuby::Database.db_string_for(config.symbolize_keys) end + +def set_psql_env(config) + ENV['PGHOST'] = config['host'] if config['host'] + ENV['PGPORT'] = config['port'].to_s if config['port'] + ENV['PGPASSWORD'] = config['password'].to_s if config['password'] + ENV['PGUSER'] = config['username'].to_s if config['username'] +end diff --git a/activerecord/lib/active_record/railties/jdbcmysql_error.rb b/activerecord/lib/active_record/railties/jdbcmysql_error.rb index 6b9af2a0cb..0b75983484 100644 --- a/activerecord/lib/active_record/railties/jdbcmysql_error.rb +++ b/activerecord/lib/active_record/railties/jdbcmysql_error.rb @@ -1,5 +1,5 @@ #FIXME Remove if ArJdbcMysql will give. -module ArJdbcMySQL +module ArJdbcMySQL #:nodoc: class Error < StandardError attr_accessor :error_number, :sql_state diff --git a/activerecord/lib/active_record/readonly_attributes.rb b/activerecord/lib/active_record/readonly_attributes.rb new file mode 100644 index 0000000000..836b15e2ce --- /dev/null +++ b/activerecord/lib/active_record/readonly_attributes.rb @@ -0,0 +1,26 @@ +require 'active_support/concern' +require 'active_support/core_ext/class/attribute' + +module ActiveRecord + module ReadonlyAttributes + extend ActiveSupport::Concern + + included do + config_attribute :_attr_readonly + self._attr_readonly = [] + end + + module ClassMethods + # Attributes listed as readonly will be used to create a new record but update operations will + # ignore these fields. + def attr_readonly(*attributes) + self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || []) + end + + # Returns an array of all the attributes that have been specified as readonly. + def readonly_attributes + self._attr_readonly + end + end + end +end diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index 89179779e3..8f8a3ec3bb 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -7,7 +7,8 @@ module ActiveRecord extend ActiveSupport::Concern included do - class_attribute :reflections + extend ActiveModel::Configuration + config_attribute :reflections self.reflections = {} end @@ -124,7 +125,7 @@ module ActiveRecord # <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt> # <tt>has_many :clients</tt> returns <tt>'Client'</tt> def class_name - @class_name ||= options[:class_name] || derive_class_name + @class_name ||= (options[:class_name] || derive_class_name).to_s end # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute, @@ -174,7 +175,7 @@ module ActiveRecord def initialize(macro, name, options, active_record) super - @collection = macro.in?([:has_many, :has_and_belongs_to_many]) + @collection = [:has_many, :has_and_belongs_to_many].include?(macro) end # Returns a new, unsaved instance of the associated class. +options+ will @@ -211,15 +212,13 @@ module ActiveRecord @association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key end - def association_primary_key - @association_primary_key ||= - options[:primary_key] || - !options[:polymorphic] && klass.primary_key || - 'id' + # klass option is necessary to support loading polymorphic associations + def association_primary_key(klass = nil) + options[:primary_key] || primary_key(klass || self.klass) end def active_record_primary_key - @active_record_primary_key ||= options[:primary_key] || active_record.primary_key + @active_record_primary_key ||= options[:primary_key] || primary_key(active_record) end def counter_cache_column @@ -230,8 +229,8 @@ module ActiveRecord end end - def columns(tbl_name, log_msg) - @columns ||= klass.connection.columns(tbl_name, log_msg) + def columns(tbl_name) + @columns ||= klass.connection.columns(tbl_name) end def reset_column_information @@ -264,6 +263,10 @@ module ActiveRecord [self] end + def nested? + false + end + # An array of arrays of conditions. Each item in the outside array corresponds to a reflection # in the #chain. The inside arrays are simply conditions (and each condition may itself be # a hash, array, arel predicate, etc...) @@ -359,6 +362,10 @@ module ActiveRecord active_record.name.foreign_key end end + + def primary_key(klass) + klass.primary_key || raise(UnknownPrimaryKey.new(klass)) + end end # Holds all the meta-data about a :through association as it was specified @@ -431,7 +438,7 @@ module ActiveRecord # of relevant reflections, plus any :source_type or polymorphic :as constraints. def conditions @conditions ||= begin - conditions = source_reflection.conditions + conditions = source_reflection.conditions.map { |c| c.dup } # Add to it the conditions from this reflection if necessary. conditions.first << options[:conditions] if options[:conditions] @@ -455,7 +462,7 @@ module ActiveRecord source_reflection.source_macro end - # A through association is nested iff there would be more than one join table + # A through association is nested if there would be more than one join table def nested? chain.length > 2 || through_reflection.macro == :has_and_belongs_to_many end @@ -463,17 +470,15 @@ module ActiveRecord # We want to use the klass from this reflection, rather than just delegate straight to # the source_reflection, because the source_reflection may be polymorphic. We still # need to respect the source_reflection's :primary_key option, though. - def association_primary_key - @association_primary_key ||= begin - # Get the "actual" source reflection if the immediate source reflection has a - # source reflection itself - source_reflection = self.source_reflection - while source_reflection.source_reflection - source_reflection = source_reflection.source_reflection - end - - source_reflection.options[:primary_key] || klass.primary_key + def association_primary_key(klass = nil) + # Get the "actual" source reflection if the immediate source reflection has a + # source reflection itself + source_reflection = self.source_reflection + while source_reflection.source_reflection + source_reflection = source_reflection.source_reflection end + + source_reflection.options[:primary_key] || primary_key(klass || self.klass) end # Gets an array of possible <tt>:through</tt> source reflection names: diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index ecefaa633c..ac70aeba67 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -1,19 +1,16 @@ +# -*- coding: utf-8 -*- require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/module/delegation' +require 'active_support/deprecation' module ActiveRecord # = Active Record Relation class Relation JoinOperation = Struct.new(:relation, :join_class, :on) ASSOCIATION_METHODS = [:includes, :eager_load, :preload] - MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind] - SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order] + MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind, :references] + SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering, :reverse_order, :uniq] - include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches - - # These are explicitly delegated to improve performance (avoids method_missing) - delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a - delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, :connection, :column_hash,:to => :klass + include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation attr_reader :table, :klass, :loaded attr_accessor :extensions, :default_scoped @@ -136,14 +133,35 @@ module ActiveRecord first || new(attributes, options, &block) end - def respond_to?(method, include_private = false) - arel.respond_to?(method, include_private) || - Array.method_defined?(method) || - @klass.respond_to?(method, include_private) || - super + # Runs EXPLAIN on the query or queries triggered by this relation and + # returns the result as a string. The string is formatted imitating the + # ones printed by the database shell. + # + # Note that this method actually runs the queries, since the results of some + # are needed by the next ones when eager loading is going on. + # + # Please see further details in the + # {Active Record Query Interface guide}[http://edgeguides.rubyonrails.org/active_record_querying.html#running-explain]. + def explain + _, queries = collecting_queries_for_explain { exec_queries } + exec_explain(queries) end def to_a + # We monitor here the entire execution rather than individual SELECTs + # because from the point of view of the user fetching the records of a + # relation is a single unit of work. You want to know if this call takes + # too long, not if the individual queries take too long. + # + # It could be the case that none of the queries involved surpass the + # threshold, and at the same time the sum of them all does. The user + # should get a query plan logged in that case. + logging_query_plan do + exec_queries + end + end + + def exec_queries return @records if loaded? default_scoped = with_default_scope @@ -174,6 +192,7 @@ module ActiveRecord @loaded = true @records end + private :exec_queries def as_json(options = nil) #:nodoc: to_a.as_json(options) @@ -219,7 +238,7 @@ module ActiveRecord # Please check unscoped if you want to remove all previous scopes (including # the default_scope) during the execution of a block. def scoping - @klass.send(:with_scope, self, :overwrite) { yield } + @klass.with_scope(self, :overwrite) { yield } end # Updates all records with details given if they match a set of conditions supplied, limits and order can @@ -337,7 +356,7 @@ module ActiveRecord end end - # Destroy an object (or multiple objects) that has the given id, the object is instantiated first, + # Destroy an object (or multiple objects) that has the given id. The object is instantiated first, # therefore all callbacks and filters are fired off before the object is deleted. This method is # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run. # @@ -477,6 +496,10 @@ module ActiveRecord to_a.inspect end + def pretty_print(q) + q.pp(self.to_a) + end + def with_default_scope #:nodoc: if default_scoped? && default_scope = klass.send(:build_default_scope) default_scope = default_scope.merge(self) @@ -487,20 +510,6 @@ module ActiveRecord end end - protected - - def method_missing(method, *args, &block) - if Array.method_defined?(method) - to_a.send(method, *args, &block) - elsif @klass.respond_to?(method) - scoping { @klass.send(method, *args, &block) } - elsif arel.respond_to?(method) - arel.send(method, *args, &block) - else - super - end - end - private def references_eager_loaded_tables? @@ -516,8 +525,30 @@ module ActiveRecord # always convert table names to downcase as in Oracle quoted table names are in uppercase joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq - - (tables_in_string(to_sql) - joined_tables).any? + string_tables = tables_in_string(to_sql) + + if (references_values - joined_tables).any? + true + elsif (string_tables - joined_tables).any? + ActiveSupport::Deprecation.warn( + "It looks like you are eager loading table(s) (one of: #{string_tables.join(', ')}) " \ + "that are referenced in a string SQL snippet. For example: \n" \ + "\n" \ + " Post.includes(:comments).where(\"comments.title = 'foo'\")\n" \ + "\n" \ + "Currently, Active Record recognises the table in the string, and knows to JOIN the " \ + "comments table to the query, rather than loading comments in a separate query. " \ + "However, doing this without writing a full-blown SQL parser is inherently flawed. " \ + "Since we don't want to write an SQL parser, we are removing this functionality. " \ + "From now on, you must explicitly tell Active Record when you are referencing a table " \ + "from a string:\n" \ + "\n" \ + " Post.includes(:comments).where(\"comments.title = 'foo'\").references(:comments)\n\n" + ) + true + else + false + end end def tables_in_string(string) @@ -526,6 +557,5 @@ module ActiveRecord # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_'] end - end end diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index af86771d2d..6bf3050af9 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -166,6 +166,22 @@ module ActiveRecord 0 end + # This method is designed to perform select by a single column as direct SQL query + # Returns <tt>Array</tt> with values of the specified column name + # The values has same data type as column. + # + # Examples: + # + # Person.pluck(:id) # SELECT people.id FROM people + # Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people + # Person.where(:confirmed => true).limit(5).pluck(:id) + # + def pluck(column_name) + klass.connection.select_all(select(column_name).arel).map! do |attributes| + klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes)) + end + end + private def perform_calculation(operation, column_name, options = {}) @@ -317,7 +333,7 @@ module ActiveRecord def select_for_count if @select_values.present? select = @select_values.join(", ") - select if select !~ /(,|\*)/ + select if select !~ /[,*]/ end end diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb new file mode 100644 index 0000000000..f5fdf437bf --- /dev/null +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -0,0 +1,49 @@ +require 'active_support/core_ext/module/delegation' + +module ActiveRecord + module Delegation + # Set up common delegations for performance (avoids method_missing) + delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :to => :to_a + delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, + :connection, :columns_hash, :auto_explain_threshold_in_seconds, :to => :klass + + def self.delegate_to_scoped_klass(method) + if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/ + module_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args, &block) + scoping { @klass.#{method}(*args, &block) } + end + RUBY + else + module_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args, &block) + scoping { @klass.send(#{method.inspect}, *args, &block) } + end + RUBY + end + end + + def respond_to?(method, include_private = false) + super || Array.method_defined?(method) || + @klass.respond_to?(method, include_private) || + arel.respond_to?(method, include_private) + end + + protected + + def method_missing(method, *args, &block) + if Array.method_defined?(method) + ::ActiveRecord::Delegation.delegate method, :to => :to_a + to_a.send(method, *args, &block) + elsif @klass.respond_to?(method) + ::ActiveRecord::Delegation.delegate_to_scoped_klass(method) + scoping { @klass.send(method, *args, &block) } + elsif arel.respond_to?(method) + ::ActiveRecord::Delegation.delegate method, :to => :arel + arel.send(method, *args, &block) + else + super + end + end + end +end
\ No newline at end of file diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 7eeb3dde70..f1ac421a50 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -134,7 +134,7 @@ module ActiveRecord def last(*args) if args.any? if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash)) - if order_values.empty? && reorder_value.nil? + if order_values.empty? order("#{primary_key} DESC").limit(*args).reverse else to_a.last(*args) @@ -187,11 +187,11 @@ module ActiveRecord def exists?(id = false) return false if id.nil? - id = id.id if ActiveRecord::Base === id + id = id.id if ActiveRecord::Model === id join_dependency = construct_join_dependency_for_association_find relation = construct_relation_for_association_find(join_dependency) - relation = relation.except(:select).select("1").limit(1) + relation = relation.except(:select, :order).select("1").limit(1) case id when Array, Hash diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 7e8ddd1b5d..1d04e763f6 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -15,42 +15,61 @@ module ActiveRecord table = Arel::Table.new(table_name, engine) end - attribute = table[column.to_sym] - - case value - when ActiveRecord::Relation - value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty? - attribute.in(value.arel.ast) - when Array, ActiveRecord::Associations::CollectionProxy - values = value.to_a.map { |x| - x.is_a?(ActiveRecord::Base) ? x.id : x - } - - if values.include?(nil) - values = values.compact - if values.empty? - attribute.eq nil - else - attribute.in(values.compact).or attribute.eq(nil) - end + build(table[column.to_sym], value) + end + end + predicates.flatten + end + + def self.references(attributes) + references = attributes.map do |key, value| + if value.is_a?(Hash) + key + else + key = key.to_s + key.split('.').first.to_sym if key.include?('.') + end + end + references.compact + end + + private + def self.build(attribute, value) + case value + when ActiveRecord::Relation + value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty? + attribute.in(value.arel.ast) + when Array, ActiveRecord::Associations::CollectionProxy + values = value.to_a.map {|x| x.is_a?(ActiveRecord::Model) ? x.id : x} + ranges, values = values.partition {|v| v.is_a?(Range) || v.is_a?(Arel::Relation)} + + array_predicates = ranges.map {|range| attribute.in(range)} + + if values.include?(nil) + values = values.compact + case values.length + when 0 + array_predicates << attribute.eq(nil) + when 1 + array_predicates << attribute.eq(values.first).or(attribute.eq(nil)) else - attribute.in(values) + array_predicates << attribute.in(values).or(attribute.eq(nil)) end - - when Range, Arel::Relation - attribute.in(value) - when ActiveRecord::Base - attribute.eq(value.id) - when Class - # FIXME: I think we need to deprecate this behavior - attribute.eq(value.name) else - attribute.eq(value) + array_predicates << attribute.in(values) end + + array_predicates.inject {|composite, predicate| composite.or(predicate)} + when Range, Arel::Relation + attribute.in(value) + when ActiveRecord::Model + attribute.eq(value.id) + when Class + # FIXME: I think we need to deprecate this behavior + attribute.eq(value.name) + else + attribute.eq(value) end end - - predicates.flatten - end end end diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index a11b7a3864..b6d762c2e2 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -9,7 +9,8 @@ module ActiveRecord :select_values, :group_values, :order_values, :joins_values, :where_values, :having_values, :bind_values, :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, - :from_value, :reorder_value, :reverse_order_value + :from_value, :reordering_value, :reverse_order_value, + :uniq_value, :references_values def includes(*args) args.reject! {|a| a.blank? } @@ -37,6 +38,53 @@ module ActiveRecord relation end + # Used to indicate that an association is referenced by an SQL string, and should + # therefore be JOINed in any query rather than loaded separately. + # + # For example: + # + # User.includes(:posts).where("posts.name = 'foo'") + # # => Doesn't JOIN the posts table, resulting in an error. + # + # User.includes(:posts).where("posts.name = 'foo'").references(:posts) + # # => Query now knows the string references posts, so adds a JOIN + def references(*args) + return self if args.blank? + + relation = clone + relation.references_values = (references_values + args.flatten.map(&:to_s)).uniq + relation + end + + # Works in two unique ways. + # + # First: takes a block so it can be used just like Array#select. + # + # Model.scoped.select { |m| m.field == value } + # + # This will build an array of objects from the database for the scope, + # converting them into an array and iterating through them using Array#select. + # + # Second: Modifies the SELECT statement for the query so that only certain + # fields are retrieved: + # + # >> Model.select(:field) + # => [#<Model field:value>] + # + # Although in the above example it looks as though this method returns an + # array, it actually returns a relation object and can have other query + # methods appended to it, such as the other methods in ActiveRecord::QueryMethods. + # + # The argument to the method can also be an array of fields. + # + # >> Model.select([:field, :other_field, :and_one_more]) + # => [#<Model field: "value", other_field: "value", and_one_more: "value">] + # + # Accessing attributes of an object that do not have fields retrieved by a select + # will throw <tt>ActiveModel::MissingAttributeError</tt>: + # + # >> Model.select(:field).first.other_field + # => ActiveModel::MissingAttributeError: missing attribute: other_field def select(value = Proc.new) if block_given? to_a.select {|*block_args| value.call(*block_args) } @@ -58,16 +106,33 @@ module ActiveRecord def order(*args) return self if args.blank? + args = args.flatten + references = args.reject { |arg| Arel::Node === arg } + .map { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 } + .compact + relation = clone - relation.order_values += args.flatten + relation = relation.references(references) if references.any? + relation.order_values += args relation end + # Replaces any existing order defined on the relation with the specified order. + # + # User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC' + # + # Subsequent calls to order on the same relation will be appended. For example: + # + # User.order('email DESC').reorder('id ASC').order('name ASC') + # + # generates a query with 'ORDER BY id ASC, name ASC'. + # def reorder(*args) return self if args.blank? relation = clone - relation.reorder_value = args.flatten + relation.reordering_value = true + relation.order_values = args.flatten relation end @@ -92,6 +157,7 @@ module ActiveRecord return self if opts.blank? relation = clone + relation = relation.references(PredicateBuilder.references(opts)) if Hash === opts relation.where_values += build_where(opts, rest) relation end @@ -100,6 +166,7 @@ module ActiveRecord return self if opts.blank? relation = clone + relation = relation.references(PredicateBuilder.references(opts)) if Hash === opts relation.having_values += build_where(opts, rest) relation end @@ -129,6 +196,39 @@ module ActiveRecord relation end + # Returns a chainable relation with zero records, specifically an + # instance of the NullRelation class. + # + # The returned NullRelation inherits from Relation and implements the + # Null Object pattern so it is an object with defined null behavior: + # it always returns an empty array of records and does not query the database. + # + # Any subsequent condition chained to the returned relation will continue + # generating an empty relation and will not fire any query to the database. + # + # This is useful in scenarios where you need a chainable response to a method + # or a scope that could return zero results. + # + # For example: + # + # @posts = current_user.visible_posts.where(:name => params[:name]) + # # => the visible_posts method is expected to return a chainable Relation + # + # def visible_posts + # case role + # when 'Country Manager' + # Post.where(:country => country) + # when 'Reviewer' + # Post.published + # when 'Bad User' + # Post.none # => returning [] instead breaks the previous code + # end + # end + # + def none + NullRelation.new(@klass, @table) + end + def readonly(value = true) relation = clone relation.readonly_value = value @@ -147,9 +247,25 @@ module ActiveRecord relation end + # Specifies whether the records should be unique or not. For example: + # + # User.select(:name) + # # => Might return two records with the same name + # + # User.select(:name).uniq + # # => Returns 1 record per unique name + # + # User.select(:name).uniq.uniq(false) + # # => You can also remove the uniqueness + def uniq(value = true) + relation = clone + relation.uniq_value = value + relation + end + # Used to extend a scope with additional methods, either through - # a module or through a block provided. - # + # a module or through a block provided. + # # The object returned is a relation, which can be further extended. # # === Using a module @@ -171,7 +287,7 @@ module ActiveRecord # # scope = Model.scoped.extending do # def page(number) - # # pagination code goes here + # # pagination code goes here # end # end # scope.page(params[:page]) @@ -180,7 +296,7 @@ module ActiveRecord # # scope = Model.scoped.extending(Pagination) do # def per_page(number) - # # pagination code goes here + # # pagination code goes here # end # end def extending(*modules) @@ -217,12 +333,13 @@ module ActiveRecord arel.group(*@group_values.uniq.reject{|g| g.blank?}) unless @group_values.empty? - order = @reorder_value ? @reorder_value : @order_values + order = @order_values order = reverse_sql_order(order) if @reverse_order_value arel.order(*order.uniq.reject{|o| o.blank?}) unless order.empty? build_select(arel, @select_values.uniq) + arel.distinct(@uniq_value) arel.from(@from_value) if @from_value arel.lock(@lock_value) if @lock_value diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb index ba882beca9..7131aa29b6 100644 --- a/activerecord/lib/active_record/relation/spawn_methods.rb +++ b/activerecord/lib/active_record/relation/spawn_methods.rb @@ -22,7 +22,7 @@ module ActiveRecord end end - (Relation::MULTI_VALUE_METHODS - [:joins, :where]).each do |method| + (Relation::MULTI_VALUE_METHODS - [:joins, :where, :order]).each do |method| value = r.send(:"#{method}_values") merged_relation.send(:"#{method}_values=", merged_relation.send(:"#{method}_values") + value) if value.present? end @@ -48,7 +48,7 @@ module ActiveRecord merged_relation.where_values = merged_wheres - (Relation::SINGLE_VALUE_METHODS - [:lock, :create_with]).each do |method| + (Relation::SINGLE_VALUE_METHODS - [:lock, :create_with, :reordering]).each do |method| value = r.send(:"#{method}_value") merged_relation.send(:"#{method}_value=", value) unless value.nil? end @@ -57,6 +57,15 @@ module ActiveRecord merged_relation = merged_relation.create_with(r.create_with_value) unless r.create_with_value.empty? + if (r.reordering_value) + # override any order specified in the original relation + merged_relation.reordering_value = true + merged_relation.order_values = r.order_values + else + # merge in order_values from r + merged_relation.order_values += r.order_values + end + # Apply scope extension modules merged_relation.send :apply_modules, r.extensions @@ -113,7 +122,7 @@ module ActiveRecord result end - VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend, + VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend, :references, :order, :select, :readonly, :group, :having, :from, :lock ] def apply_finder_options(options) @@ -124,7 +133,7 @@ module ActiveRecord finders = options.dup finders.delete_if { |key, value| value.nil? && key != :limit } - ([:joins, :select, :group, :order, :having, :limit, :offset, :from, :lock, :readonly] & finders.keys).each do |finder| + ((VALID_FIND_OPTIONS - [:conditions, :include, :extend]) & finders.keys).each do |finder| relation = relation.send(finder, finders[finder]) end diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index 9ceab2eabc..60a2e90e23 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -24,6 +24,31 @@ module ActiveRecord hash_rows end + alias :map! :map + alias :collect! :map + + def empty? + rows.empty? + end + + def to_ary + hash_rows + end + + def [](idx) + hash_rows[idx] + end + + def last + hash_rows.last + end + + def initialize_copy(other) + @columns = columns.dup + @rows = rows.dup + @hash_rows = nil + end + private def hash_rows @hash_rows ||= @rows.map { |row| diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb new file mode 100644 index 0000000000..2d7d83d160 --- /dev/null +++ b/activerecord/lib/active_record/sanitization.rb @@ -0,0 +1,194 @@ +require 'active_support/concern' + +module ActiveRecord + module Sanitization + extend ActiveSupport::Concern + + module ClassMethods + def quote_value(value, column = nil) #:nodoc: + connection.quote(value,column) + end + + # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>. + def sanitize(object) #:nodoc: + connection.quote(object) + end + + protected + + # Accepts an array, hash, or string of SQL conditions and sanitizes + # them into a valid SQL fragment for a WHERE clause. + # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" + # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'" + # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'" + def sanitize_sql_for_conditions(condition, table_name = self.table_name) + return nil if condition.blank? + + case condition + when Array; sanitize_sql_array(condition) + when Hash; sanitize_sql_hash_for_conditions(condition, table_name) + else condition + end + end + alias_method :sanitize_sql, :sanitize_sql_for_conditions + + # Accepts an array, hash, or string of SQL conditions and sanitizes + # them into a valid SQL fragment for a SET clause. + # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'" + def sanitize_sql_for_assignment(assignments) + case assignments + when Array; sanitize_sql_array(assignments) + when Hash; sanitize_sql_hash_for_assignment(assignments) + else assignments + end + end + + # Accepts a hash of SQL conditions and replaces those attributes + # that correspond to a +composed_of+ relationship with their expanded + # aggregate attribute values. + # Given: + # class Person < ActiveRecord::Base + # composed_of :address, :class_name => "Address", + # :mapping => [%w(address_street street), %w(address_city city)] + # end + # Then: + # { :address => Address.new("813 abc st.", "chicago") } + # # => { :address_street => "813 abc st.", :address_city => "chicago" } + def expand_hash_conditions_for_aggregates(attrs) + expanded_attrs = {} + attrs.each do |attr, value| + unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil? + mapping = aggregate_mapping(aggregation) + mapping.each do |field_attr, aggregate_attr| + if mapping.size == 1 && !value.respond_to?(aggregate_attr) + expanded_attrs[field_attr] = value + else + expanded_attrs[field_attr] = value.send(aggregate_attr) + end + end + else + expanded_attrs[attr] = value + end + end + expanded_attrs + end + + # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause. + # { :name => "foo'bar", :group_id => 4 } + # # => "name='foo''bar' and group_id= 4" + # { :status => nil, :group_id => [1,2,3] } + # # => "status IS NULL and group_id IN (1,2,3)" + # { :age => 13..18 } + # # => "age BETWEEN 13 AND 18" + # { 'other_records.id' => 7 } + # # => "`other_records`.`id` = 7" + # { :other_records => { :id => 7 } } + # # => "`other_records`.`id` = 7" + # And for value objects on a composed_of relationship: + # { :address => Address.new("123 abc st.", "chicago") } + # # => "address_street='123 abc st.' and address_city='chicago'" + def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) + attrs = expand_hash_conditions_for_aggregates(attrs) + + table = Arel::Table.new(table_name).alias(default_table_name) + PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b| + connection.visitor.accept b + }.join(' AND ') + end + alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions + + # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. + # { :status => nil, :group_id => 1 } + # # => "status = NULL , group_id = 1" + def sanitize_sql_hash_for_assignment(attrs) + attrs.map do |attr, value| + "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}" + end.join(', ') + end + + # Accepts an array of conditions. The array has each value + # sanitized and interpolated into the SQL statement. + # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" + def sanitize_sql_array(ary) + statement, *values = ary + if values.first.is_a?(Hash) && statement =~ /:\w+/ + replace_named_bind_variables(statement, values.first) + elsif statement.include?('?') + replace_bind_variables(statement, values) + elsif statement.blank? + statement + else + statement % values.collect { |value| connection.quote_string(value.to_s) } + end + end + + alias_method :sanitize_conditions, :sanitize_sql + + def replace_bind_variables(statement, values) #:nodoc: + raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size) + bound = values.dup + c = connection + statement.gsub('?') { quote_bound_value(bound.shift, c) } + end + + def replace_named_bind_variables(statement, bind_vars) #:nodoc: + statement.gsub(/(:?):([a-zA-Z]\w*)/) do + if $1 == ':' # skip postgresql casts + $& # return the whole match + elsif bind_vars.include?(match = $2.to_sym) + quote_bound_value(bind_vars[match]) + else + raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" + end + end + end + + def expand_range_bind_variables(bind_vars) #:nodoc: + expanded = [] + + bind_vars.each do |var| + next if var.is_a?(Hash) + + if var.is_a?(Range) + expanded << var.first + expanded << var.last + else + expanded << var + end + end + + expanded + end + + def quote_bound_value(value, c = connection) #:nodoc: + if value.respond_to?(:map) && !value.acts_like?(:string) + if value.respond_to?(:empty?) && value.empty? + c.quote(nil) + else + value.map { |v| c.quote(v) }.join(',') + end + else + c.quote(value) + end + end + + def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc: + unless expected == provided + raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" + end + end + end + + # TODO: Deprecate this + def quoted_id #:nodoc: + quote_value(id, column_for_attribute(self.class.primary_key)) + end + + private + + # Quote strings appropriately for SQL statements. + def quote_value(value, column = nil) + self.class.connection.quote(value, column) + end + end +end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 6fe305f843..2a565b51c6 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -112,7 +112,7 @@ HEADER # AR has an optimization which handles zero-scale decimals as integers. This # code ensures that the dumper still dumps the column as a decimal. - spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } + spec[:type] = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type 'decimal' else column.type.to_s @@ -127,10 +127,14 @@ HEADER end.compact # find all migration keys used in this table - keys = [:name, :limit, :precision, :scale, :default, :null] & column_specs.map{ |k| k.keys }.flatten + keys = [:name, :limit, :precision, :scale, :default, :null] # figure out the lengths for each column based on above keys - lengths = keys.map{ |key| column_specs.map{ |spec| spec[key] ? spec[key].length + 2 : 0 }.max } + lengths = keys.map { |key| + column_specs.map { |spec| + spec[key] ? spec[key].length + 2 : 0 + }.max + } # the string we're going to sprintf our values against, with standardized column widths format_string = lengths.map{ |len| "%-#{len}s" } @@ -190,6 +194,9 @@ HEADER index_lengths = (index.lengths || []).compact statement_parts << (':length => ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty? + index_orders = (index.orders || {}) + statement_parts << (':order => ' + index.orders.inspect) unless index_orders.empty? + ' ' + statement_parts.join(', ') end diff --git a/activerecord/lib/active_record/schema_migration.rb b/activerecord/lib/active_record/schema_migration.rb new file mode 100644 index 0000000000..257963c2ce --- /dev/null +++ b/activerecord/lib/active_record/schema_migration.rb @@ -0,0 +1,32 @@ +require 'active_record/scoping/default' +require 'active_record/scoping/named' +require 'active_record/base' + +module ActiveRecord + class SchemaMigration < ActiveRecord::Base + def self.table_name + Base.table_name_prefix + 'schema_migrations' + Base.table_name_suffix + end + + def self.create_table + unless connection.table_exists?(table_name) + connection.create_table(table_name, :id => false) do |t| + t.column :version, :string, :null => false + end + connection.add_index table_name, :version, :unique => true, + :name => "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}" + end + end + + def self.drop_table + if connection.table_exists?(table_name) + connection.remove_index table_name, :name => "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}" + connection.drop_table(table_name) + end + end + + def version + super.to_i + end + end +end diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb new file mode 100644 index 0000000000..a8f5e96190 --- /dev/null +++ b/activerecord/lib/active_record/scoping.rb @@ -0,0 +1,152 @@ +require 'active_support/concern' + +module ActiveRecord + module Scoping + extend ActiveSupport::Concern + + included do + include Default + include Named + end + + module ClassMethods + # with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be + # <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while + # <tt>:create</tt> parameters are an attributes hash. + # + # class Article < ActiveRecord::Base + # def self.create_with_scope + # with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do + # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 + # a = create(1) + # a.blog_id # => 1 + # end + # end + # end + # + # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of + # <tt>where</tt>, <tt>includes</tt>, and <tt>joins</tt> operations in <tt>Relation</tt>, which are merged. + # + # <tt>joins</tt> operations are uniqued so multiple scopes can join in the same table without table aliasing + # problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the + # array of strings format for your joins. + # + # class Article < ActiveRecord::Base + # def self.find_with_scope + # with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do + # with_scope(:find => limit(10)) do + # all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10 + # end + # with_scope(:find => where(:author_id => 3)) do + # all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1 + # end + # end + # end + # end + # + # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method. + # + # class Article < ActiveRecord::Base + # def self.find_with_exclusive_scope + # with_scope(:find => where(:blog_id => 1).limit(1)) do + # with_exclusive_scope(:find => limit(10)) do + # all # => SELECT * from articles LIMIT 10 + # end + # end + # end + # end + # + # *Note*: the +:find+ scope also has effect on update and deletion methods, like +update_all+ and +delete_all+. + def with_scope(scope = {}, action = :merge, &block) + # If another Active Record class has been passed in, get its current scope + scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope) + + previous_scope = self.current_scope + + if scope.is_a?(Hash) + # Dup first and second level of hash (method and params). + scope = scope.dup + scope.each do |method, params| + scope[method] = params.dup unless params == true + end + + scope.assert_valid_keys([ :find, :create ]) + relation = construct_finder_arel(scope[:find] || {}) + relation.default_scoped = true unless action == :overwrite + + if previous_scope && previous_scope.create_with_value && scope[:create] + scope_for_create = if action == :merge + previous_scope.create_with_value.merge(scope[:create]) + else + scope[:create] + end + + relation = relation.create_with(scope_for_create) + else + scope_for_create = scope[:create] + scope_for_create ||= previous_scope.create_with_value if previous_scope + relation = relation.create_with(scope_for_create) if scope_for_create + end + + scope = relation + end + + scope = previous_scope.merge(scope) if previous_scope && action == :merge + + self.current_scope = scope + begin + yield + ensure + self.current_scope = previous_scope + end + end + + protected + + # Works like with_scope, but discards any nested properties. + def with_exclusive_scope(method_scoping = {}, &block) + if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } + raise ArgumentError, <<-MSG + New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: + + User.unscoped.where(:active => true) + + Or call unscoped with a block: + + User.unscoped do + User.where(:active => true).all + end + + MSG + end + with_scope(method_scoping, :overwrite, &block) + end + + def current_scope #:nodoc: + Thread.current["#{self}_current_scope"] + end + + def current_scope=(scope) #:nodoc: + Thread.current["#{self}_current_scope"] = scope + end + + private + + def construct_finder_arel(options = {}, scope = nil) + relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options + relation = scope.merge(relation) if scope + relation + end + + end + + def populate_with_current_scope_attributes + return unless self.class.scope_attributes? + + self.class.scope_attributes.each do |att,value| + send("#{att}=", value) if respond_to?("#{att}=") + end + end + + end +end diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb new file mode 100644 index 0000000000..5f05d146f2 --- /dev/null +++ b/activerecord/lib/active_record/scoping/default.rb @@ -0,0 +1,142 @@ +require 'active_support/concern' + +module ActiveRecord + module Scoping + module Default + extend ActiveSupport::Concern + + included do + # Stores the default scope for the class + config_attribute :default_scopes + self.default_scopes = [] + end + + module ClassMethods + # Returns a scope for the model without the default_scope. + # + # class Post < ActiveRecord::Base + # def self.default_scope + # where :published => true + # end + # end + # + # Post.all # Fires "SELECT * FROM posts WHERE published = true" + # Post.unscoped.all # Fires "SELECT * FROM posts" + # + # This method also accepts a block. All queries inside the block will + # not use the default_scope: + # + # Post.unscoped { + # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10" + # } + # + # It is recommended to use the block form of unscoped because chaining + # unscoped with <tt>scope</tt> does not work. Assuming that + # <tt>published</tt> is a <tt>scope</tt>, the following two statements + # are equal: the default_scope is applied on both. + # + # Post.unscoped.published + # Post.published + def unscoped #:nodoc: + block_given? ? relation.scoping { yield } : relation + end + + def before_remove_const #:nodoc: + self.current_scope = nil + end + + protected + + # Use this macro in your model to set a default scope for all operations on + # the model. + # + # class Article < ActiveRecord::Base + # default_scope where(:published => true) + # end + # + # Article.all # => SELECT * FROM articles WHERE published = true + # + # The <tt>default_scope</tt> is also applied while creating/building a record. It is not + # applied while updating a record. + # + # Article.new.published # => true + # Article.create.published # => true + # + # You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated: + # + # class Article < ActiveRecord::Base + # default_scope { where(:published_at => Time.now - 1.week) } + # end + # + # (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt> + # macro, and it will be called when building the default scope.) + # + # If you use multiple <tt>default_scope</tt> declarations in your model then they will + # be merged together: + # + # class Article < ActiveRecord::Base + # default_scope where(:published => true) + # default_scope where(:rating => 'G') + # end + # + # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G' + # + # This is also the case with inheritance and module includes where the parent or module + # defines a <tt>default_scope</tt> and the child or including class defines a second one. + # + # If you need to do more complex things with a default scope, you can alternatively + # define it as a class method: + # + # class Article < ActiveRecord::Base + # def self.default_scope + # # Should return a scope, you can call 'super' here etc. + # end + # end + def default_scope(scope = {}) + scope = Proc.new if block_given? + self.default_scopes = default_scopes + [scope] + end + + def build_default_scope #:nodoc: + if method(:default_scope).owner != ActiveRecord::Scoping::Default::ClassMethods + evaluate_default_scope { default_scope } + elsif default_scopes.any? + evaluate_default_scope do + default_scopes.inject(relation) do |default_scope, scope| + if scope.is_a?(Hash) + default_scope.apply_finder_options(scope) + elsif !scope.is_a?(Relation) && scope.respond_to?(:call) + default_scope.merge(scope.call) + else + default_scope.merge(scope) + end + end + end + end + end + + def ignore_default_scope? #:nodoc: + Thread.current["#{self}_ignore_default_scope"] + end + + def ignore_default_scope=(ignore) #:nodoc: + Thread.current["#{self}_ignore_default_scope"] = ignore + end + + # The ignore_default_scope flag is used to prevent an infinite recursion situation where + # a default scope references a scope which has a default scope which references a scope... + def evaluate_default_scope + return if ignore_default_scope? + + begin + self.ignore_default_scope = true + yield + ensure + self.ignore_default_scope = false + end + end + + end + end + end +end diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb new file mode 100644 index 0000000000..0edc3f1dcc --- /dev/null +++ b/activerecord/lib/active_record/scoping/named.rb @@ -0,0 +1,202 @@ +require 'active_support/core_ext/array' +require 'active_support/core_ext/hash/except' +require 'active_support/core_ext/kernel/singleton_class' +require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/class/attribute' + +module ActiveRecord + # = Active Record Named \Scopes + module Scoping + module Named + extend ActiveSupport::Concern + + module ClassMethods + # Returns an anonymous \scope. + # + # posts = Post.scoped + # posts.size # Fires "select count(*) from posts" and returns the count + # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects + # + # fruits = Fruit.scoped + # fruits = fruits.where(:color => 'red') if options[:red_only] + # fruits = fruits.limit(10) if limited? + # + # Anonymous \scopes tend to be useful when procedurally generating complex + # queries, where passing intermediate values (\scopes) around as first-class + # objects is convenient. + # + # You can define a \scope that applies to all finders using + # ActiveRecord::Base.default_scope. + def scoped(options = nil) + if options + scoped.apply_finder_options(options) + else + if current_scope + current_scope.clone + else + scope = relation.clone + scope.default_scoped = true + scope + end + 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: + if current_scope + current_scope.scope_for_create + else + scope = relation.clone + scope.default_scoped = true + scope.scope_for_create + end + 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>. + # + # class Shirt < ActiveRecord::Base + # scope :red, where(:color => 'red') + # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) + # end + # + # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, + # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. + # + # Note that this is simply 'syntactic sugar' for defining an actual class method: + # + # class Shirt < ActiveRecord::Base + # def self.red + # where(:color => 'red') + # end + # end + # + # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it + # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance, + # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>. + # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable; + # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> + # all behave as if Shirt.red really was an Array. + # + # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce + # all shirts that are both red and dry clean only. + # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> + # returns the number of garments for which these criteria obtain. Similarly with + # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. + # + # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which + # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If, + # + # class Person < ActiveRecord::Base + # has_many :shirts + # end + # + # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean + # only shirts. + # + # Named \scopes can also be procedural: + # + # class Shirt < ActiveRecord::Base + # scope :colored, lambda { |color| where(:color => color) } + # end + # + # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. + # + # On Ruby 1.9 you can use the 'stabby lambda' syntax: + # + # scope :colored, ->(color) { where(:color => color) } + # + # Note that scopes defined with \scope will be evaluated when they are defined, rather than + # when they are used. For example, the following would be incorrect: + # + # class Post < ActiveRecord::Base + # scope :recent, where('published_at >= ?', Time.current - 1.week) + # end + # + # The example above would be 'frozen' to the <tt>Time.current</tt> value when the <tt>Post</tt> + # class was defined, and so the resultant SQL query would always be the same. The correct + # way to do this would be via a lambda, which will re-evaluate the scope each time + # it is called: + # + # class Post < ActiveRecord::Base + # scope :recent, lambda { where('published_at >= ?', Time.current - 1.week) } + # end + # + # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: + # + # class Shirt < ActiveRecord::Base + # scope :red, where(:color => 'red') do + # def dom_id + # 'red_shirts' + # end + # end + # end + # + # Scopes can also be used while creating/building a record. + # + # class Article < ActiveRecord::Base + # scope :published, where(:published => true) + # end + # + # Article.published.new.published # => true + # Article.published.create.published # => true + # + # Class methods on your model are automatically available + # on scopes. Assuming the following setup: + # + # class Article < ActiveRecord::Base + # scope :published, where(:published => true) + # scope :featured, where(:featured => true) + # + # def self.latest_article + # order('published_at desc').first + # end + # + # def self.titles + # map(&:title) + # end + # + # end + # + # We are able to call the methods like this: + # + # Article.published.featured.latest_article + # Article.featured.titles + + def scope(name, scope_options = {}) + name = name.to_sym + valid_scope_name?(name) + extension = Module.new(&Proc.new) if block_given? + + scope_proc = lambda do |*args| + options = scope_options.respond_to?(:call) ? unscoped { scope_options.call(*args) } : scope_options + options = scoped.apply_finder_options(options) if options.is_a?(Hash) + + relation = scoped.merge(options) + + extension ? relation.extending(extension) : relation + end + + singleton_class.send(:redefine_method, name, &scope_proc) + end + + protected + + def valid_scope_name?(name) + if respond_to?(name, true) + logger.warn "Creating scope :#{name}. " \ + "Overwriting existing method #{self.name}.#{name}." + end + end + end + end + end +end diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb index 5ad40d8cd9..41e3b92499 100644 --- a/activerecord/lib/active_record/serialization.rb +++ b/activerecord/lib/active_record/serialization.rb @@ -7,8 +7,8 @@ module ActiveRecord #:nodoc: def serializable_hash(options = nil) options = options.try(:clone) || {} - options[:except] = Array.wrap(options[:except]).map { |n| n.to_s } - options[:except] |= Array.wrap(self.class.inheritance_column) + options[:except] = Array(options[:except]).map { |n| n.to_s } + options[:except] |= Array(self.class.inheritance_column) super(options) end diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb index cbfa1ad609..7f1dba5095 100644 --- a/activerecord/lib/active_record/serializers/xml_serializer.rb +++ b/activerecord/lib/active_record/serializers/xml_serializer.rb @@ -1,4 +1,3 @@ -require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/hash/conversions' module ActiveRecord #:nodoc: @@ -179,7 +178,7 @@ module ActiveRecord #:nodoc: class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc: def initialize(*args) super - options[:except] |= Array.wrap(@serializable.class.inheritance_column) + options[:except] = Array(options[:except]) | Array(@serializable.class.inheritance_column) end class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc: diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb index 76c37cc367..ce43ae8066 100644 --- a/activerecord/lib/active_record/session_store.rb +++ b/activerecord/lib/active_record/session_store.rb @@ -51,20 +51,20 @@ module ActiveRecord class SessionStore < ActionDispatch::Session::AbstractStore module ClassMethods # :nodoc: def marshal(data) - ActiveSupport::Base64.encode64(Marshal.dump(data)) if data + ::Base64.encode64(Marshal.dump(data)) if data end def unmarshal(data) - Marshal.load(ActiveSupport::Base64.decode64(data)) if data + Marshal.load(::Base64.decode64(data)) if data end def drop_table! - connection_pool.clear_table_cache!(table_name) + connection.schema_cache.clear_table_cache!(table_name) connection.drop_table table_name end def create_table! - connection_pool.clear_table_cache!(table_name) + connection.schema_cache.clear_table_cache!(table_name) connection.create_table(table_name) do |t| t.string session_id_column, :limit => 255 t.text data_column_name @@ -116,7 +116,7 @@ module ActiveRecord define_method(:session_id) { sessid } define_method(:session_id=) { |session_id| self.sessid = session_id } else - class << self; remove_method :find_by_session_id; end + class << self; remove_possible_method :find_by_session_id; end def self.find_by_session_id(session_id) find :first, :conditions => {:session_id=>session_id} @@ -169,11 +169,11 @@ module ActiveRecord # are implemented as class methods that you may override. By default, # marshaling data is # - # ActiveSupport::Base64.encode64(Marshal.dump(data)) + # ::Base64.encode64(Marshal.dump(data)) # # and unmarshaling data is # - # Marshal.load(ActiveSupport::Base64.decode64(data)) + # Marshal.load(::Base64.decode64(data)) # # This marshaling behavior is intended to store the widest range of # binary session data in a +text+ column. For higher performance, diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb new file mode 100644 index 0000000000..1c7b839e5e --- /dev/null +++ b/activerecord/lib/active_record/store.rb @@ -0,0 +1,52 @@ +module ActiveRecord + # Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. + # It's like a simple key/value store backed into your record when you don't care about being able to + # query that store outside the context of a single record. + # + # You can then declare accessors to this store that are then accessible just like any other attribute + # of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's + # already built around just accessing attributes on the model. + # + # Make sure that you declare the database column used for the serialized store as a text, so there's + # plenty of room. + # + # Examples: + # + # class User < ActiveRecord::Base + # store :settings, accessors: [ :color, :homepage ] + # end + # + # u = User.new(color: 'black', homepage: '37signals.com') + # u.color # Accessor stored attribute + # u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor + # + # # Add additional accessors to an existing store through store_accessor + # class SuperUser < User + # store_accessor :settings, :privileges, :servants + # end + module Store + extend ActiveSupport::Concern + + module ClassMethods + def store(store_attribute, options = {}) + serialize store_attribute, Hash + store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors + end + + def store_accessor(store_attribute, *keys) + keys.flatten.each do |key| + define_method("#{key}=") do |value| + send("#{store_attribute}=", {}) unless send(store_attribute).is_a?(Hash) + send(store_attribute)[key] = value + send("#{store_attribute}_will_change!") + end + + define_method(key) do + send("#{store_attribute}=", {}) unless send(store_attribute).is_a?(Hash) + send(store_attribute)[key] + end + end + end + end + end +end diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb index ffe9b08dce..86687afdda 100644 --- a/activerecord/lib/active_record/test_case.rb +++ b/activerecord/lib/active_record/test_case.rb @@ -1,3 +1,7 @@ +require 'active_support/deprecation' +require 'active_support/test_case' + +ActiveSupport::Deprecation.warn('ActiveRecord::TestCase is deprecated, please use ActiveSupport::TestCase') module ActiveRecord # = Active Record Test Case # @@ -9,15 +13,12 @@ module ActiveRecord cleanup_identity_map end - def cleanup_identity_map - ActiveRecord::IdentityMap.clear + def teardown + ActiveRecord::SQLCounter.log.clear end - # Backport skip to Ruby 1.8. test/unit doesn't support it, so just - # make it a noop. - unless instance_methods.map(&:to_s).include?("skip") - def skip(message) - end + def cleanup_identity_map + ActiveRecord::IdentityMap.clear end def assert_date_from_db(expected, actual, message = nil) @@ -29,45 +30,5 @@ module ActiveRecord assert_equal expected.to_s, actual.to_s, message end end - - def assert_sql(*patterns_to_match) - ActiveRecord::SQLCounter.log = [] - yield - ActiveRecord::SQLCounter.log - ensure - failed_patterns = [] - patterns_to_match.each do |pattern| - failed_patterns << pattern unless ActiveRecord::SQLCounter.log.any?{ |sql| pattern === sql } - end - assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}" - end - - def assert_queries(num = 1) - ActiveRecord::SQLCounter.log = [] - yield - ensure - assert_equal num, ActiveRecord::SQLCounter.log.size, "#{ActiveRecord::SQLCounter.log.size} instead of #{num} queries were executed.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}" - end - - def assert_no_queries(&block) - prev_ignored_sql = ActiveRecord::SQLCounter.ignored_sql - ActiveRecord::SQLCounter.ignored_sql = [] - assert_queries(0, &block) - ensure - ActiveRecord::SQLCounter.ignored_sql = prev_ignored_sql - end - - def with_kcode(kcode) - if RUBY_VERSION < '1.9' - orig_kcode, $KCODE = $KCODE, kcode - begin - yield - ensure - $KCODE = orig_kcode - end - else - yield - end - end end end diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb index 4d5e469a7f..c717fdea47 100644 --- a/activerecord/lib/active_record/timestamp.rb +++ b/activerecord/lib/active_record/timestamp.rb @@ -33,7 +33,7 @@ module ActiveRecord extend ActiveSupport::Concern included do - class_attribute :record_timestamps, :instance_writer => false + config_attribute :record_timestamps, :instance_writer => true self.record_timestamps = true end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index ae97a3f3ca..b492377d18 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -211,7 +211,7 @@ module ActiveRecord def after_commit(*args, &block) options = args.last if options.is_a?(Hash) && options[:on] - options[:if] = Array.wrap(options[:if]) + options[:if] = Array(options[:if]) options[:if] << "transaction_include_action?(:#{options[:on]})" end set_callback(:commit, :after, *args, &block) @@ -220,7 +220,7 @@ module ActiveRecord def after_rollback(*args, &block) options = args.last if options.is_a?(Hash) && options[:on] - options[:if] = Array.wrap(options[:if]) + options[:if] = Array(options[:if]) options[:if] << "transaction_include_action?(:#{options[:on]})" end set_callback(:rollback, :after, *args, &block) @@ -301,7 +301,7 @@ module ActiveRecord protected # Save the new record state and id of a record so it can be restored later if a transaction fails. - def remember_transaction_record_state #:nodoc + def remember_transaction_record_state #:nodoc: @_start_transaction_state ||= {} @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key) unless @_start_transaction_state.include?(:new_record) @@ -314,7 +314,7 @@ module ActiveRecord end # Clear the new record state and id of a record. - def clear_transaction_record_state #:nodoc + def clear_transaction_record_state #:nodoc: if defined?(@_start_transaction_state) @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 remove_instance_variable(:@_start_transaction_state) if @_start_transaction_state[:level] < 1 @@ -322,7 +322,7 @@ module ActiveRecord end # Restore the new record state and id of a record that was previously saved by a call to save_record_state. - def restore_transaction_record_state(force = false) #:nodoc + def restore_transaction_record_state(force = false) #:nodoc: if defined?(@_start_transaction_state) @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 if @_start_transaction_state[:level] < 1 @@ -341,12 +341,12 @@ module ActiveRecord end # Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed. - def transaction_record_state(state) #:nodoc + def transaction_record_state(state) #:nodoc: @_start_transaction_state[state] if defined?(@_start_transaction_state) end # Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks. - def transaction_include_action?(action) #:nodoc + def transaction_include_action?(action) #:nodoc: case action when :create transaction_record_state(:new_record) diff --git a/activerecord/lib/active_record/translation.rb b/activerecord/lib/active_record/translation.rb new file mode 100644 index 0000000000..ddcb5f2a7a --- /dev/null +++ b/activerecord/lib/active_record/translation.rb @@ -0,0 +1,22 @@ +module ActiveRecord + module Translation + include ActiveModel::Translation + + # Set the lookup ancestors for ActiveModel. + def lookup_ancestors #:nodoc: + klass = self + classes = [klass] + return classes if klass == ActiveRecord::Base + + while klass != klass.base_class + classes << klass = klass.superclass + end + classes + end + + # Set the i18n scope to overwrite ActiveModel. + def i18n_scope #:nodoc: + :activerecord + end + end +end diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb index 7af0352a31..afce149da9 100644 --- a/activerecord/lib/active_record/validations/associated.rb +++ b/activerecord/lib/active_record/validations/associated.rb @@ -2,8 +2,9 @@ module ActiveRecord module Validations class AssociatedValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) - return if (value.is_a?(Array) ? value : [value]).collect{ |r| r.nil? || r.valid? }.all? - record.errors.add(attribute, :invalid, options.merge(:value => value)) + if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?(record.validation_context) }.any? + record.errors.add(attribute, :invalid, options.merge(:value => value)) + end end end diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb index 484b1d369b..7fd5d76ba5 100644 --- a/activerecord/lib/active_record/validations/uniqueness.rb +++ b/activerecord/lib/active_record/validations/uniqueness.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/array/wrap' - module ActiveRecord module Validations class UniquenessValidator < ActiveModel::EachValidator @@ -25,8 +23,13 @@ module ActiveRecord relation = build_relation(finder_class, table, attribute, value) relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.send(:id))) if record.persisted? - Array.wrap(options[:scope]).each do |scope_item| + Array(options[:scope]).each do |scope_item| scope_value = record.send(scope_item) + reflection = record.class.reflect_on_association(scope_item) + if reflection + scope_value = record.send(reflection.foreign_key) + scope_item = reflection.foreign_key + end relation = relation.and(table[scope_item].eq(scope_value)) end @@ -53,14 +56,21 @@ module ActiveRecord end def build_relation(klass, table, attribute, value) #:nodoc: - column = klass.columns_hash[attribute.to_s] - value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if column.text? + reflection = klass.reflect_on_association(attribute) + if reflection + column = klass.columns_hash[reflection.foreign_key] + attribute = reflection.foreign_key + value = value.attributes[reflection.primary_key_column.name] + else + column = klass.columns_hash[attribute.to_s] + end + value = column.limit ? value.to_s[0, column.limit] : value.to_s if !value.nil? && column.text? if !options[:case_sensitive] && value && column.text? - # will use SQL LOWER function before comparison - relation = table[attribute].lower.eq(table.lower(value)) + # will use SQL LOWER function before comparison, unless it detects a case insensitive collation + relation = klass.connection.case_insensitive_comparison(table, attribute, column, value) else - value = klass.connection.case_sensitive_modifier(value) + value = klass.connection.case_sensitive_modifier(value) unless value.nil? relation = table[attribute].eq(value) end @@ -81,7 +91,7 @@ module ActiveRecord # # class Person < ActiveRecord::Base # validates_uniqueness_of :user_name, :scope => :account_id - # end + # end # # Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once # per semester for a particular class. diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb index 838aa8fb1e..0c35adc11d 100644 --- a/activerecord/lib/active_record/version.rb +++ b/activerecord/lib/active_record/version.rb @@ -1,7 +1,7 @@ module ActiveRecord module VERSION #:nodoc: - MAJOR = 3 - MINOR = 2 + MAJOR = 4 + MINOR = 0 TINY = 0 PRE = "beta" diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb index f6159deeeb..1509e34473 100644 --- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb +++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb @@ -3,7 +3,7 @@ require 'rails/generators/active_record' module ActiveRecord module Generators class MigrationGenerator < Base - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" def create_migration_file set_local_assigns! diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb index ce8d7eed42..d084a00ed7 100644 --- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb @@ -2,14 +2,20 @@ class <%= migration_class_name %> < ActiveRecord::Migration <%- if migration_action == 'add' -%> def change <% attributes.each do |attribute| -%> - add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %> + add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %> + <%- if attribute.has_index? -%> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> + <%- end %> <%- end -%> end <%- else -%> def up <% attributes.each do |attribute| -%> <%- if migration_action -%> - <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end %> + <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><%= attribute.inject_options %><% end %> + <% if attribute.has_index? && migration_action == 'add' %> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> + <% end -%> <%- end -%> <%- end -%> end @@ -17,7 +23,7 @@ class <%= migration_class_name %> < ActiveRecord::Migration def down <% attributes.reverse.each do |attribute| -%> <%- if migration_action -%> - <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><% end %> + <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><%= attribute.inject_options %><% end %> <%- end -%> <%- end -%> end diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb index f7caa43ac8..99a022461e 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -3,7 +3,7 @@ require 'rails/generators/active_record' module ActiveRecord module Generators class ModelGenerator < Base - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" check_class_collision @@ -26,6 +26,10 @@ module ActiveRecord template 'module.rb', File.join('app/models', "#{class_path.join('/')}.rb") if behavior == :invoke end + def attributes_with_index + attributes.select { |a| a.has_index? || (a.reference? && options[:indexes]) } + end + hook_for :test_framework protected diff --git a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb index 851930344a..3a3cf86d73 100644 --- a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb @@ -2,16 +2,14 @@ class <%= migration_class_name %> < ActiveRecord::Migration def change create_table :<%= table_name %> do |t| <% attributes.each do |attribute| -%> - t.<%= attribute.type %> :<%= attribute.name %> + t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %> <% end -%> <% if options[:timestamps] %> t.timestamps <% end -%> end -<% if options[:indexes] -%> -<% attributes.select {|attr| attr.reference? }.each do |attribute| -%> - add_index :<%= table_name %>, :<%= attribute.name %>_id -<% end -%> +<% attributes_with_index.each do |attribute| -%> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> <% end -%> end end diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb index 1c2942170e..69dfd2503e 100644 --- a/activerecord/test/active_record/connection_adapters/fake_adapter.rb +++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb @@ -9,11 +9,16 @@ module ActiveRecord class FakeAdapter < AbstractAdapter attr_accessor :tables, :primary_keys + @columns = Hash.new { |h,k| h[k] = [] } + class << self + attr_reader :columns + end + def initialize(connection, logger) super @tables = [] @primary_keys = {} - @columns = Hash.new { |h,k| h[k] = [] } + @columns = self.class.columns end def primary_key(table) @@ -28,7 +33,7 @@ module ActiveRecord options[:null]) end - def columns(table_name, message) + def columns(table_name) @columns[table_name] end end diff --git a/activerecord/test/assets/test.txt b/activerecord/test/assets/test.txt new file mode 100644 index 0000000000..6754f0612e --- /dev/null +++ b/activerecord/test/assets/test.txt @@ -0,0 +1 @@ +%00 diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 94497e37c7..852fc0e26e 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -1,170 +1,163 @@ require "cases/helper" -class AdapterTest < ActiveRecord::TestCase - def setup - @connection = ActiveRecord::Base.connection - end - - def test_tables - tables = @connection.tables - assert tables.include?("accounts") - assert tables.include?("authors") - assert tables.include?("tasks") - assert tables.include?("topics") - end +module ActiveRecord + class AdapterTest < ActiveRecord::TestCase + def setup + @connection = ActiveRecord::Base.connection + end - def test_table_exists? - assert @connection.table_exists?("accounts") - assert !@connection.table_exists?("nonexistingtable") - end + def test_tables + tables = @connection.tables + assert tables.include?("accounts") + assert tables.include?("authors") + assert tables.include?("tasks") + assert tables.include?("topics") + end - def test_indexes - idx_name = "accounts_idx" - - if @connection.respond_to?(:indexes) - indexes = @connection.indexes("accounts") - assert indexes.empty? - - @connection.add_index :accounts, :firm_id, :name => idx_name - indexes = @connection.indexes("accounts") - assert_equal "accounts", indexes.first.table - # OpenBase does not have the concept of a named index - # Indexes are merely properties of columns. - assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter) - assert !indexes.first.unique - assert_equal ["firm_id"], indexes.first.columns - else - warn "#{@connection.class} does not respond to #indexes" + def test_table_exists? + assert @connection.table_exists?("accounts") + assert !@connection.table_exists?("nonexistingtable") + assert !@connection.table_exists?(nil) end - ensure - @connection.remove_index(:accounts, :name => idx_name) rescue nil - end + def test_indexes + idx_name = "accounts_idx" + + if @connection.respond_to?(:indexes) + indexes = @connection.indexes("accounts") + assert indexes.empty? + + @connection.add_index :accounts, :firm_id, :name => idx_name + indexes = @connection.indexes("accounts") + assert_equal "accounts", indexes.first.table + # OpenBase does not have the concept of a named index + # Indexes are merely properties of columns. + assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter) + assert !indexes.first.unique + assert_equal ["firm_id"], indexes.first.columns + else + warn "#{@connection.class} does not respond to #indexes" + end - def test_current_database - if @connection.respond_to?(:current_database) - assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database + ensure + @connection.remove_index(:accounts, :name => idx_name) rescue nil end - end - if current_adapter?(:MysqlAdapter) - def test_charset - assert_not_nil @connection.charset - assert_not_equal 'character_set_database', @connection.charset - assert_equal @connection.show_variable('character_set_database'), @connection.charset + def test_current_database + if @connection.respond_to?(:current_database) + assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database + end end - def test_collation - assert_not_nil @connection.collation - assert_not_equal 'collation_database', @connection.collation - assert_equal @connection.show_variable('collation_database'), @connection.collation - end + if current_adapter?(:MysqlAdapter) + def test_charset + assert_not_nil @connection.charset + assert_not_equal 'character_set_database', @connection.charset + assert_equal @connection.show_variable('character_set_database'), @connection.charset + end - def test_show_nonexistent_variable_returns_nil - assert_nil @connection.show_variable('foo_bar_baz') - end + def test_collation + assert_not_nil @connection.collation + assert_not_equal 'collation_database', @connection.collation + assert_equal @connection.show_variable('collation_database'), @connection.collation + end - def test_not_specifying_database_name_for_cross_database_selects - begin - assert_nothing_raised do - ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database)) + def test_show_nonexistent_variable_returns_nil + assert_nil @connection.show_variable('foo_bar_baz') + end - config = ARTest.connection_config - ActiveRecord::Base.connection.execute( - "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \ - "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses" - ) + def test_not_specifying_database_name_for_cross_database_selects + begin + assert_nothing_raised do + ActiveRecord::Model.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database)) + + config = ARTest.connection_config + ActiveRecord::Model.connection.execute( + "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \ + "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses" + ) + end + ensure + ActiveRecord::Model.establish_connection 'arunit' end - ensure - ActiveRecord::Base.establish_connection 'arunit' end end - end - def test_table_alias - def @connection.test_table_alias_length() 10; end - class << @connection - alias_method :old_table_alias_length, :table_alias_length - alias_method :table_alias_length, :test_table_alias_length - end + def test_table_alias + def @connection.test_table_alias_length() 10; end + class << @connection + alias_method :old_table_alias_length, :table_alias_length + alias_method :table_alias_length, :test_table_alias_length + end - assert_equal 'posts', @connection.table_alias_for('posts') - assert_equal 'posts_comm', @connection.table_alias_for('posts_comments') - assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts') + assert_equal 'posts', @connection.table_alias_for('posts') + assert_equal 'posts_comm', @connection.table_alias_for('posts_comments') + assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts') - class << @connection - remove_method :table_alias_length - alias_method :table_alias_length, :old_table_alias_length + class << @connection + remove_method :table_alias_length + alias_method :table_alias_length, :old_table_alias_length + end end - end - # test resetting sequences in odd tables in postgreSQL - if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!) - require 'models/movie' - require 'models/subscriber' + # test resetting sequences in odd tables in postgreSQL + if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!) + require 'models/movie' + require 'models/subscriber' - def test_reset_empty_table_with_custom_pk - Movie.delete_all - Movie.connection.reset_pk_sequence! 'movies' - assert_equal 1, Movie.create(:name => 'fight club').id - end + def test_reset_empty_table_with_custom_pk + Movie.delete_all + Movie.connection.reset_pk_sequence! 'movies' + assert_equal 1, Movie.create(:name => 'fight club').id + end - if ActiveRecord::Base.connection.adapter_name != "FrontBase" - def test_reset_table_with_non_integer_pk - Subscriber.delete_all - Subscriber.connection.reset_pk_sequence! 'subscribers' - sub = Subscriber.new(:name => 'robert drake') - sub.id = 'bob drake' - assert_nothing_raised { sub.save! } + if ActiveRecord::Base.connection.adapter_name != "FrontBase" + def test_reset_table_with_non_integer_pk + Subscriber.delete_all + Subscriber.connection.reset_pk_sequence! 'subscribers' + sub = Subscriber.new(:name => 'robert drake') + sub.id = 'bob drake' + assert_nothing_raised { sub.save! } + end end end - end - def test_uniqueness_violations_are_translated_to_specific_exception - @connection.execute "INSERT INTO subscribers(nick) VALUES('me')" - assert_raises(ActiveRecord::RecordNotUnique) do + def test_uniqueness_violations_are_translated_to_specific_exception @connection.execute "INSERT INTO subscribers(nick) VALUES('me')" + assert_raises(ActiveRecord::RecordNotUnique) do + @connection.execute "INSERT INTO subscribers(nick) VALUES('me')" + end end - end - def test_foreign_key_violations_are_translated_to_specific_exception - unless @connection.adapter_name == 'SQLite' - assert_raises(ActiveRecord::InvalidForeignKey) do - # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method - if @connection.prefetch_primary_key? - id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) - @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" - else - @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + def test_foreign_key_violations_are_translated_to_specific_exception + unless @connection.adapter_name == 'SQLite' + assert_raises(ActiveRecord::InvalidForeignKey) do + # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method + if @connection.prefetch_primary_key? + id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) + @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" + else + @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + end end end end - end - def test_disable_referential_integrity - assert_nothing_raised do - @connection.disable_referential_integrity do - # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method - if @connection.prefetch_primary_key? - id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) - @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" - else - @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + def test_disable_referential_integrity + assert_nothing_raised do + @connection.disable_referential_integrity do + # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method + if @connection.prefetch_primary_key? + id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) + @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" + else + @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + end + # should deleted created record as otherwise disable_referential_integrity will try to enable contraints after executed block + # and will fail (at least on Oracle) + @connection.execute "DELETE FROM fk_test_has_fk" end - # should deleted created record as otherwise disable_referential_integrity will try to enable contraints after executed block - # and will fail (at least on Oracle) - @connection.execute "DELETE FROM fk_test_has_fk" end end end - - def test_deprecated_visitor_for - visitor_klass = Class.new(Arel::Visitors::ToSql) - Arel::Visitors::VISITORS['fuuu'] = visitor_klass - pool = stub(:spec => stub(:config => { :adapter => 'fuuu' })) - visitor = assert_deprecated { - ActiveRecord::ConnectionAdapters::AbstractAdapter.visitor_for(pool) - } - assert visitor.is_a?(visitor_klass) - end end diff --git a/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb new file mode 100644 index 0000000000..97adb6b297 --- /dev/null +++ b/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb @@ -0,0 +1,35 @@ +require "cases/helper" +require 'models/person' + +class MysqlCaseSensitivityTest < ActiveRecord::TestCase + class CollationTest < ActiveRecord::Base + validates_uniqueness_of :string_cs_column, :case_sensitive => false + validates_uniqueness_of :string_ci_column, :case_sensitive => false + end + + def test_columns_include_collation_different_from_table + assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation + assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation + end + + def test_case_sensitive + assert !CollationTest.columns_hash['string_ci_column'].case_sensitive? + assert CollationTest.columns_hash['string_cs_column'].case_sensitive? + end + + def test_case_insensitive_comparison_for_ci_column + CollationTest.create!(:string_ci_column => 'A') + invalid = CollationTest.new(:string_ci_column => 'a') + queries = assert_sql { invalid.save } + ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } + assert_no_match(/lower/i, ci_uniqueness_query) + end + + def test_case_insensitive_comparison_for_cs_column + CollationTest.create!(:string_cs_column => 'A') + invalid = CollationTest.new(:string_cs_column => 'a') + queries = assert_sql { invalid.save } + cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) } + assert_match(/lower/i, cs_uniqueness_query) + end +end diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 2a89430da9..fa2ba8d592 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -3,13 +3,13 @@ require "cases/helper" class MysqlConnectionTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Model.connection end def test_mysql_reconnect_attribute_after_connection_with_reconnect_true run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => true})) - assert ActiveRecord::Base.connection.raw_connection.reconnect + ActiveRecord::Model.establish_connection(orig_connection.merge({:reconnect => true})) + assert ActiveRecord::Model.connection.raw_connection.reconnect end end @@ -25,8 +25,8 @@ class MysqlConnectionTest < ActiveRecord::TestCase def test_mysql_reconnect_attribute_after_connection_with_reconnect_false run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => false})) - assert !ActiveRecord::Base.connection.raw_connection.reconnect + ActiveRecord::Model.establish_connection(orig_connection.merge({:reconnect => false})) + assert !ActiveRecord::Model.connection.raw_connection.reconnect end end @@ -114,7 +114,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase # Test that MySQL allows multiple results for stored procedures if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) def test_multi_results - rows = ActiveRecord::Base.connection.select_rows('CALL ten();') + rows = ActiveRecord::Model.connection.select_rows('CALL ten();') assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'" end @@ -123,11 +123,11 @@ class MysqlConnectionTest < ActiveRecord::TestCase private def run_without_connection - original_connection = ActiveRecord::Base.remove_connection + original_connection = ActiveRecord::Model.remove_connection begin yield original_connection ensure - ActiveRecord::Base.establish_connection(original_connection) + ActiveRecord::Model.establish_connection(original_connection) end end end diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb index 146b77a95c..7fe2c02c04 100644 --- a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb @@ -17,11 +17,7 @@ module ActiveRecord end def test_client_encoding - if "<3".respond_to?(:encoding) - assert_equal Encoding::UTF_8, @conn.client_encoding - else - assert_equal 'utf8', @conn.client_encoding - end + assert_equal Encoding::UTF_8, @conn.client_encoding end def test_exec_insert_number @@ -41,13 +37,11 @@ module ActiveRecord value = result.rows.last.last - if "<3".respond_to?(:encoding) - # FIXME: this should probably be inside the mysql AR adapter? - value.force_encoding(@conn.client_encoding) + # FIXME: this should probably be inside the mysql AR adapter? + value.force_encoding(@conn.client_encoding) - # The strings in this file are utf-8, so transcode to utf-8 - value.encode!(Encoding::UTF_8) - end + # The strings in this file are utf-8, so transcode to utf-8 + value.encode!(Encoding::UTF_8) assert_equal str, value end diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb index a2155d1dd1..29f885c6e7 100644 --- a/activerecord/test/cases/adapters/mysql/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql/schema_test.rb @@ -13,8 +13,8 @@ module ActiveRecord table = Post.table_name @db_name = db - @omgpost = Class.new(Post) do - set_table_name "#{db}.#{table}" + @omgpost = Class.new(ActiveRecord::Base) do + self.table_name = "#{db}.#{table}" def self.name; 'Post'; end end end @@ -23,6 +23,10 @@ module ActiveRecord assert @omgpost.find(:first) end + def test_primary_key + assert_equal 'id', @omgpost.primary_key + end + def test_table_exists? name = @omgpost.table_name assert @connection.table_exists?(name), "#{name} table should exist" diff --git a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb new file mode 100644 index 0000000000..6bcc113482 --- /dev/null +++ b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb @@ -0,0 +1,35 @@ +require "cases/helper" +require 'models/person' + +class Mysql2CaseSensitivityTest < ActiveRecord::TestCase + class CollationTest < ActiveRecord::Base + validates_uniqueness_of :string_cs_column, :case_sensitive => false + validates_uniqueness_of :string_ci_column, :case_sensitive => false + end + + def test_columns_include_collation_different_from_table + assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation + assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation + end + + def test_case_sensitive + assert !CollationTest.columns_hash['string_ci_column'].case_sensitive? + assert CollationTest.columns_hash['string_cs_column'].case_sensitive? + end + + def test_case_insensitive_comparison_for_ci_column + CollationTest.create!(:string_ci_column => 'A') + invalid = CollationTest.new(:string_ci_column => 'a') + queries = assert_sql { invalid.save } + ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } + assert_no_match(/lower/i, ci_uniqueness_query) + end + + def test_case_insensitive_comparison_for_cs_column + CollationTest.create!(:string_cs_column => 'A') + invalid = CollationTest.new(:string_cs_column => 'a') + queries = assert_sql { invalid.save } + cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/)} + assert_match(/lower/i, cs_uniqueness_query) + end +end diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 26091c713b..8e2b9ca9a5 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -3,7 +3,7 @@ require "cases/helper" class MysqlConnectionTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Model.connection end def test_no_automatic_reconnection_after_timeout @@ -32,11 +32,11 @@ class MysqlConnectionTest < ActiveRecord::TestCase private def run_without_connection - original_connection = ActiveRecord::Base.remove_connection + original_connection = ActiveRecord::Model.remove_connection begin yield original_connection ensure - ActiveRecord::Base.establish_connection(original_connection) + ActiveRecord::Model.establish_connection(original_connection) end end end diff --git a/activerecord/test/cases/adapters/mysql2/explain_test.rb b/activerecord/test/cases/adapters/mysql2/explain_test.rb new file mode 100644 index 0000000000..68ed361aeb --- /dev/null +++ b/activerecord/test/cases/adapters/mysql2/explain_test.rb @@ -0,0 +1,26 @@ +require "cases/helper" +require 'models/developer' + +module ActiveRecord + module ConnectionAdapters + class Mysql2Adapter + class ExplainTest < ActiveRecord::TestCase + fixtures :developers + + def test_explain_for_one_query + explain = Developer.where(:id => 1).explain + assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain + assert_match %(developers | const), explain + end + + def test_explain_with_eager_loading + explain = Developer.where(:id => 1).includes(:audit_logs).explain + assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain + assert_match %(developers | const), explain + assert_match %(EXPLAIN for: SELECT `audit_logs`.* FROM `audit_logs` WHERE `audit_logs`.`developer_id` IN (1)), explain + assert_match %(audit_logs | ALL), explain + end + end + end + end +end diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb index 858d1da2dd..d5676bc522 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb @@ -13,8 +13,8 @@ module ActiveRecord table = Post.table_name @db_name = db - @omgpost = Class.new(Post) do - set_table_name "#{db}.#{table}" + @omgpost = Class.new(ActiveRecord::Base) do + self.table_name = "#{db}.#{table}" def self.name; 'Post'; end end end @@ -23,6 +23,10 @@ module ActiveRecord assert @omgpost.find(:first) end + def test_primary_key + assert_equal 'id', @omgpost.primary_key + end + def test_table_exists? name = @omgpost.table_name assert @connection.table_exists?(name), "#{name} table should exist" diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 21b97b3b39..4baec749ff 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -2,6 +2,9 @@ require "cases/helper" module ActiveRecord class PostgresqlConnectionTest < ActiveRecord::TestCase + class NonExistentTable < ActiveRecord::Base + end + def setup super @connection = ActiveRecord::Base.connection @@ -10,5 +13,17 @@ module ActiveRecord def test_encoding assert_not_nil @connection.encoding end + + # Ensure, we can set connection params using the example of Generic + # Query Optimizer (geqo). It is 'on' per default. + def test_connection_options + params = ActiveRecord::Base.connection_config.dup + params[:options] = "-c geqo=off" + NonExistentTable.establish_connection(params) + + # Verify the connection param has been applied. + expect = NonExistentTable.connection.query('show geqo').first.first + assert_equal 'off', expect + end end end diff --git a/activerecord/test/cases/adapters/postgresql/explain_test.rb b/activerecord/test/cases/adapters/postgresql/explain_test.rb new file mode 100644 index 0000000000..0b61f61572 --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/explain_test.rb @@ -0,0 +1,28 @@ +require "cases/helper" +require 'models/developer' + +module ActiveRecord + module ConnectionAdapters + class PostgreSQLAdapter + class ExplainTest < ActiveRecord::TestCase + fixtures :developers + + def test_explain_for_one_query + explain = Developer.where(:id => 1).explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match %(QUERY PLAN), explain + assert_match %(Index Scan using developers_pkey on developers), explain + end + + def test_explain_with_eager_loading + explain = Developer.where(:id => 1).includes(:audit_logs).explain + assert_match %(QUERY PLAN), explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match %(Index Scan using developers_pkey on developers), explain + assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" IN (1)), explain + assert_match %(Seq Scan on audit_logs), explain + end + end + end + end +end diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb new file mode 100644 index 0000000000..33bf4478cc --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -0,0 +1,89 @@ +require "cases/helper" + +class PostgresqlHstoreTest < ActiveRecord::TestCase + class Hstore < ActiveRecord::Base + self.table_name = 'hstores' + end + + def setup + @connection = ActiveRecord::Base.connection + begin + @connection.transaction do + @connection.create_table('hstores') do |t| + t.hstore 'tags' + end + end + rescue ActiveRecord::StatementInvalid + return skip "do not test on PG without hstore" + end + end + + def teardown + @connection.execute 'drop table if exists hstores' + end + + def test_column + column = Hstore.columns.find { |c| c.name == 'tags' } + assert column + assert_equal :hstore, column.type + end + + def test_type_cast_hstore + column = Hstore.columns.find { |c| c.name == 'tags' } + assert column + + data = "\"1\"=>\"2\"" + hash = column.class.cast_hstore data + assert_equal({'1' => '2'}, hash) + assert_equal({'1' => '2'}, column.type_cast(data)) + end + + def test_select + @connection.execute "insert into hstores (tags) VALUES ('1=>2')" + x = Hstore.find :first + assert_equal({'1' => '2'}, x.tags) + end + + def test_select_multikey + @connection.execute "insert into hstores (tags) VALUES ('1=>2,2=>3')" + x = Hstore.find :first + assert_equal({'1' => '2', '2' => '3'}, x.tags) + end + + def test_create + assert_cycle('a' => 'b', '1' => '2') + end + + def test_quotes + assert_cycle('a' => 'b"ar', '1"foo' => '2') + end + + def test_whitespace + assert_cycle('a b' => 'b ar', '1"foo' => '2') + end + + def test_backslash + assert_cycle('a\\b' => 'b\\ar', '1"foo' => '2') + end + + def test_comma + assert_cycle('a, b' => 'bar', '1"foo' => '2') + end + + def test_arrow + assert_cycle('a=>b' => 'bar', '1"foo' => '2') + end + + private + def assert_cycle hash + x = Hstore.create!(:tags => hash) + x.reload + assert_equal(hash, x.tags) + + # make sure updates work + x.tags = hash + x.save! + x.reload + assert_equal(hash, x.tags) + end +end diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 76c73e9dfa..18670b4177 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -10,32 +10,39 @@ class SchemaTest < ActiveRecord::TestCase INDEX_A_NAME = 'a_index_things_on_name' INDEX_B_NAME = 'b_index_things_on_different_columns_in_each_schema' INDEX_C_NAME = 'c_index_full_text_search' + INDEX_D_NAME = 'd_index_things_on_description_desc' INDEX_A_COLUMN = 'name' INDEX_B_COLUMN_S1 = 'email' INDEX_B_COLUMN_S2 = 'moment' INDEX_C_COLUMN = %q{(to_tsvector('english', coalesce(things.name, '')))} + INDEX_D_COLUMN = 'description' COLUMNS = [ 'id integer', 'name character varying(50)', 'email character varying(50)', + 'description character varying(100)', 'moment timestamp without time zone default now()' ] PK_TABLE_NAME = 'table_with_pk' class Thing1 < ActiveRecord::Base - set_table_name "test_schema.things" + self.table_name = "test_schema.things" end class Thing2 < ActiveRecord::Base - set_table_name "test_schema2.things" + self.table_name = "test_schema2.things" end class Thing3 < ActiveRecord::Base - set_table_name 'test_schema."things.table"' + self.table_name = 'test_schema."things.table"' end class Thing4 < ActiveRecord::Base - set_table_name 'test_schema."Things"' + self.table_name = 'test_schema."Things"' + end + + class Thing5 < ActiveRecord::Base + self.table_name = 'things' end def setup @@ -50,6 +57,8 @@ class SchemaTest < ActiveRecord::TestCase @connection.execute "CREATE INDEX #{INDEX_B_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_B_COLUMN_S2});" @connection.execute "CREATE INDEX #{INDEX_C_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING gin (#{INDEX_C_COLUMN});" @connection.execute "CREATE INDEX #{INDEX_C_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING gin (#{INDEX_C_COLUMN});" + @connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);" + @connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);" @connection.execute "CREATE TABLE #{SCHEMA_NAME}.#{PK_TABLE_NAME} (id serial primary key)" end @@ -58,6 +67,18 @@ class SchemaTest < ActiveRecord::TestCase @connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE" end + def test_schema_change_with_prepared_stmt + altered = false + @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]] + @connection.exec_query "alter table developers add column zomg int", 'sql', [] + altered = true + @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]] + ensure + # We are not using DROP COLUMN IF EXISTS because that syntax is only + # supported by pg 9.X + @connection.exec_query("alter table developers drop column zomg", 'sql', []) if altered + end + def test_table_exists? [Thing1, Thing2, Thing3, Thing4].each do |klass| name = klass.table_name @@ -172,11 +193,15 @@ class SchemaTest < ActiveRecord::TestCase end def test_dump_indexes_for_schema_one - do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1) + do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN) end def test_dump_indexes_for_schema_two - do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2) + do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2, INDEX_D_COLUMN) + end + + def test_dump_indexes_for_schema_multiple_schemas_in_search_path + do_dump_index_tests_for_schema("public, #{SCHEMA_NAME}", INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN) end def test_with_uppercase_index_name @@ -236,6 +261,21 @@ class SchemaTest < ActiveRecord::TestCase end end + def test_prepared_statements_with_multiple_schemas + + @connection.schema_search_path = SCHEMA_NAME + Thing5.create(:id => 1, :name => "thing inside #{SCHEMA_NAME}", :email => "thing1@localhost", :moment => Time.now) + + @connection.schema_search_path = SCHEMA2_NAME + Thing5.create(:id => 1, :name => "thing inside #{SCHEMA2_NAME}", :email => "thing1@localhost", :moment => Time.now) + + @connection.schema_search_path = SCHEMA_NAME + assert_equal 1, Thing5.count + + @connection.schema_search_path = SCHEMA2_NAME + assert_equal 1, Thing5.count + end + def test_schema_exists? { 'public' => true, @@ -261,13 +301,16 @@ class SchemaTest < ActiveRecord::TestCase @connection.schema_search_path = "'$user', public" end - def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name) + def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name, third_index_column_name) with_schema_search_path(this_schema_name) do indexes = @connection.indexes(TABLE_NAME).sort_by {|i| i.name} - assert_equal 2,indexes.size + assert_equal 3,indexes.size do_dump_index_assertions_for_one_index(indexes[0], INDEX_A_NAME, first_index_column_name) do_dump_index_assertions_for_one_index(indexes[1], INDEX_B_NAME, second_index_column_name) + do_dump_index_assertions_for_one_index(indexes[2], INDEX_D_NAME, third_index_column_name) + + assert_equal :desc, indexes.select{|i| i.name == INDEX_D_NAME}[0].orders[INDEX_D_COLUMN] end end diff --git a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb index a82c6f67d6..f1c4b85126 100644 --- a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb +++ b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb @@ -2,6 +2,16 @@ require 'cases/helper' module ActiveRecord::ConnectionAdapters class PostgreSQLAdapter < AbstractAdapter + class InactivePGconn + def query(*args) + raise PGError + end + + def status + PGconn::CONNECTION_BAD + end + end + class StatementPoolTest < ActiveRecord::TestCase def test_cache_is_per_pid return skip('must support fork') unless Process.respond_to?(:fork) @@ -18,6 +28,12 @@ module ActiveRecord::ConnectionAdapters Process.waitpid pid assert $?.success?, 'process should exit successfully' end + + def test_dealloc_does_not_raise_on_inactive_connection + cache = StatementPool.new InactivePGconn.new, 10 + cache['foo'] = 'bar' + assert_nothing_raised { cache.clear } + end end end end diff --git a/activerecord/test/cases/adapters/postgresql/utils_test.rb b/activerecord/test/cases/adapters/postgresql/utils_test.rb index 5f08f79171..9e7b08ef34 100644 --- a/activerecord/test/cases/adapters/postgresql/utils_test.rb +++ b/activerecord/test/cases/adapters/postgresql/utils_test.rb @@ -1,3 +1,5 @@ +require 'cases/helper' + class PostgreSQLUtilsTest < ActiveSupport::TestCase include ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils diff --git a/activerecord/test/cases/adapters/postgresql/view_test.rb b/activerecord/test/cases/adapters/postgresql/view_test.rb index 303ba9245a..66e07b71a0 100644 --- a/activerecord/test/cases/adapters/postgresql/view_test.rb +++ b/activerecord/test/cases/adapters/postgresql/view_test.rb @@ -14,7 +14,7 @@ class ViewTest < ActiveRecord::TestCase ] class ThingView < ActiveRecord::Base - set_table_name 'test_schema.view_things' + self.table_name = 'test_schema.view_things' end def setup diff --git a/activerecord/test/cases/adapters/sqlite3/explain_test.rb b/activerecord/test/cases/adapters/sqlite3/explain_test.rb new file mode 100644 index 0000000000..b227bce680 --- /dev/null +++ b/activerecord/test/cases/adapters/sqlite3/explain_test.rb @@ -0,0 +1,26 @@ +require "cases/helper" +require 'models/developer' + +module ActiveRecord + module ConnectionAdapters + class SQLite3Adapter + class ExplainTest < ActiveRecord::TestCase + fixtures :developers + + def test_explain_for_one_query + explain = Developer.where(:id => 1).explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain) + end + + def test_explain_with_eager_loading + explain = Developer.where(:id => 1).includes(:audit_logs).explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain) + assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" IN (1)), explain + assert_match(/(SCAN )?TABLE audit_logs/, explain) + end + end + end + end +end diff --git a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb index e0152e7ccf..46da1b0a2b 100644 --- a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb @@ -70,9 +70,9 @@ module ActiveRecord assert_equal bd.to_f, @conn.type_cast(bd, nil) end - def test_type_cast_unknown + def test_type_cast_unknown_should_raise_error obj = Class.new.new - assert_equal YAML.dump(obj), @conn.type_cast(obj, nil) + assert_raise(TypeError) { @conn.type_cast(obj, nil) } end def test_quoted_id diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 2b598220ee..17bde6cb62 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -5,6 +5,8 @@ require 'models/owner' module ActiveRecord module ConnectionAdapters class SQLite3AdapterTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + class DualEncoding < ActiveRecord::Base end @@ -21,8 +23,6 @@ module ActiveRecord end def test_column_types - return skip('only test encoding on 1.9') unless "<3".encoding_aware? - owner = Owner.create!(:name => "hello".encode('ascii-8bit')) owner.reload select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ', ' @@ -142,8 +142,6 @@ module ActiveRecord end def test_quote_binary_column_escapes_it - return unless "<3".respond_to?(:encode) - DualEncoding.connection.execute(<<-eosql) CREATE TABLE dual_encodings ( id integer PRIMARY KEY AUTOINCREMENT, @@ -155,6 +153,9 @@ module ActiveRecord binary = DualEncoding.new :name => 'いただきます!', :data => str binary.save! assert_equal str, binary.data + + ensure + DualEncoding.connection.drop_table('dual_encodings') end def test_execute diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 866a3cca10..1160d236c9 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -13,6 +13,7 @@ require 'models/comment' require 'models/sponsor' require 'models/member' require 'models/essay' +require 'models/toy' class BelongsToAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :developers, :projects, :topics, @@ -696,4 +697,11 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal nil, comment.reload.parent assert_equal 0, comments(:greetings).reload.children_count end + + def test_polymorphic_with_custom_primary_key + toy = Toy.create! + sponsor = Sponsor.create!(:sponsorable => toy) + + assert_equal toy, sponsor.reload.sponsorable + end end diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb index ff376a68d8..6733f3e889 100644 --- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb +++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb @@ -61,7 +61,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_cascaded_eager_association_loading_with_duplicated_includes - categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null") + categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null").references(:categorizations) assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.all.size @@ -69,7 +69,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_cascaded_eager_association_loading_with_twice_includes_edge_cases - categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null") + categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null").references(:posts) assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.all.size @@ -127,7 +127,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase silly.parent_id = 1 assert silly.save - topics = Topic.find(:all, :include => :replies, :order => 'topics.id, replies_topics.id') + topics = Topic.find(:all, :include => :replies, :order => ['topics.id', 'replies_topics.id']) assert_no_queries do assert_equal 2, topics[0].replies.size assert_equal 0, topics[1].replies.size diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb index d75791cab9..7965bb404c 100644 --- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb @@ -4,7 +4,7 @@ require 'models/tagging' module Namespaced class Post < ActiveRecord::Base - set_table_name 'posts' + self.table_name = 'posts' has_one :tagging, :as => :taggable, :class_name => 'Tagging' end end diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 2cf9f89c3c..1e1958410c 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -6,7 +6,6 @@ require 'models/comment' require 'models/category' require 'models/categorization' require 'models/tagging' -require 'active_support/core_ext/array/random_access' module Remembered extend ActiveSupport::Concern diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index c6e451fc57..b79c69bbb5 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -61,7 +61,10 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_loading_conditions_with_or - posts = authors(:david).posts.find(:all, :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'") + posts = authors(:david).posts.find( + :all, :include => :comments, :references => :comments, + :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'" + ) assert_nil posts.detect { |p| p.author_id != authors(:david).id }, "expected to find only david's posts" end @@ -164,7 +167,7 @@ class EagerAssociationTest < ActiveRecord::TestCase car_post.categories << categories(:technology) comment = car_post.comments.create!(:body => "hmm") - categories = Category.find(:all, :conditions => ["posts.id=?", car_post.id], + categories = Category.find(:all, :conditions => { 'posts.id' => car_post.id }, :include => {:posts => :comments}) categories.each do |category| assert_equal [comment], category.posts[0].comments @@ -252,6 +255,50 @@ class EagerAssociationTest < ActiveRecord::TestCase end end + def test_nested_loading_through_has_one_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}) + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_order + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :order => 'author_addresses.id') + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_order_on_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :order => 'authors.id') + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_order_on_nested_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :order => 'posts.id') + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_conditions + aa = AuthorAddress.find( + author_addresses(:david_address).id, :include => {:author => :posts}, + :conditions => "author_addresses.id > 0", :references => :author_addresses + ) + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_conditions_on_association + aa = AuthorAddress.find( + author_addresses(:david_address).id, :include => {:author => :posts}, + :conditions => "authors.id > 0", :references => :authors + ) + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_conditions_on_nested_association + aa = AuthorAddress.find( + author_addresses(:david_address).id, :include => {:author => :posts}, + :conditions => "posts.id > 0", :references => :posts + ) + assert_equal aa.author.posts.count, aa.author.posts.length + end + def test_eager_association_loading_with_belongs_to_and_foreign_keys pets = Pet.find(:all, :include => :owner) assert_equal 3, pets.length @@ -297,7 +344,9 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name assert_nothing_raised do - Comment.find(:all, :include => :post, :conditions => ['posts.id = ?',4]) + ActiveSupport::Deprecation.silence do + Comment.find(:all, :include => :post, :conditions => ['posts.id = ?',4]) + end end end @@ -316,7 +365,9 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_conditions_string_with_quoted_table_name quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id') assert_nothing_raised do - Comment.find(:all, :include => :post, :conditions => ["#{quoted_posts_id} = ?",4]) + ActiveSupport::Deprecation.silence do + Comment.find(:all, :include => :post, :conditions => ["#{quoted_posts_id} = ?",4]) + end end end @@ -329,7 +380,9 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_table_name quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id') assert_nothing_raised do - Comment.find(:all, :include => :post, :order => quoted_posts_id) + ActiveSupport::Deprecation.silence do + Comment.find(:all, :include => :post, :order => quoted_posts_id) + end end end @@ -493,22 +546,27 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers - posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + posts = ActiveSupport::Deprecation.silence do + Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + end assert_equal 2, posts.size - count = Post.count(:include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + count = ActiveSupport::Deprecation.silence do + Post.count(:include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + end assert_equal count, posts.size end def test_eager_with_has_many_and_limit_and_high_offset - posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ]) + posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => { 'authors.name' => 'David' }) assert_equal 0, posts.size end def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions assert_queries(1) do posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, - :conditions => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]) + :conditions => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ], + :references => [:authors, :comments]) assert_equal 0, posts.size end end @@ -522,7 +580,7 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_count_eager_with_has_many_and_limit_and_high_offset - posts = Post.count(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ]) + posts = Post.count(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => { 'authors.name' => 'David' }) assert_equal 0, posts end @@ -534,7 +592,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_count_performed_on_a_has_many_association_with_multi_table_conditional author = authors(:david) author_posts_without_comments = author.posts.select { |post| post.comments.blank? } - assert_equal author_posts_without_comments.size, author.posts.count(:all, :include => :comments, :conditions => 'comments.id is null') + assert_equal author_posts_without_comments.size, author.posts.count(:all, :include => :comments, :conditions => 'comments.id is null', :references => :comments) end def test_eager_count_performed_on_a_has_many_through_association_with_multi_table_conditional @@ -573,6 +631,7 @@ class EagerAssociationTest < ActiveRecord::TestCase posts = authors(:david).posts.find(:all, :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", + :references => :comments, :limit => 2 ) assert_equal 2, posts.size @@ -580,6 +639,7 @@ class EagerAssociationTest < ActiveRecord::TestCase count = Post.count( :include => [ :comments, :author ], :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", + :references => [:authors, :comments], :limit => 2 ) assert_equal count, posts.size @@ -589,7 +649,8 @@ class EagerAssociationTest < ActiveRecord::TestCase posts = nil Post.send(:with_scope, :find => { :include => :comments, - :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'" + :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", + :references => :comments }) do posts = authors(:david).posts.find(:all, :limit => 2) assert_equal 2, posts.size @@ -597,7 +658,8 @@ class EagerAssociationTest < ActiveRecord::TestCase Post.send(:with_scope, :find => { :include => [ :comments, :author ], - :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')" + :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", + :references => [:authors, :comments] }) do count = Post.count(:limit => 2) assert_equal count, posts.size @@ -609,6 +671,7 @@ class EagerAssociationTest < ActiveRecord::TestCase posts = authors(:david).posts.find(:all, :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", + :references => :comments, :limit => 2 ) assert_equal 2, posts.size @@ -616,6 +679,7 @@ class EagerAssociationTest < ActiveRecord::TestCase count = Post.count( :include => [ :comments, :author ], :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", + :references => [:authors, :comments], :limit => 2 ) assert_equal count, posts.size @@ -623,9 +687,15 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_with_scoped_order_using_association_limiting_without_explicit_scope - posts_with_explicit_order = Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :order => 'posts.id DESC', :limit => 2) + posts_with_explicit_order = Post.find( + :all, :conditions => 'comments.id is not null', :references => :comments, + :include => :comments, :order => 'posts.id DESC', :limit => 2 + ) posts_with_scoped_order = Post.send(:with_scope, :find => {:order => 'posts.id DESC'}) do - Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :limit => 2) + Post.find( + :all, :conditions => 'comments.id is not null', + :references => :comments, :include => :comments, :limit => 2 + ) end assert_equal posts_with_explicit_order, posts_with_scoped_order end @@ -738,17 +808,49 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_limited_eager_with_order - assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title)', :limit => 2, :offset => 1) - assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1) + assert_equal( + posts(:thinking, :sti_comments), + Post.find( + :all, :include => [:author, :comments], :conditions => { 'authors.name' => 'David' }, + :order => 'UPPER(posts.title)', :limit => 2, :offset => 1 + ) + ) + assert_equal( + posts(:sti_post_and_comments, :sti_comments), + Post.find( + :all, :include => [:author, :comments], :conditions => { 'authors.name' => 'David' }, + :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1 + ) + ) end def test_limited_eager_with_multiple_order_columns - assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1) - assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1) + assert_equal( + posts(:thinking, :sti_comments), + Post.find( + :all, :include => [:author, :comments], :conditions => { 'authors.name' => 'David' }, + :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1 + ) + ) + assert_equal( + posts(:sti_post_and_comments, :sti_comments), + Post.find( + :all, :include => [:author, :comments], :conditions => { 'authors.name' => 'David' }, + :order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1 + ) + ) end def test_limited_eager_with_numeric_in_association - assert_equal people(:david, :susan), Person.find(:all, :include => [:readers, :primary_contact, :number1_fan], :conditions => "number1_fans_people.first_name like 'M%'", :order => 'people.id', :limit => 2, :offset => 0) + assert_equal( + people(:david, :susan), + Person.find( + :all, :include => [:readers, :primary_contact, :number1_fan], + :conditions => "number1_fans_people.first_name like 'M%'", + :references => :number1_fans_people, + :order => 'people.id', :limit => 2, :offset => 0 + ) + ) end def test_preload_with_interpolation @@ -863,11 +965,11 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_count_with_include if current_adapter?(:SybaseAdapter) - assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15") + assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15", :references => :comments) elsif current_adapter?(:OpenBaseAdapter) - assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15") + assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15", :references => :comments) else - assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15") + assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15", :references => :comments) end end @@ -878,7 +980,7 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_conditions_on_join_table_with_include_and_limit - assert_equal 3, Developer.find(:all, :include => 'projects', :conditions => 'developers_projects.access_level = 1', :limit => 5).size + assert_equal 3, Developer.find(:all, :include => 'projects', :conditions => { 'developers_projects.access_level' => 1 }, :limit => 5).size end def test_order_on_join_table_with_include_and_limit @@ -1060,4 +1162,11 @@ class EagerAssociationTest < ActiveRecord::TestCase Post.includes(:comments).order(nil).where(:comments => {:body => "Thank you for the welcome"}).first end end + + def test_deep_including_through_habtm + posts = Post.find(:all, :include => {:categories => :categorizations}, :order => "posts.id") + assert_no_queries { assert_equal 2, posts[0].categories[0].categorizations.length } + assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length } + assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length } + end end diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index 8dc1423375..d7c489c2b5 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -36,11 +36,6 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase end def test_marshalling_extensions - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - david = developers(:david) assert_equal projects(:action_controller), david.projects.find_most_recent @@ -51,11 +46,6 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase end def test_marshalling_named_extensions - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - david = developers(:david) assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent @@ -71,6 +61,12 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer) end + def test_proxy_association_after_scoped + post = posts(:welcome) + assert_equal post.association(:comments), post.comments.the_association + assert_equal post.association(:comments), post.comments.scoped.the_association + end + private def extension_name(model) diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index d8d2a113ff..f457dfb9b3 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -23,7 +23,7 @@ require 'models/treaty' require 'active_support/core_ext/string/conversions' class ProjectWithAfterCreateHook < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' has_and_belongs_to_many :developers, :class_name => "DeveloperForProjectWithAfterCreateHook", :join_table => "developers_projects", @@ -39,7 +39,7 @@ class ProjectWithAfterCreateHook < ActiveRecord::Base end class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' has_and_belongs_to_many :projects, :class_name => "ProjectWithAfterCreateHook", :join_table => "developers_projects", @@ -48,7 +48,7 @@ class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base end class ProjectWithSymbolsForKeys < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' has_and_belongs_to_many :developers, :class_name => "DeveloperWithSymbolsForKeys", :join_table => :developers_projects, @@ -57,7 +57,7 @@ class ProjectWithSymbolsForKeys < ActiveRecord::Base end class DeveloperWithSymbolsForKeys < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' has_and_belongs_to_many :projects, :class_name => "ProjectWithSymbolsForKeys", :join_table => :developers_projects, @@ -66,7 +66,7 @@ class DeveloperWithSymbolsForKeys < ActiveRecord::Base end class DeveloperWithCounterSQL < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' has_and_belongs_to_many :projects, :class_name => "DeveloperWithCounterSQL", :join_table => "developers_projects", @@ -77,7 +77,7 @@ end class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects, - :parrots, :pirates, :treasures, :price_estimates, :tags, :taggings + :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings def setup_data_for_habtm_case ActiveRecord::Base.connection.execute('delete from countries_treaties') @@ -445,6 +445,26 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert david.projects(true).empty? end + def test_destroy_associations_destroys_multiple_associations + george = parrots(:george) + assert !george.pirates.empty? + assert !george.treasures.empty? + + assert_no_difference "Pirate.count" do + assert_no_difference "Treasure.count" do + george.destroy_associations + end + end + + join_records = Parrot.connection.select_all("SELECT * FROM parrots_pirates WHERE parrot_id = #{george.id}") + assert join_records.empty? + assert george.pirates(true).empty? + + join_records = Parrot.connection.select_all("SELECT * FROM parrots_treasures WHERE parrot_id = #{george.id}") + assert join_records.empty? + assert george.treasures(true).empty? + end + def test_deprecated_push_with_attributes_was_removed jamis = developers(:jamis) assert_raise(NoMethodError) do @@ -650,8 +670,22 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_respond_to categories(:technology).select_testing_posts.find(:first), :correctness_marker end + def test_habtm_selects_all_columns_by_default + assert_equal Project.column_names.sort, developers(:david).projects.first.attributes.keys.sort + end + + def test_habtm_respects_select_query_method + assert_equal ['id'], developers(:david).projects.select(:id).first.attributes.keys + end + def test_join_table_alias - assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size + assert_equal( + 3, + Developer.find( + :all, :include => {:projects => :developers}, :references => :developers_projects_join, + :conditions => 'developers_projects_join.joined_on IS NOT NULL' + ).size + ) end def test_join_with_group @@ -661,7 +695,13 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase end Project.columns.each { |c| group << "projects.#{c.name}" } - assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', :group => group.join(",")).size + assert_equal( + 3, + Developer.find( + :all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', + :references => :developers_projects_join, :group => group.join(",") + ).size + ) end def test_find_grouped @@ -797,12 +837,11 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase # clear cache possibly created by other tests david.projects.reset_column_information - # One query for columns, one for primary key - assert_queries(2) { david.projects.columns; david.projects.columns } + assert_queries(1) { david.projects.columns; david.projects.columns } ## and again to verify that reset_column_information clears the cache correctly david.projects.reset_column_information - assert_queries(2) { david.projects.columns; david.projects.columns } + assert_queries(1) { david.projects.columns; david.projects.columns } end def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 1e59931963..3967009c82 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -8,6 +8,7 @@ require 'models/reply' require 'models/category' require 'models/post' require 'models/author' +require 'models/essay' require 'models/comment' require 'models/person' require 'models/reader' @@ -41,12 +42,37 @@ class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase end end +class HasManyAssociationsTestForCountDistinctWithFinderSql < ActiveRecord::TestCase + class Invoice < ActiveRecord::Base + has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items" + end + + def test_should_count_distinct_results + invoice = Invoice.new + invoice.custom_line_items << LineItem.new(:amount => 0) + invoice.custom_line_items << LineItem.new(:amount => 0) + invoice.save! + + assert_equal 1, invoice.custom_line_items.count + end +end + +class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase + fixtures :authors, :posts, :comments + + def test_should_generate_valid_sql + author = authors(:david) + # this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression + # if the reorder clauses are not correctly handled + assert author.posts_with_comments_sorted_by_comment_id.where('comments.id > 0').reorder('posts.comments_count DESC', 'posts.taggings_count DESC').last + end +end class HasManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :categories, :companies, :developers, :projects, :developers_projects, :topics, :authors, :comments, - :people, :posts, :readers, :taggings, :cars + :people, :posts, :readers, :taggings, :cars, :essays def setup Client.destroyed_client_ids.clear @@ -485,6 +511,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 0, authors(:mary).popular_grouped_posts.length end + def test_default_select + assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort + end + + def test_select_query_method + assert_equal ['id'], posts(:welcome).comments.select(:id).first.attributes.keys + end + def test_adding force_signal37_to_load_all_clients_of_firm natural = Client.new("name" => "Natural Company") @@ -704,6 +738,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal number_of_clients + 1, companies(:first_firm).clients_of_firm.size end + def test_find_or_initialize_returns_the_instantiated_object + client = companies(:first_firm).clients_of_firm.find_or_initialize_by_name("name" => "Another Client") + assert_equal client, companies(:first_firm).clients_of_firm[-1] + end + + def test_find_or_initialize_only_instantiates_a_single_object + number_of_clients = Client.count + companies(:first_firm).clients_of_firm.find_or_initialize_by_name("name" => "Another Client").save! + companies(:first_firm).save! + assert_equal number_of_clients+1, Client.count + end + def test_find_or_create_with_hash post = authors(:david).posts.find_or_create_by_title(:title => 'Yet another post', :body => 'somebody') assert_equal post, authors(:david).posts.find_or_create_by_title(:title => 'Yet another post', :body => 'somebody') @@ -1106,16 +1152,42 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_nil companies(:leetsoft).reload.client_of assert_nil companies(:jadedpixel).reload.client_of - assert_equal num_accounts, Account.count end def test_restrict - firm = RestrictedFirm.new(:name => 'restrict') - firm.save! + option_before = ActiveRecord::Base.dependent_restrict_raises + ActiveRecord::Base.dependent_restrict_raises = true + + firm = RestrictedFirm.create!(:name => 'restrict') firm.companies.create(:name => 'child') + assert !firm.companies.empty? assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy } + assert RestrictedFirm.exists?(:name => 'restrict') + assert firm.companies.exists?(:name => 'child') + ensure + ActiveRecord::Base.dependent_restrict_raises = option_before + end + + def test_restrict_when_dependent_restrict_raises_config_set_to_false + option_before = ActiveRecord::Base.dependent_restrict_raises + ActiveRecord::Base.dependent_restrict_raises = false + + firm = RestrictedFirm.create!(:name => 'restrict') + firm.companies.create(:name => 'child') + + assert !firm.companies.empty? + + firm.destroy + + assert !firm.errors.empty? + + assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first + assert RestrictedFirm.exists?(:name => 'restrict') + assert firm.companies.exists?(:name => 'child') + ensure + ActiveRecord::Base.dependent_restrict_raises = option_before end def test_included_in_collection @@ -1219,6 +1291,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert company.clients_using_sql.loaded? end + def test_get_ids_for_ordered_association + assert_equal [companies(:second_client).id, companies(:first_client).id], companies(:first_firm).clients_ordered_by_name_ids + end + def test_assign_ids_ignoring_blanks firm = Firm.create!(:name => 'Apple') firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ''] @@ -1368,6 +1444,32 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end end + def test_custom_primary_key_on_new_record_should_fetch_with_query + author = Author.new(:name => "David") + assert !author.essays.loaded? + + assert_queries 1 do + assert_equal 1, author.essays.size + end + + assert_equal author.essays, Essay.find_all_by_writer_id("David") + + end + + def test_has_many_custom_primary_key + david = authors(:david) + assert_equal david.essays, Essay.find_all_by_writer_id("David") + end + + def test_blank_custom_primary_key_on_new_record_should_not_run_queries + author = Author.new + assert !author.essays.loaded? + + assert_queries 0 do + assert_equal 0, author.essays.size + end + end + def test_calling_first_or_last_with_find_options_on_loaded_association_should_fetch_with_query firm = companies(:first_firm) firm.clients.class # force load target @@ -1578,4 +1680,27 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal car.id, bulb.attributes_after_initialize['car_id'] end + + def test_replace + car = Car.create(:name => 'honda') + bulb1 = car.bulbs.create + bulb2 = Bulb.create + + assert_equal [bulb1], car.bulbs + car.bulbs.replace([bulb2]) + assert_equal [bulb2], car.bulbs + assert_equal [bulb2], car.reload.bulbs + end + + def test_building_has_many_association_with_restrict_dependency + option_before = ActiveRecord::Base.dependent_restrict_raises + ActiveRecord::Base.dependent_restrict_raises = true + + klass = Class.new(ActiveRecord::Base) + + assert_deprecated { klass.has_many :companies, :dependent => :restrict } + assert_not_deprecated { klass.has_many :companies } + ensure + ActiveRecord::Base.dependent_restrict_raises = option_before + end end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index b703c96ec1..9cc09194dc 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -67,6 +67,31 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end end + def test_associate_existing_record_twice_should_add_records_twice + post = posts(:thinking) + person = people(:david) + + assert_difference 'post.people.count', 2 do + post.people << person + post.people << person + end + end + + def test_add_two_instance_and_then_deleting + post = posts(:thinking) + person = people(:david) + + post.people << person + post.people << person + + counts = ['post.people.count', 'post.people.to_a.count', 'post.readers.count', 'post.readers.to_a.count'] + assert_difference counts, -2 do + post.people.delete(person) + end + + assert !post.people.reload.include?(person) + end + def test_associating_new assert_queries(1) { posts(:thinking) } new_person = nil # so block binding catches it @@ -503,6 +528,12 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort end + def test_get_ids_for_has_many_through_with_conditions_should_not_preload + Tagging.create!(:taggable_type => 'Post', :taggable_id => posts(:welcome).id, :tag => tags(:misc)) + ActiveRecord::Associations::Preloader.expects(:new).never + posts(:welcome).misc_tag_ids + end + def test_get_ids_for_loaded_associations person = people(:michael) person.posts(true) @@ -707,7 +738,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_select_chosen_fields_only author = authors(:david) - assert_equal ['body'], author.comments.select('comments.body').first.attributes.keys + assert_equal ['body', 'id'].sort, author.comments.select('comments.body').first.attributes.keys.sort end def test_get_has_many_through_belongs_to_ids_with_conditions @@ -816,7 +847,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_preloading_empty_through_association_via_joins person = Person.create!(:first_name => "Gaga") - person = Person.where(:id => person.id).where('readers.id = 1 or 1=1').includes(:posts).to_a.first + person = Person.where(:id => person.id).where('readers.id = 1 or 1=1').references(:readers).includes(:posts).to_a.first assert person.posts.loaded?, 'person.posts should be loaded' assert_equal [], person.posts @@ -825,4 +856,9 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_explicitly_joining_join_table assert_equal owners(:blackbeard).toys, owners(:blackbeard).toys.with_pet end + + def test_has_many_through_with_polymorphic_source + post = tags(:general).tagged_posts.create! :title => "foo", :body => "bar" + assert_equal [tags(:general)], post.reload.tags + end end diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 26931e3e85..246877bbed 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -157,11 +157,62 @@ class HasOneAssociationsTest < ActiveRecord::TestCase end def test_dependence_with_restrict - firm = RestrictedFirm.new(:name => 'restrict') - firm.save! + option_before = ActiveRecord::Base.dependent_restrict_raises + ActiveRecord::Base.dependent_restrict_raises = true + + firm = RestrictedFirm.create!(:name => 'restrict') firm.create_account(:credit_limit => 10) + assert_not_nil firm.account + assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy } + assert RestrictedFirm.exists?(:name => 'restrict') + assert firm.account.present? + ensure + ActiveRecord::Base.dependent_restrict_raises = option_before + end + + def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false + option_before = ActiveRecord::Base.dependent_restrict_raises + ActiveRecord::Base.dependent_restrict_raises = false + + firm = RestrictedFirm.create!(:name => 'restrict') + firm.create_account(:credit_limit => 10) + + assert_not_nil firm.account + + firm.destroy + + assert !firm.errors.empty? + assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first + assert RestrictedFirm.exists?(:name => 'restrict') + assert firm.account.present? + ensure + ActiveRecord::Base.dependent_restrict_raises = option_before + end + + def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false_and_attribute_name + old_backend = I18n.backend + I18n.backend = I18n::Backend::Simple.new + I18n.backend.store_translations 'en', :activerecord => {:attributes => {:restricted_firm => {:account => "account model"}}} + + option_before = ActiveRecord::Base.dependent_restrict_raises + ActiveRecord::Base.dependent_restrict_raises = false + + firm = RestrictedFirm.create!(:name => 'restrict') + firm.create_account(:credit_limit => 10) + + assert_not_nil firm.account + + firm.destroy + + assert !firm.errors.empty? + assert_equal "Cannot delete record because a dependent account model exists", firm.errors[:base].first + assert RestrictedFirm.exists?(:name => 'restrict') + assert firm.account.present? + ensure + ActiveRecord::Base.dependent_restrict_raises = option_before + I18n.backend = old_backend end def test_successful_build_association @@ -456,4 +507,16 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal car.id, bulb.attributes_after_initialize['car_id'] end + + def test_building_has_one_association_with_dependent_restrict + option_before = ActiveRecord::Base.dependent_restrict_raises + ActiveRecord::Base.dependent_restrict_raises = true + + klass = Class.new(ActiveRecord::Base) + + assert_deprecated { klass.has_one :account, :dependent => :restrict } + assert_not_deprecated { klass.has_one :account } + ensure + ActiveRecord::Base.dependent_restrict_raises = option_before + end end diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index e5e9ca6131..68a1e62328 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -67,7 +67,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase def test_find_with_implicit_inner_joins_does_not_set_associations authors = Author.joins(:posts).select('authors.*') assert !authors.empty?, "expected authors to be non-empty" - assert authors.all? {|a| !a.send(:instance_variable_names).include?("@posts")}, "expected no authors to have the @posts association loaded" + assert authors.all? { |a| !a.instance_variable_defined?(:@posts) }, "expected no authors to have the @posts association loaded" end def test_count_honors_implicit_inner_joins diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 4ce8b85098..301755249c 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -362,7 +362,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end assert_raise ActiveRecord::EagerLoadPolymorphicError do - tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1') + tags(:general).taggings.find(:all, :include => :taggable, :references => :bogus_table, :conditions => 'bogus_table.column = 1') end end @@ -733,7 +733,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}" Post.find(post_id).update_column :type, class_name klass = Object.const_set(class_name, Class.new(ActiveRecord::Base)) - klass.set_table_name 'posts' + klass.table_name = 'posts' klass.send(association, association_name, :as => :taggable, :dependent => dependency) klass.find(post_id) end diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb index 530f5212a2..03d99d19f6 100644 --- a/activerecord/test/cases/associations/nested_through_associations_test.rb +++ b/activerecord/test/cases/associations/nested_through_associations_test.rb @@ -505,7 +505,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase def test_nested_has_many_through_with_conditions_on_through_associations_preload_via_joins # Pointless condition to force single-query loading assert_includes_and_joins_equal( - Author.where('tags.id = tags.id'), + Author.where('tags.id = tags.id').references(:tags), [authors(:bob)], :misc_post_first_blue_tags ) end @@ -526,7 +526,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase def test_nested_has_many_through_with_conditions_on_source_associations_preload_via_joins # Pointless condition to force single-query loading assert_includes_and_joins_equal( - Author.where('tags.id = tags.id'), + Author.where('tags.id = tags.id').references(:tags), [authors(:bob)], :misc_post_first_blue_tags_2 ) end @@ -545,6 +545,15 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase assert_equal [organizations(:nsa)], organizations end + def test_nested_has_many_through_should_not_be_autosaved + c = Categorization.new + c.author = authors(:david) + c.post_taggings.to_a + assert !c.post_taggings.empty? + c.save + assert !c.post_taggings.empty? + end + private def assert_includes_and_joins_equal(query, expected, association) diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index ffe2993e0f..017905e0ac 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require 'models/computer' require 'models/developer' require 'models/project' require 'models/company' @@ -28,7 +29,7 @@ class AssociationsTest < ActiveRecord::TestCase molecule.electrons.create(:name => 'electron_1') molecule.electrons.create(:name => 'electron_2') - liquids = Liquid.includes(:molecules => :electrons).where('molecules.id is not null') + liquids = Liquid.includes(:molecules => :electrons).references(:molecules).where('molecules.id is not null') assert_equal 1, liquids[0].molecules.length end @@ -128,6 +129,11 @@ class AssociationsTest < ActiveRecord::TestCase end end + def test_association_with_references + firm = companies(:first_firm) + assert_equal ['foo'], firm.association_with_references.scoped.references_values + end + end class AssociationProxyTest < ActiveRecord::TestCase @@ -273,3 +279,18 @@ class OverridingAssociationsTest < ActiveRecord::TestCase ) end end + +class GeneratedMethodsTest < ActiveRecord::TestCase + fixtures :developers, :computers, :posts, :comments + def test_association_methods_override_attribute_methods_of_same_name + assert_equal(developers(:david), computers(:workstation).developer) + # this next line will fail if the attribute methods module is generated lazily + # after the association methods module is generated + assert_equal(developers(:david), computers(:workstation).developer) + assert_equal(developers(:david).id, computers(:workstation)[:developer]) + end + + def test_model_method_overrides_association_method + assert_equal(comments(:greetings).body, posts(:welcome).first_comment) + end +end diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb index e03ed33591..764305459d 100644 --- a/activerecord/test/cases/attribute_methods/read_test.rb +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'active_support/core_ext/object/inclusion' +require 'thread' module ActiveRecord module AttributeMethods @@ -14,8 +15,18 @@ module ActiveRecord def setup @klass = Class.new do + def self.superclass; Base; end + def self.active_record_super; Base; end + def self.base_class; self; end + include ActiveRecord::AttributeMethods - include ActiveRecord::AttributeMethods::Read + + def self.define_attribute_methods + # Created in the inherited/included hook for "proper" ARs + @attribute_methods_mutex ||= Mutex.new + + super + end def self.column_names %w{ one two three } @@ -33,9 +44,6 @@ module ActiveRecord [name, FakeColumn.new(name)] }] end - - def self.serialized_attributes; {}; end - def self.base_class; self; end end end diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index b1b41fed0d..d6de668a17 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -35,6 +35,30 @@ class AttributeMethodsTest < ActiveRecord::TestCase assert !t.attribute_present?("content") end + def test_attribute_present_with_booleans + b1 = Boolean.new + b1.value = false + assert b1.attribute_present?(:value) + + b2 = Boolean.new + b2.value = true + assert b2.attribute_present?(:value) + + b3 = Boolean.new + assert !b3.attribute_present?(:value) + + b4 = Boolean.new + b4.value = false + b4.save! + assert Boolean.find(b4.id).attribute_present?(:value) + end + + def test_caching_nil_primary_key + klass = Class.new(Minimalistic) + klass.expects(:reset_primary_key).returns(nil).once + 2.times { klass.primary_key } + end + def test_attribute_keys_on_new_instance t = Topic.new assert_equal nil, t.title, "The topics table has a title column, so it should be nil" @@ -78,7 +102,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_respond_to? topic = Topic.find(1) assert_respond_to topic, "title" - assert_respond_to topic, "_title" assert_respond_to topic, "title?" assert_respond_to topic, "title=" assert_respond_to topic, :title @@ -95,9 +118,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase assert_not_nil keyboard.key_number assert_equal keyboard.key_number, keyboard.id assert keyboard.respond_to?('key_number') - assert keyboard.respond_to?('_key_number') assert keyboard.respond_to?('id') - assert keyboard.respond_to?('_id') end # Syck calls respond_to? before actually calling initialize @@ -237,8 +258,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase topic.send(:write_attribute, :title, "Still another topic") assert_equal "Still another topic", topic.title - topic.send(:write_attribute, "title", "Still another topic: part 2") + topic[:title] = "Still another topic: part 2" assert_equal "Still another topic: part 2", topic.title + + topic.send(:write_attribute, "title", "Still another topic: part 3") + assert_equal "Still another topic: part 3", topic.title + + topic["title"] = "Still another topic: part 4" + assert_equal "Still another topic: part 4", topic.title end def test_read_attribute @@ -291,6 +318,39 @@ class AttributeMethodsTest < ActiveRecord::TestCase # puts "" end + def test_overridden_write_attribute + topic = Topic.new + def topic.write_attribute(attr_name, value) + super(attr_name, value.downcase) + end + + topic.send(:write_attribute, :title, "Yet another topic") + assert_equal "yet another topic", topic.title + + topic[:title] = "Yet another topic: part 2" + assert_equal "yet another topic: part 2", topic.title + + topic.send(:write_attribute, "title", "Yet another topic: part 3") + assert_equal "yet another topic: part 3", topic.title + + topic["title"] = "Yet another topic: part 4" + assert_equal "yet another topic: part 4", topic.title + end + + def test_overridden_read_attribute + topic = Topic.new + topic.title = "Stop changing the topic" + def topic.read_attribute(attr_name) + super(attr_name).upcase + end + + assert_equal "STOP CHANGING THE TOPIC", topic.send(:read_attribute, "title") + assert_equal "STOP CHANGING THE TOPIC", topic["title"] + + assert_equal "STOP CHANGING THE TOPIC", topic.send(:read_attribute, :title) + assert_equal "STOP CHANGING THE TOPIC", topic[:title] + end + def test_read_overridden_attribute topic = Topic.new(:title => 'a') def topic.title() 'b' end @@ -489,6 +549,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end + def test_write_time_to_date_attributes + in_time_zone "Pacific Time (US & Canada)" do + record = @target.new + record.last_read = Time.utc(2010, 1, 1, 10) + assert_equal Date.civil(2010, 1, 1), record.last_read + end + end + def test_time_attributes_are_retrieved_in_current_time_zone in_time_zone "Pacific Time (US & Canada)" do utc_time = Time.utc(2008, 1, 1) @@ -524,6 +592,17 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end + def test_setting_time_zone_aware_read_attribute + utc_time = Time.utc(2008, 1, 1) + cst_time = utc_time.in_time_zone("Central Time (US & Canada)") + in_time_zone "Pacific Time (US & Canada)" do + record = @target.create(:written_on => cst_time).reload + assert_equal utc_time, record[:written_on] + assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record[:written_on].time_zone + assert_equal Time.utc(2007, 12, 31, 16), record[:written_on].time + end + end + def test_setting_time_zone_aware_attribute_with_string utc_time = Time.utc(2008, 1, 1) (-11..13).each do |timezone_offset| @@ -543,6 +622,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase record = @target.new record.written_on = ' ' assert_nil record.written_on + assert_nil record[:written_on] end end @@ -657,7 +737,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase topic = Topic.new(:id => 5) topic.id = 5 - topic.method(:id).owner.send(:remove_method, :id) + topic.method(:id).owner.send(:undef_method, :id) assert_deprecated do assert_equal 5, topic.id @@ -666,19 +746,39 @@ class AttributeMethodsTest < ActiveRecord::TestCase Topic.undefine_attribute_methods end + def test_read_attribute_with_nil_should_not_asplode + assert_equal nil, Topic.new.read_attribute(nil) + end + + # If B < A, and A defines an accessor for 'foo', we don't want to override + # that by defining a 'foo' method in the generated methods module for B. + # (That module will be inserted between the two, e.g. [B, <GeneratedAttributes>, A].) + def test_inherited_custom_accessors + klass = Class.new(ActiveRecord::Base) do + self.table_name = "topics" + self.abstract_class = true + def title; "omg"; end + def title=(val); self.author_name = val; end + end + subklass = Class.new(klass) + [klass, subklass].each(&:define_attribute_methods) + + topic = subklass.find(1) + assert_equal "omg", topic.title + + topic.title = "lol" + assert_equal "lol", topic.author_name + end + private def cached_columns - @cached_columns ||= (time_related_columns_on_topic + serialized_columns_on_topic).map(&:name) + @cached_columns ||= time_related_columns_on_topic.map(&:name) end def time_related_columns_on_topic Topic.columns.select { |c| c.type.in?([:time, :date, :datetime, :timestamp]) } end - def serialized_columns_on_topic - Topic.columns.select { |c| Topic.serialized_attributes.include?(c.name) } - end - def in_time_zone(zone) old_zone = Time.zone old_tz = ActiveRecord::Base.time_zone_aware_attributes diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 4ad2cdfc7e..1376810adf 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -347,6 +347,17 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test client.save! assert_no_queries { assert_equal apple, client.firm } end + + def test_validation_does_not_validate_stale_association_target + valid_developer = Developer.create!(:name => "Dude", :salary => 50_000) + invalid_developer = Developer.new() + + auditlog = AuditLog.new(:message => "foo") + auditlog.developer = invalid_developer + auditlog.developer_id = valid_developer.id + + assert auditlog.valid? + end end class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase @@ -575,6 +586,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @ship = @pirate.create_ship(:name => 'Nights Dirty Lightning') end @@ -897,6 +909,7 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @ship = @pirate.create_ship(:name => 'Nights Dirty Lightning') end @@ -1020,6 +1033,7 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @ship = Ship.create(:name => 'Nights Dirty Lightning') @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?") end @@ -1268,6 +1282,7 @@ class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @association_name = :birds @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -1282,6 +1297,7 @@ class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::T self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @association_name = :parrots @habtm = true @@ -1297,6 +1313,7 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @pirate.birds.create(:name => 'cookoo') end @@ -1313,6 +1330,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @pirate.create_ship(:name => 'titanic') super @@ -1335,6 +1353,7 @@ class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord:: self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") end @@ -1355,6 +1374,7 @@ class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::Test self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") end @@ -1377,6 +1397,7 @@ class TestAutosaveAssociationValidationMethodsGeneration < ActiveRecord::TestCas self.use_transactional_fixtures = false unless supports_savepoints? def setup + super @pirate = Pirate.new end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 12c1cfb30e..d70525b57d 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -23,10 +23,18 @@ require 'models/edge' require 'models/joke' require 'models/bulb' require 'models/bird' +require 'models/teapot' require 'rexml/document' require 'active_support/core_ext/exception' require 'bcrypt' +class FirstAbstractClass < ActiveRecord::Base + self.abstract_class = true +end +class SecondAbstractClass < FirstAbstractClass + self.abstract_class = true +end +class Photo < SecondAbstractClass; end class Category < ActiveRecord::Base; end class Categorization < ActiveRecord::Base; end class Smarts < ActiveRecord::Base; end @@ -69,6 +77,16 @@ end class BasicsTest < ActiveRecord::TestCase fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts + def test_generated_methods_modules + modules = Computer.ancestors + assert modules.include?(Computer::GeneratedFeatureMethods) + assert_equal(Computer::GeneratedFeatureMethods, Computer.generated_feature_methods) + assert(modules.index(Computer.generated_attribute_methods) > modules.index(Computer.generated_feature_methods), + "generated_attribute_methods must be higher in inheritance hierarchy than generated_feature_methods") + assert_not_equal Computer.generated_feature_methods, Post.generated_feature_methods + assert(modules.index(Computer.generated_attribute_methods) < modules.index(ActiveRecord::Base.ancestors[1])) + end + def test_column_names_are_escaped conn = ActiveRecord::Base.connection classname = conn.class.name[/[^:]*$/] @@ -169,6 +187,31 @@ class BasicsTest < ActiveRecord::TestCase end end + def test_previously_changed + topic = Topic.find :first + topic.title = '<3<3<3' + assert_equal({}, topic.previous_changes) + + topic.save! + expected = ["The First Topic", "<3<3<3"] + assert_equal(expected, topic.previous_changes['title']) + end + + def test_previously_changed_dup + topic = Topic.find :first + topic.title = '<3<3<3' + topic.save! + + t2 = topic.dup + + assert_equal(topic.previous_changes, t2.previous_changes) + + topic.title = "lolwut" + topic.save! + + assert_not_equal(topic.previous_changes, t2.previous_changes) + end + def test_preserving_time_objects assert_kind_of( Time, Topic.find(1).bonus_time, @@ -561,10 +604,12 @@ class BasicsTest < ActiveRecord::TestCase weird = Weird.create('a$b' => 'value') weird.reload assert_equal 'value', weird.send('a$b') + assert_equal 'value', weird.read_attribute('a$b') weird.update_column('a$b', 'value2') weird.reload assert_equal 'value2', weird.send('a$b') + assert_equal 'value2', weird.read_attribute('a$b') end def test_multiparameter_attributes_on_date @@ -644,7 +689,7 @@ class BasicsTest < ActiveRecord::TestCase } topic = Topic.find(1) topic.attributes = attributes - assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on + assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on end def test_multiparameter_attributes_on_time_with_no_date @@ -893,7 +938,7 @@ class BasicsTest < ActiveRecord::TestCase } topic = Topic.find(1) topic.attributes = attributes - assert_equal Time.local(2000, 1, 1, 5, 42, 0), topic.bonus_time + assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time end def test_boolean @@ -947,10 +992,9 @@ class BasicsTest < ActiveRecord::TestCase assert_equal "b", duped_topic.title # test if the attribute values have been duped - topic.title = {"a" => "b"} duped_topic = topic.dup - duped_topic.title["a"] = "c" - assert_equal "b", topic.title["a"] + duped_topic.title.replace "c" + assert_equal "a", topic.title # test if attributes set as part of after_initialize are duped correctly assert_equal topic.author_email_address, duped_topic.author_email_address @@ -961,8 +1005,7 @@ class BasicsTest < ActiveRecord::TestCase assert_not_equal duped_topic.id, topic.id duped_topic.reload - # FIXME: I think this is poor behavior, and will fix it with #5686 - assert_equal({'a' => 'c'}.to_yaml, duped_topic.title) + assert_equal("c", duped_topic.title) end def test_dup_with_aggregate_of_same_name_as_attribute @@ -1061,7 +1104,10 @@ class BasicsTest < ActiveRecord::TestCase # TODO: extend defaults tests to other databases! if current_adapter?(:PostgreSQLAdapter) def test_default + tz = Default.default_timezone + Default.default_timezone = :local default = Default.new + Default.default_timezone = tz # fixed dates / times assert_equal Date.new(2004, 1, 1), default.fixed_date @@ -1185,19 +1231,6 @@ class BasicsTest < ActiveRecord::TestCase assert(auto.id > 0) end - def quote_column_name(name) - "<#{name}>" - end - - def test_quote_keys - ar = AutoId.new - source = {"foo" => "bar", "baz" => "quux"} - actual = ar.send(:quote_columns, self, source) - inverted = actual.invert - assert_equal("<foo>", inverted["bar"]) - assert_equal("<baz>", inverted["quux"]) - end - def test_sql_injection_via_find assert_raise(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do Topic.find("123456 OR id > 0") @@ -1235,6 +1268,27 @@ class BasicsTest < ActiveRecord::TestCase assert_equal(myobj, topic.content) end + def test_serialized_attribute_in_base_class + Topic.serialize("content", Hash) + + hash = { 'content1' => 'value1', 'content2' => 'value2' } + important_topic = ImportantTopic.create("content" => hash) + assert_equal(hash, important_topic.content) + + important_topic.reload + assert_equal(hash, important_topic.content) + end + + def test_serialized_attribute_declared_in_subclass + hash = { 'important1' => 'value1', 'important2' => 'value2' } + important_topic = ImportantTopic.create("important" => hash) + assert_equal(hash, important_topic.important) + + important_topic.reload + assert_equal(hash, important_topic.important) + assert_equal(hash, important_topic.read_attribute(:important)) + end + def test_serialized_time_attribute myobj = Time.local(2008,1,1,1,0) topic = Topic.create("content" => myobj).reload @@ -1247,11 +1301,24 @@ class BasicsTest < ActiveRecord::TestCase assert_equal(myobj, topic.content) end - def test_nil_serialized_attribute_with_class_constraint + def test_nil_serialized_attribute_without_class_constraint topic = Topic.new assert_nil topic.content end + def test_nil_not_serialized_without_class_constraint + assert Topic.new(:content => nil).save + assert_equal 1, Topic.where(:content => nil).count + end + + def test_nil_not_serialized_with_class_constraint + Topic.serialize :content, Hash + assert Topic.new(:content => nil).save + assert_equal 1, Topic.where(:content => nil).count + ensure + Topic.serialize(:content) + end + def test_should_raise_exception_on_serialized_attribute_with_type_mismatch myobj = MyObject.new('value1', 'value2') topic = Topic.new(:content => myobj) @@ -1359,22 +1426,6 @@ class BasicsTest < ActiveRecord::TestCase assert_equal author_name, Topic.find(topic.id).author_name end - if RUBY_VERSION < '1.9' - def test_quote_chars - with_kcode('UTF8') do - str = 'The Narrator' - topic = Topic.create(:author_name => str) - assert_equal str, topic.author_name - - assert_kind_of ActiveSupport::Multibyte.proxy_class, str.mb_chars - topic = Topic.find_by_author_name(str.mb_chars) - - assert_kind_of Topic, topic - assert_equal str, topic.author_name, "The right topic should have been found by name even with name passed as Chars" - end - end - end - def test_toggle_attribute assert !topics(:first).approved? topics(:first).toggle!(:approved) @@ -1401,86 +1452,48 @@ class BasicsTest < ActiveRecord::TestCase assert_equal dev, dev.reload end - def test_define_attr_method_with_value - k = Class.new( ActiveRecord::Base ) - k.send(:define_attr_method, :table_name, "foo") - assert_equal "foo", k.table_name - end - - def test_define_attr_method_with_block - k = Class.new( ActiveRecord::Base ) do - class << self - attr_accessor :foo_key - end - end - k.foo_key = "id" - k.send(:define_attr_method, :foo_key) { "sys_" + original_foo_key } - assert_equal "sys_id", k.foo_key - end - - def test_set_table_name_with_value - k = Class.new( ActiveRecord::Base ) - k.table_name = "foo" - assert_equal "foo", k.table_name - k.set_table_name "bar" - assert_equal "bar", k.table_name - end - def test_switching_between_table_name assert_difference("GoodJoke.count") do - Joke.set_table_name "cold_jokes" + Joke.table_name = "cold_jokes" Joke.create - Joke.set_table_name "funny_jokes" + Joke.table_name = "funny_jokes" Joke.create end end + def test_set_table_name_symbol_converted_to_string + Joke.table_name = :cold_jokes + assert_equal 'cold_jokes', Joke.table_name + end + def test_quoted_table_name_after_set_table_name klass = Class.new(ActiveRecord::Base) - klass.set_table_name "foo" + klass.table_name = "foo" assert_equal "foo", klass.table_name assert_equal klass.connection.quote_table_name("foo"), klass.quoted_table_name - klass.set_table_name "bar" + klass.table_name = "bar" assert_equal "bar", klass.table_name assert_equal klass.connection.quote_table_name("bar"), klass.quoted_table_name end - def test_set_table_name_with_block - k = Class.new( ActiveRecord::Base ) - k.set_table_name { "ks" } - assert_equal "ks", k.table_name - end - - def test_set_primary_key_with_value - k = Class.new( ActiveRecord::Base ) - k.primary_key = "foo" - assert_equal "foo", k.primary_key - k.set_primary_key "bar" - assert_equal "bar", k.primary_key - end - - def test_set_primary_key_with_block - k = Class.new( ActiveRecord::Base ) - k.primary_key = 'id' - k.set_primary_key { "sys_" + original_primary_key } - assert_equal "sys_id", k.primary_key - end - - def test_set_inheritance_column_with_value + def test_set_table_name_with_inheritance k = Class.new( ActiveRecord::Base ) - k.inheritance_column = "foo" - assert_equal "foo", k.inheritance_column - k.set_inheritance_column "bar" - assert_equal "bar", k.inheritance_column + def k.name; "Foo"; end + def k.table_name; super + "ks"; end + assert_equal "foosks", k.table_name end - def test_set_inheritance_column_with_block - k = Class.new( ActiveRecord::Base ) - k.set_inheritance_column { original_inheritance_column + "_id" } - assert_equal "type_id", k.inheritance_column + def test_sequence_name_with_abstract_class + ak = Class.new(ActiveRecord::Base) + ak.abstract_class = true + k = Class.new(ak) + k.table_name = "projects" + orig_name = k.sequence_name + return skip "sequences not supported by db" unless orig_name + assert_equal k.reset_sequence_name, orig_name end def test_count_with_join @@ -1582,7 +1595,7 @@ class BasicsTest < ActiveRecord::TestCase Developer.find(:all) end assert developers.size >= 2 - for i in 1...developers.size + (1...developers.size).each do |i| assert developers[i-1].salary >= developers[i].salary end end @@ -1673,10 +1686,7 @@ class BasicsTest < ActiveRecord::TestCase end def test_descends_from_active_record - # Tries to call Object.abstract_class? - assert_raise(NoMethodError) do - ActiveRecord::Base.descends_from_active_record? - end + assert !ActiveRecord::Base.descends_from_active_record? # Abstract subclass of AR::Base. assert LoosePerson.descends_from_active_record? @@ -1699,6 +1709,10 @@ class BasicsTest < ActiveRecord::TestCase # Concrete subclasses an abstract class which has a type column. assert !SubStiPost.descends_from_active_record? + + assert Teapot.descends_from_active_record? + assert !OtherTeapot.descends_from_active_record? + assert CoolTeapot.descends_from_active_record? end def test_find_on_abstract_base_class_doesnt_use_type_condition @@ -1732,7 +1746,7 @@ class BasicsTest < ActiveRecord::TestCase def test_inspect_instance topic = topics(:first) - assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}", updated_at: "#{topic.updated_at.to_s(:db)}">), topic.inspect + assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", important: nil, approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}", updated_at: "#{topic.updated_at.to_s(:db)}">), topic.inspect end def test_inspect_new_instance @@ -1761,10 +1775,18 @@ class BasicsTest < ActiveRecord::TestCase assert_equal "The First Topic", topics(:first).becomes(Reply).title end + def test_becomes_includes_errors + company = Company.new(:name => nil) + assert !company.valid? + original_errors = company.errors + client = company.becomes(Client) + assert_equal original_errors, client.errors + end + def test_silence_sets_log_level_to_error_in_block original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::DEBUG ActiveRecord::Base.silence do ActiveRecord::Base.logger.warn "warn" @@ -1778,7 +1800,7 @@ class BasicsTest < ActiveRecord::TestCase def test_silence_sets_log_level_back_to_level_before_yield original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::WARN ActiveRecord::Base.silence do end @@ -1790,7 +1812,7 @@ class BasicsTest < ActiveRecord::TestCase def test_benchmark_with_log_level original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::WARN ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count } ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count } @@ -1805,10 +1827,8 @@ class BasicsTest < ActiveRecord::TestCase def test_benchmark_with_use_silence original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) - ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => true) { ActiveRecord::Base.logger.debug "Loud" } + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" } - assert_no_match(/Loud/, log.string) assert_match(/Quiet/, log.string) ensure ActiveRecord::Base.logger = original_logger @@ -1840,9 +1860,9 @@ class BasicsTest < ActiveRecord::TestCase def test_clear_cache! # preheat cache - c1 = Post.columns + c1 = Post.connection.schema_cache.columns['posts'] ActiveRecord::Base.clear_cache! - c2 = Post.columns + c2 = Post.connection.schema_cache.columns['posts'] assert_not_equal c1, c2 end @@ -1859,11 +1879,6 @@ class BasicsTest < ActiveRecord::TestCase end def test_marshal_round_trip - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - expected = posts(:welcome) marshalled = Marshal.dump(expected) actual = Marshal.load(marshalled) @@ -1872,11 +1887,6 @@ class BasicsTest < ActiveRecord::TestCase end def test_marshal_new_record_round_trip - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - marshalled = Marshal.dump(Post.new) post = Marshal.load(marshalled) @@ -1884,11 +1894,6 @@ class BasicsTest < ActiveRecord::TestCase end def test_marshalling_with_associations - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - post = Post.new post.comments.build @@ -1907,7 +1912,7 @@ class BasicsTest < ActiveRecord::TestCase assert_equal [], NonExistentTable.attribute_names end - def test_attribtue_names_on_abstract_class + def test_attribute_names_on_abstract_class assert_equal [], AbstractCompany.attribute_names end @@ -1935,4 +1940,23 @@ class BasicsTest < ActiveRecord::TestCase dev.update_attribute(:updated_at, nil) assert_match(/\/#{dev.id}$/, dev.cache_key) end + + def test_uniq_delegates_to_scoped + scope = stub + Bird.stubs(:scoped).returns(mock(:uniq => scope)) + assert_equal scope, Bird.uniq + end + + def test_active_record_super + assert_equal ActiveRecord::Model, ActiveRecord::Base.active_record_super + assert_equal ActiveRecord::Base, Topic.active_record_super + assert_equal Topic, ImportantTopic.active_record_super + assert_equal ActiveRecord::Model, Teapot.active_record_super + assert_equal Teapot, OtherTeapot.active_record_super + assert_equal ActiveRecord::Model, CoolTeapot.active_record_super + end + + def test_table_name_with_2_abstract_subclasses + assert_equal "photos", Photo.table_name + end end diff --git a/activerecord/test/cases/binary_test.rb b/activerecord/test/cases/binary_test.rb index 06c14cb108..25d2896ab0 100644 --- a/activerecord/test/cases/binary_test.rb +++ b/activerecord/test/cases/binary_test.rb @@ -8,11 +8,11 @@ unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter) require 'models/binary' class BinaryTest < ActiveRecord::TestCase - FIXTURES = %w(flowers.jpg example.log) + FIXTURES = %w(flowers.jpg example.log test.txt) def test_mixed_encoding str = "\x80" - str.force_encoding('ASCII-8BIT') if str.respond_to?(:force_encoding) + str.force_encoding('ASCII-8BIT') binary = Binary.new :name => 'いただきます!', :data => str binary.save! @@ -23,7 +23,7 @@ unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter) # Mysql adapter doesn't properly encode things, so we have to do it if current_adapter?(:MysqlAdapter) - name.force_encoding('UTF-8') if name.respond_to?(:force_encoding) + name.force_encoding('UTF-8') end assert_equal 'いただきます!', name end @@ -33,7 +33,7 @@ unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter) FIXTURES.each do |filename| data = File.read(ASSETS_ROOT + "/#{filename}") - data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding) + data.force_encoding('ASCII-8BIT') data.freeze bin = Binary.new(:data => data) diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index c38814713a..7c9ebf528e 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/company' +require "models/contract" require 'models/topic' require 'models/edge' require 'models/club' @@ -48,11 +49,11 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_get_maximum_of_field_with_include - assert_equal 55, Account.maximum(:credit_limit, :include => :firm, :conditions => "companies.name != 'Summit'") + assert_equal 55, Account.maximum(:credit_limit, :include => :firm, :references => :companies, :conditions => "companies.name != 'Summit'") end def test_should_get_maximum_of_field_with_scoped_include - Account.send :with_scope, :find => { :include => :firm, :conditions => "companies.name != 'Summit'" } do + Account.send :with_scope, :find => { :include => :firm, :references => :companies, :conditions => "companies.name != 'Summit'" } do assert_equal 55, Account.maximum(:credit_limit) end end @@ -269,7 +270,7 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_not_modify_options_when_using_includes - options = {:conditions => 'companies.id > 1', :include => :firm} + options = {:conditions => 'companies.id > 1', :include => :firm, :references => :companies} options_copy = options.dup Account.count(:all, options) @@ -446,4 +447,35 @@ class CalculationsTest < ActiveRecord::TestCase distinct_authors_for_approved_count = Topic.group(:approved).count(:author_name, :distinct => true)[true] assert_equal distinct_authors_for_approved_count, 2 end + + def test_pluck + assert_equal [1,2,3,4], Topic.order(:id).pluck(:id) + end + + def test_pluck_type_cast + topic = topics(:first) + relation = Topic.where(:id => topic.id) + assert_equal [ topic.approved ], relation.pluck(:approved) + assert_equal [ topic.last_read ], relation.pluck(:last_read) + assert_equal [ topic.written_on ], relation.pluck(:written_on) + end + + def test_pluck_and_uniq + assert_equal [50, 53, 55, 60], Account.order(:credit_limit).uniq.pluck(:credit_limit) + end + + def test_pluck_in_relation + company = Company.first + contract = company.contracts.create! + assert_equal [contract.id], company.contracts.pluck(:id) + end + + def test_pluck_with_serialization + t = Topic.create!(:content => { :foo => :bar }) + assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content) + end + + def test_pluck_with_qualified_column_name + assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id") + end end diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index 7f4d25790b..7690769226 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class CallbackDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' class << self def callback_string(callback_method) @@ -48,7 +48,7 @@ class CallbackDeveloperWithFalseValidation < CallbackDeveloper end class ParentDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' attr_accessor :after_save_called before_validation {|record| record.after_save_called = true} end @@ -58,7 +58,7 @@ class ChildDeveloper < ParentDeveloper end class RecursiveCallbackDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' before_save :on_before_save after_save :on_after_save @@ -79,7 +79,7 @@ class RecursiveCallbackDeveloper < ActiveRecord::Base end class ImmutableDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' validates_inclusion_of :salary, :in => 50000..200000 @@ -98,7 +98,7 @@ class ImmutableDeveloper < ActiveRecord::Base end class ImmutableMethodDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' validates_inclusion_of :salary, :in => 50000..200000 @@ -118,7 +118,7 @@ class ImmutableMethodDeveloper < ActiveRecord::Base end class OnCallbacksDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' before_validation { history << :before_validation } before_validation(:on => :create){ history << :before_validation_on_create } @@ -138,7 +138,7 @@ class OnCallbacksDeveloper < ActiveRecord::Base end class CallbackCancellationDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' attr_reader :after_save_called, :after_create_called, :after_update_called, :after_destroy_called attr_accessor :cancel_before_save, :cancel_before_create, :cancel_before_update, :cancel_before_destroy diff --git a/activerecord/test/cases/column_test.rb b/activerecord/test/cases/column_test.rb new file mode 100644 index 0000000000..ccc57cb876 --- /dev/null +++ b/activerecord/test/cases/column_test.rb @@ -0,0 +1,29 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class ColumnTest < ActiveRecord::TestCase + def test_type_cast_boolean + column = Column.new("field", nil, "boolean") + assert column.type_cast(true) + assert column.type_cast(1) + assert column.type_cast('1') + assert column.type_cast('t') + assert column.type_cast('T') + assert column.type_cast('true') + assert column.type_cast('TRUE') + assert column.type_cast('on') + assert column.type_cast('ON') + assert !column.type_cast(false) + assert !column.type_cast(0) + assert !column.type_cast('0') + assert !column.type_cast('f') + assert !column.type_cast('F') + assert !column.type_cast('false') + assert !column.type_cast('FALSE') + assert !column.type_cast('off') + assert !column.type_cast('OFF') + end + end + end +end diff --git a/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb new file mode 100644 index 0000000000..7dc6e8afcb --- /dev/null +++ b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb @@ -0,0 +1,54 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class AbstractAdapterTest < ActiveRecord::TestCase + attr_reader :adapter + + def setup + @adapter = AbstractAdapter.new nil, nil + end + + def test_in_use? + # FIXME: change to refute in Rails 4.0 / mt + assert !adapter.in_use?, 'adapter is not in use' + assert adapter.lease, 'lease adapter' + assert adapter.in_use?, 'adapter is in use' + end + + def test_lease_twice + assert adapter.lease, 'should lease adapter' + assert !adapter.lease, 'should not lease adapter' + end + + def test_last_use + assert !adapter.last_use + adapter.lease + assert adapter.last_use + end + + def test_expire_mutates_in_use + assert adapter.lease, 'lease adapter' + assert adapter.in_use?, 'adapter is in use' + adapter.expire + assert !adapter.in_use?, 'adapter is in use' + end + + def test_close + pool = ConnectionPool.new(ConnectionSpecification.new({}, nil)) + pool.connections << adapter + adapter.pool = pool + + # Make sure the pool marks the connection in use + assert_equal adapter, pool.connection + assert adapter.in_use? + + # Close should put the adapter back in the pool + adapter.close + assert !adapter.in_use? + + assert_equal adapter, pool.connection + end + end + end +end diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index bd0d161838..dc99ac665c 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -8,6 +8,9 @@ module ActiveRecord @handler.establish_connection 'america', Base.connection_pool.spec @klass = Class.new do def self.name; 'america'; end + class << self + alias active_record_super superclass + end end @subklass = Class.new(@klass) do def self.name; 'north america'; end @@ -40,8 +43,6 @@ module ActiveRecord def test_retrieve_connection_pool_uses_superclass_pool_after_subclass_establish_and_remove @handler.establish_connection 'north america', Base.connection_pool.spec - assert_not_same @handler.retrieve_connection_pool(@klass), - @handler.retrieve_connection_pool(@subklass) @handler.remove_connection @subklass assert_same @handler.retrieve_connection_pool(@klass), diff --git a/activerecord/test/cases/connection_adapters/connection_specification_test.rb b/activerecord/test/cases/connection_adapters/connection_specification_test.rb new file mode 100644 index 0000000000..ea2196cda2 --- /dev/null +++ b/activerecord/test/cases/connection_adapters/connection_specification_test.rb @@ -0,0 +1,12 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class ConnectionSpecificationTest < ActiveRecord::TestCase + def test_dup_deep_copy_config + spec = ConnectionSpecification.new({ :a => :b }, "bar") + assert_not_equal(spec.config.object_id, spec.dup.config.object_id) + end + end + end +end diff --git a/activerecord/test/cases/connection_adapters/schema_cache_test.rb b/activerecord/test/cases/connection_adapters/schema_cache_test.rb new file mode 100644 index 0000000000..42e39d534c --- /dev/null +++ b/activerecord/test/cases/connection_adapters/schema_cache_test.rb @@ -0,0 +1,44 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class SchemaCacheTest < ActiveRecord::TestCase + def setup + connection = ActiveRecord::Base.connection + @cache = SchemaCache.new connection + end + + def test_primary_key + assert_equal 'id', @cache.primary_keys['posts'] + end + + def test_primary_key_for_non_existent_table + assert_nil @cache.primary_keys['omgponies'] + end + + def test_caches_columns + columns = @cache.columns['posts'] + assert_equal columns, @cache.columns['posts'] + end + + def test_caches_columns_hash + columns_hash = @cache.columns_hash['posts'] + assert_equal columns_hash, @cache.columns_hash['posts'] + end + + def test_clearing + @cache.columns['posts'] + @cache.columns_hash['posts'] + @cache.tables['posts'] + @cache.primary_keys['posts'] + + @cache.clear! + + assert_equal 0, @cache.columns.size + assert_equal 0, @cache.columns_hash.size + assert_equal 0, @cache.tables.size + assert_equal 0, @cache.primary_keys.size + end + end + end +end diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb index f554ceef35..496cd78136 100644 --- a/activerecord/test/cases/connection_management_test.rb +++ b/activerecord/test/cases/connection_management_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require "rack" module ActiveRecord module ConnectionAdapters @@ -25,40 +26,6 @@ module ActiveRecord assert ActiveRecord::Base.connection_handler.active_connections? end - class FakeBase < ActiveRecord::Base - def self.establish_connection spec - String === spec ? super : spec - end - end - - def test_url_host_no_db - spec = FakeBase.establish_connection 'postgres://foo?encoding=utf8' - assert_equal({ - :adapter => "postgresql", - :database => "", - :host => "foo", - :encoding => "utf8" }, spec) - end - - def test_url_host_db - spec = FakeBase.establish_connection 'postgres://foo/bar?encoding=utf8' - assert_equal({ - :adapter => "postgresql", - :database => "bar", - :host => "foo", - :encoding => "utf8" }, spec) - end - - def test_url_port - spec = FakeBase.establish_connection 'postgres://foo:123?encoding=utf8' - assert_equal({ - :adapter => "postgresql", - :database => "", - :port => 123, - :host => "foo", - :encoding => "utf8" }, spec) - end - def test_app_delegation manager = ConnectionManagement.new(@app) @@ -114,9 +81,10 @@ module ActiveRecord test "proxy is polite to it's body and responds to it" do body = Class.new(String) { def to_path; "/path"; end }.new - proxy = ConnectionManagement::Proxy.new(body) - assert proxy.respond_to?(:to_path) - assert_equal proxy.to_path, "/path" + app = lambda { |_| [200, {}, body] } + response_body = ConnectionManagement.new(app).call(@env)[2] + assert response_body.respond_to?(:to_path) + assert_equal response_body.to_path, "/path" end end end diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 8a0f453127..2c69bfde5b 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -4,6 +4,8 @@ module ActiveRecord module ConnectionAdapters class ConnectionPoolTest < ActiveRecord::TestCase def setup + super + # Keep a duplicate pool so we do not bother others @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec @@ -18,73 +20,76 @@ module ActiveRecord end end - def test_active_connection? - assert !@pool.active_connection? - assert @pool.connection - assert @pool.active_connection? - @pool.release_connection - assert !@pool.active_connection? + def teardown + super + @pool.disconnect! end - def test_pool_caches_columns - columns = @pool.columns['posts'] - assert_equal columns, @pool.columns['posts'] + def test_full_pool_exception + assert_raises(PoolFullError) do + (@pool.size + 1).times do + @pool.checkout + end + end end - def test_pool_caches_columns_hash - columns_hash = @pool.columns_hash['posts'] - assert_equal columns_hash, @pool.columns_hash['posts'] - end + def test_reap_and_active + @pool.checkout + @pool.checkout + @pool.checkout + @pool.timeout = 0 - def test_clearing_column_cache - @pool.columns['posts'] - @pool.columns_hash['posts'] + connections = @pool.connections.dup - @pool.clear_cache! + @pool.reap - assert_equal 0, @pool.columns.size - assert_equal 0, @pool.columns_hash.size + assert_equal connections.length, @pool.connections.length end - def test_primary_key - assert_equal 'id', @pool.primary_keys['posts'] - end + def test_reap_inactive + @pool.checkout + @pool.checkout + @pool.checkout + @pool.timeout = 0 - def test_primary_key_for_non_existent_table - assert_equal 'id', @pool.primary_keys['omgponies'] - end + connections = @pool.connections.dup + connections.each do |conn| + conn.extend(Module.new { def active?; false; end; }) + end - def test_primary_key_is_set_on_columns - posts_columns = @pool.columns_hash['posts'] - assert posts_columns['id'].primary + @pool.reap - (posts_columns.keys - ['id']).each do |key| - assert !posts_columns[key].primary - end + assert_equal 0, @pool.connections.length + ensure + connections.each(&:close) end - def test_clear_stale_cached_connections! - pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec - - threads = [ - Thread.new { pool.connection }, - Thread.new { pool.connection }] + def test_remove_connection + conn = @pool.checkout + assert conn.in_use? - threads.map { |t| t.join } + length = @pool.connections.length + @pool.remove conn + assert conn.in_use? + assert_equal(length - 1, @pool.connections.length) + ensure + conn.close + end - pool.extend Module.new { - attr_accessor :checkins - def checkin conn - @checkins << conn - conn.object_id - end - } - pool.checkins = [] + def test_remove_connection_for_thread + conn = @pool.connection + @pool.remove conn + assert_not_equal(conn, @pool.connection) + ensure + conn.close if conn + end - cleared_threads = pool.clear_stale_cached_connections! - assert((cleared_threads - threads.map { |x| x.object_id }).empty?, - "threads should have been removed") - assert_equal pool.checkins.length, threads.length + def test_active_connection? + assert !@pool.active_connection? + assert @pool.connection + assert @pool.active_connection? + @pool.release_connection + assert !@pool.active_connection? end def test_checkout_behaviour @@ -96,24 +101,16 @@ module ActiveRecord threads << Thread.new(i) do |pool_count| connection = pool.connection assert_not_nil connection + connection.close end end - threads.each {|t| t.join} + threads.each(&:join) Thread.new do - threads.each do |t| - thread_ids = pool.instance_variable_get(:@reserved_connections).keys - assert thread_ids.include?(t.object_id) - end - - pool.connection - threads.each do |t| - thread_ids = pool.instance_variable_get(:@reserved_connections).keys - assert !thread_ids.include?(t.object_id) - end - end.join() - + assert pool.connection + pool.connection.close + end.join end def test_automatic_reconnect= diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb new file mode 100644 index 0000000000..e6cb1b9521 --- /dev/null +++ b/activerecord/test/cases/connection_specification/resolver_test.rb @@ -0,0 +1,41 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class ConnectionSpecification + class ResolverTest < ActiveRecord::TestCase + def resolve(spec) + Resolver.new(spec, {}).spec.config + end + + def test_url_host_no_db + spec = resolve 'mysql://foo?encoding=utf8' + assert_equal({ + :adapter => "mysql", + :database => "", + :host => "foo", + :encoding => "utf8" }, spec) + end + + def test_url_host_db + spec = resolve 'mysql://foo/bar?encoding=utf8' + assert_equal({ + :adapter => "mysql", + :database => "bar", + :host => "foo", + :encoding => "utf8" }, spec) + end + + def test_url_port + spec = resolve 'mysql://foo:123?encoding=utf8' + assert_equal({ + :adapter => "mysql", + :database => "", + :port => 123, + :host => "foo", + :encoding => "utf8" }, spec) + end + end + end + end +end diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb index 3ed96a3ec8..cd3d19e783 100644 --- a/activerecord/test/cases/counter_cache_test.rb +++ b/activerecord/test/cases/counter_cache_test.rb @@ -6,9 +6,11 @@ require 'models/engine' require 'models/reply' require 'models/category' require 'models/categorization' +require 'models/dog' +require 'models/dog_lover' class CounterCacheTest < ActiveRecord::TestCase - fixtures :topics, :categories, :categorizations, :cars + fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers class ::SpecialTopic < ::Topic has_many :special_replies, :foreign_key => 'parent_id' @@ -61,7 +63,7 @@ class CounterCacheTest < ActiveRecord::TestCase end end - test "reset counter should with belongs_to which has class_name" do + test "reset counter with belongs_to which has class_name" do car = cars(:honda) assert_nothing_raised do Car.reset_counters(car.id, :engines) @@ -71,6 +73,20 @@ class CounterCacheTest < ActiveRecord::TestCase end end + test "reset the right counter if two have the same class_name" do + david = dog_lovers(:david) + + DogLover.increment_counter(:bred_dogs_count, david.id) + DogLover.increment_counter(:trained_dogs_count, david.id) + + assert_difference 'david.reload.bred_dogs_count', -1 do + DogLover.reset_counters(david.id, :bred_dogs) + end + assert_difference 'david.reload.trained_dogs_count', -1 do + DogLover.reset_counters(david.id, :trained_dogs) + end + end + test "update counter with initial null value" do category = categories(:general) assert_equal 2, category.categorizations.count diff --git a/activerecord/test/cases/dup_test.rb b/activerecord/test/cases/dup_test.rb index 0236f9b0a1..9705a11387 100644 --- a/activerecord/test/cases/dup_test.rb +++ b/activerecord/test/cases/dup_test.rb @@ -99,5 +99,13 @@ module ActiveRecord assert_not_nil new_topic.created_at end + def test_dup_after_initialize_callbacks + topic = Topic.new + assert Topic.after_initialize_called + Topic.after_initialize_called = false + topic.dup + assert Topic.after_initialize_called + end + end end diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb new file mode 100644 index 0000000000..83c9b6e107 --- /dev/null +++ b/activerecord/test/cases/explain_test.rb @@ -0,0 +1,115 @@ +require 'cases/helper' +require 'models/car' +require 'active_support/core_ext/string/strip' + +if ActiveRecord::Base.connection.supports_explain? + class ExplainTest < ActiveRecord::TestCase + fixtures :cars + + def base + ActiveRecord::Base + end + + def connection + base.connection + end + + def test_logging_query_plan_with_logger + base.logger.expects(:warn).with do |message| + message.starts_with?('EXPLAIN for:') + end + + with_threshold(0) do + Car.where(:name => 'honda').all + end + end + + def test_logging_query_plan_without_logger + original = base.logger + base.logger = nil + + base.logger.expects(:warn).never + + with_threshold(0) do + car = Car.where(:name => 'honda').first + assert_equal 'honda', car.name + end + ensure + base.logger = original + end + + def test_collect_queries_for_explain + base.auto_explain_threshold_in_seconds = nil + queries = Thread.current[:available_queries_for_explain] = [] + + with_threshold(0) do + Car.where(:name => 'honda').all + end + + sql, binds = queries[0] + assert_match "SELECT", sql + assert_match "honda", sql + assert_equal [], binds + ensure + Thread.current[:available_queries_for_explain] = nil + end + + def test_collecting_queries_for_explain + result, queries = ActiveRecord::Base.collecting_queries_for_explain do + Car.where(:name => 'honda').all + end + + sql, binds = queries[0] + assert_match "SELECT", sql + assert_match "honda", sql + assert_equal [], binds + assert_equal [cars(:honda)], result + end + + def test_exec_explain_with_no_binds + sqls = %w(foo bar) + binds = [[], []] + queries = sqls.zip(binds) + + connection.stubs(:explain).returns('query plan foo', 'query plan bar') + expected = sqls.map {|sql| "EXPLAIN for: #{sql}\nquery plan #{sql}"}.join("\n") + assert_equal expected, base.exec_explain(queries) + end + + def test_exec_explain_with_binds + cols = [Object.new, Object.new] + cols[0].expects(:name).returns('wadus') + cols[1].expects(:name).returns('chaflan') + + sqls = %w(foo bar) + binds = [[[cols[0], 1]], [[cols[1], 2]]] + queries = sqls.zip(binds) + + connection.stubs(:explain).returns("query plan foo\n", "query plan bar\n") + expected = <<-SQL.strip_heredoc + EXPLAIN for: #{sqls[0]} [["wadus", 1]] + query plan foo + + EXPLAIN for: #{sqls[1]} [["chaflan", 2]] + query plan bar + SQL + assert_equal expected, base.exec_explain(queries) + end + + def test_silence_auto_explain + base.expects(:collecting_sqls_for_explain).never + base.logger.expects(:warn).never + base.silence_auto_explain do + with_threshold(0) { Car.all } + end + end + + def with_threshold(threshold) + current_threshold = base.auto_explain_threshold_in_seconds + base.auto_explain_threshold_in_seconds = threshold + yield + ensure + base.auto_explain_threshold_in_seconds = current_threshold + end + end +end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 3088ab012f..76c041397a 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -57,6 +57,11 @@ class FinderTest < ActiveRecord::TestCase assert Topic.first.replies.exists? end + # ensures +exists?+ runs valid SQL by excluding order value + def test_exists_with_order + assert Topic.order(:id).uniq.exists? + end + def test_does_not_exist_with_empty_table_and_no_args_given Topic.delete_all assert !Topic.exists? @@ -369,6 +374,10 @@ class FinderTest < ActiveRecord::TestCase assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort end + def test_find_on_hash_conditions_with_array_of_integers_and_ranges + assert_equal [1,2,3,5,6,7,8,9], Comment.find(:all, :conditions => {:id => [1..2, 3, 5, 6..8, 9]}).map(&:id).sort + end + def test_find_on_multiple_hash_conditions assert Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false }) assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) } @@ -872,6 +881,17 @@ class FinderTest < ActiveRecord::TestCase assert_equal 23, sig38.client_of end + def test_find_or_create_from_two_attributes_and_hash + number_of_companies = Company.count + sig38 = Company.find_or_create_by_name_and_firm_id({:name => "38signals", :firm_id => 17, :client_of => 23}) + assert_equal number_of_companies + 1, Company.count + assert_equal sig38, Company.find_or_create_by_name_and_firm_id({:name => "38signals", :firm_id => 17, :client_of => 23}) + assert sig38.persisted? + assert_equal "38signals", sig38.name + assert_equal 17, sig38.firm_id + assert_equal 23, sig38.client_of + end + def test_find_or_create_from_one_aggregate_attribute number_of_customers = Customer.count created_customer = Customer.find_or_create_by_balance(Money.new(123)) @@ -1110,10 +1130,10 @@ class FinderTest < ActiveRecord::TestCase end def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct - assert_equal 2, Post.find(:all, :include => { :authors => :author_address }, :order => ' author_addresses.id DESC ', :limit => 2).size + assert_equal 2, Post.find(:all, :include => { :authors => :author_address }, :order => 'author_addresses.id DESC ', :limit => 2).size assert_equal 3, Post.find(:all, :include => { :author => :author_address, :authors => :author_address}, - :order => ' author_addresses_authors.id DESC ', :limit => 3).size + :order => 'author_addresses_authors.id DESC ', :limit => 3).size end def test_find_with_nil_inside_set_passed_for_one_attribute @@ -1140,7 +1160,10 @@ class FinderTest < ActiveRecord::TestCase end def test_with_limiting_with_custom_select - posts = Post.find(:all, :include => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id') + posts = Post.find( + :all, :include => :author, :select => ' posts.*, authors.id as "author_id"', + :references => :authors, :limit => 3, :order => 'posts.id' + ) assert_equal 3, posts.size assert_equal [0, 1, 1], posts.map(&:author_id).sort end @@ -1154,7 +1177,7 @@ class FinderTest < ActiveRecord::TestCase end def test_find_one_message_with_custom_primary_key - Toy.set_primary_key :name + Toy.primary_key = :name begin Toy.find 'Hello World!' rescue ActiveRecord::RecordNotFound => e diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 866dcefbab..562b370c97 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -1,31 +1,34 @@ -require "cases/helper" -require 'models/post' +require 'cases/helper' +require 'models/admin' +require 'models/admin/account' +require 'models/admin/randomly_named_c1' +require 'models/admin/user' require 'models/binary' -require 'models/topic' +require 'models/book' +require 'models/category' +require 'models/company' require 'models/computer' +require 'models/course' require 'models/developer' -require 'models/company' -require 'models/task' -require 'models/reply' require 'models/joke' -require 'models/course' -require 'models/category' +require 'models/matey' require 'models/parrot' require 'models/pirate' -require 'models/treasure' -require 'models/traffic_light' -require 'models/matey' +require 'models/post' +require 'models/randomly_named_c1' +require 'models/reply' require 'models/ship' -require 'models/book' -require 'models/admin' -require 'models/admin/account' -require 'models/admin/user' +require 'models/task' +require 'models/topic' +require 'models/traffic_light' +require 'models/treasure' require 'tempfile' class FixturesTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_transactional_fixtures = false + # other_topics fixture should not be included here fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights FIXTURES = %w( accounts binaries companies customers @@ -48,11 +51,11 @@ class FixturesTest < ActiveRecord::TestCase def test_broken_yaml_exception badyaml = Tempfile.new ['foo', '.yml'] - badyaml.write 'a: !ruby.yaml.org,2002:str |\nfoo' + badyaml.write 'a: : ' badyaml.flush dir = File.dirname badyaml.path - name =File.basename badyaml.path, '.yml' + name = File.basename badyaml.path, '.yml' assert_raises(ActiveRecord::Fixture::FormatError) do ActiveRecord::Fixtures.create_fixtures(dir, name) end @@ -62,8 +65,9 @@ class FixturesTest < ActiveRecord::TestCase end def test_create_fixtures - ActiveRecord::Fixtures.create_fixtures(FIXTURES_ROOT, "parrots") - assert Parrot.find_by_name('Curious George'), 'George is in the database' + fixtures = ActiveRecord::Fixtures.create_fixtures(FIXTURES_ROOT, "parrots") + assert Parrot.find_by_name('Curious George'), 'George is not in the database' + assert fixtures.detect { |f| f.name == 'parrots' }, "no fixtures named 'parrots' in #{fixtures.map(&:name).inspect}" end def test_multiple_clean_fixtures @@ -73,6 +77,13 @@ class FixturesTest < ActiveRecord::TestCase fixtures_array.each { |fixtures| assert_kind_of(ActiveRecord::Fixtures, fixtures) } end + def test_create_symbol_fixtures + fixtures = ActiveRecord::Fixtures.create_fixtures(FIXTURES_ROOT, :collections, :collections => Course) { Course.connection } + + assert Course.find_by_name('Collection'), 'course is not in the database' + assert fixtures.detect { |f| f.name == 'collections' }, "no fixtures named 'collections' in #{fixtures.map(&:name).inspect}" + end + def test_attributes topics = create_fixtures("topics").first assert_equal("The First Topic", topics["first"]["title"]) @@ -93,7 +104,7 @@ class FixturesTest < ActiveRecord::TestCase # Reset cache to make finds on the new table work ActiveRecord::Fixtures.reset_cache - ActiveRecord::Base.connection.create_table :prefix_topics_suffix do |t| + ActiveRecord::Base.connection.create_table :prefix_other_topics_suffix do |t| t.column :title, :string t.column :author_name, :string t.column :author_email_address, :string @@ -115,23 +126,36 @@ class FixturesTest < ActiveRecord::TestCase ActiveRecord::Base.table_name_prefix = 'prefix_' ActiveRecord::Base.table_name_suffix = '_suffix' - topics = create_fixtures("topics") - - first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'David'") - assert_equal("The First Topic", first_row["title"]) + other_topic_klass = Class.new(ActiveRecord::Base) do + def self.name + "OtherTopic" + end + end - second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'Mary'") - assert_nil(second_row["author_email_address"]) + topics = [create_fixtures("other_topics")].flatten.first # This checks for a caching problem which causes a bug in the fixtures # class-level configuration helper. assert_not_nil topics, "Fixture data inserted, but fixture objects not returned from create" + + first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'David'") + assert_not_nil first_row, "The prefix_other_topics_suffix table appears to be empty despite create_fixtures: the row with author_name = 'David' was not found" + assert_equal("The First Topic", first_row["title"]) + + second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'Mary'") + assert_nil(second_row["author_email_address"]) + + assert_equal :prefix_other_topics_suffix, topics.table_name.to_sym + # This assertion should preferably be the last in the list, because calling + # other_topic_klass.table_name sets a class-level instance variable + assert_equal :prefix_other_topics_suffix, other_topic_klass.table_name.to_sym + ensure # Restore prefix/suffix to its previous values ActiveRecord::Base.table_name_prefix = old_prefix ActiveRecord::Base.table_name_suffix = old_suffix - ActiveRecord::Base.connection.drop_table :prefix_topics_suffix rescue nil + ActiveRecord::Base.connection.drop_table :prefix_other_topics_suffix rescue nil end end @@ -179,7 +203,7 @@ class FixturesTest < ActiveRecord::TestCase #sanity check to make sure that this file never exists assert Dir[nonexistent_fixture_path+"*"].empty? - assert_raise(FixturesFileNotFound) do + assert_raise(Errno::ENOENT) do ActiveRecord::Fixtures.new( Account.connection, "companies", 'Company', nonexistent_fixture_path) end end @@ -213,7 +237,7 @@ class FixturesTest < ActiveRecord::TestCase def test_binary_in_fixtures data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read } - data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding) + data.force_encoding('ASCII-8BIT') data.freeze assert_equal data, @flowers.data end @@ -451,14 +475,36 @@ end class CustomConnectionFixturesTest < ActiveRecord::TestCase set_fixture_class :courses => Course fixtures :courses - # 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 def test_connection assert_kind_of Course, courses(:ruby) assert_equal Course.connection, courses(:ruby).connection end + + def test_leaky_destroy + assert_nothing_raised { courses(:ruby) } + courses(:ruby).destroy + end + + def test_it_twice_in_whatever_order_to_check_for_fixture_leakage + test_leaky_destroy + end +end + +class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase + set_fixture_class :courses => Course + fixtures :courses + self.use_transactional_fixtures = true + + def test_leaky_destroy + assert_nothing_raised { courses(:ruby) } + courses(:ruby).destroy + end + + def test_it_twice_in_whatever_order_to_check_for_fixture_leakage + test_leaky_destroy + end end class InvalidTableNameFixturesTest < ActiveRecord::TestCase @@ -496,7 +542,9 @@ class ManyToManyFixturesWithClassDefined < ActiveRecord::TestCase end class FixturesBrokenRollbackTest < ActiveRecord::TestCase - def blank_setup; end + def blank_setup + @fixture_connections = [ActiveRecord::Base.connection] + end alias_method :ar_setup_fixtures, :setup_fixtures alias_method :setup_fixtures, :blank_setup alias_method :setup, :blank_setup @@ -549,7 +597,7 @@ class FasterFixturesTest < ActiveRecord::TestCase load_extra_fixture('posts') assert ActiveRecord::Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'posts') - self.class.setup_fixture_accessors('posts') + self.class.setup_fixture_accessors :posts assert_equal 'Welcome to the weblog', posts(:welcome).title end end @@ -707,3 +755,34 @@ class FixtureLoadingTest < ActiveRecord::TestCase ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine) end end + +class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase + ActiveRecord::Fixtures.reset_cache + + set_fixture_class :randomly_named_a9 => + ClassNameThatDoesNotFollowCONVENTIONS, + :'admin/randomly_named_a9' => + Admin::ClassNameThatDoesNotFollowCONVENTIONS, + 'admin/randomly_named_b0' => + Admin::ClassNameThatDoesNotFollowCONVENTIONS + + fixtures :randomly_named_a9, 'admin/randomly_named_a9', + :'admin/randomly_named_b0' + + def test_named_accessor_for_randomly_named_fixture_and_class + assert_kind_of ClassNameThatDoesNotFollowCONVENTIONS, + randomly_named_a9(:first_instance) + end + + def test_named_accessor_for_randomly_named_namespaced_fixture_and_class + assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS, + admin_randomly_named_a9(:first_instance) + assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS, + admin_randomly_named_b0(:second_instance) + end + + def test_table_name_is_defined_in_the_model + assert_equal 'randomly_named_table', ActiveRecord::Fixtures::all_loaded_fixtures["admin/randomly_named_a9"].table_name + assert_equal 'randomly_named_table', Admin::ClassNameThatDoesNotFollowCONVENTIONS.table_name + end +end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 6735bc521b..734d017b6e 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -2,12 +2,14 @@ require File.expand_path('../../../../load_paths', __FILE__) require 'config' -require 'test/unit' +require 'minitest/autorun' require 'stringio' require 'mocha' +require 'cases/test_case' require 'active_record' require 'active_support/dependencies' +require 'active_support/logger' require 'support/config' require 'support/connection' @@ -20,6 +22,9 @@ ActiveSupport::Deprecation.debug = true # Enable Identity Map only when ENV['IM'] is set to "true" ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "true") +# Avoid deprecation warning setting dependent_restrict_raises to false. The default is true +ActiveRecord::Base.dependent_restrict_raises = false + # Connect to the database ARTest.connect @@ -68,14 +73,19 @@ module ActiveRecord cattr_accessor :log self.log = [] + attr_reader :ignore + + def initialize(ignore = Regexp.union(self.class.ignored_sql)) + @ignore = ignore + end + def call(name, start, finish, message_id, values) sql = values[:sql] # FIXME: this seems bad. we should probably have a better way to indicate # the query was cached - unless 'CACHE' == values[:name] - self.class.log << sql unless self.class.ignored_sql.any? { |r| sql =~ r } - end + return if 'CACHE' == values[:name] || ignore =~ sql + self.class.log << sql end end @@ -85,7 +95,10 @@ end unless ENV['FIXTURE_DEBUG'] module ActiveRecord::TestFixtures::ClassMethods def try_to_load_dependency_with_silence(*args) - ActiveRecord::Base.logger.silence { try_to_load_dependency_without_silence(*args)} + old = ActiveRecord::Base.logger.level + ActiveRecord::Base.logger.level = ActiveSupport::Logger::ERROR + try_to_load_dependency_without_silence(*args) + ActiveRecord::Base.logger.level = old end alias_method_chain :try_to_load_dependency, :silence diff --git a/activerecord/test/cases/identity_map/middleware_test.rb b/activerecord/test/cases/identity_map/middleware_test.rb index 60dcad4586..5b32a1c6d2 100644 --- a/activerecord/test/cases/identity_map/middleware_test.rb +++ b/activerecord/test/cases/identity_map/middleware_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require "rack" module ActiveRecord module IdentityMap @@ -19,6 +20,7 @@ module ActiveRecord called = false mw = Middleware.new lambda { |env| called = true + [200, {}, nil] } mw.call({}) assert called, 'middleware delegated' @@ -27,6 +29,7 @@ module ActiveRecord def test_im_enabled_during_delegation mw = Middleware.new lambda { |env| assert IdentityMap.enabled?, 'identity map should be enabled' + [200, {}, nil] } mw.call({}) end diff --git a/activerecord/test/cases/inclusion_test.rb b/activerecord/test/cases/inclusion_test.rb new file mode 100644 index 0000000000..8726ba5e51 --- /dev/null +++ b/activerecord/test/cases/inclusion_test.rb @@ -0,0 +1,113 @@ +require 'cases/helper' +require 'models/teapot' + +class BasicInclusionModelTest < ActiveRecord::TestCase + def test_basic_model + Teapot.create!(:name => "Ronnie Kemper") + assert_equal "Ronnie Kemper", Teapot.find(1).name + end + + def test_initialization + t = Teapot.new(:name => "Bob") + assert_equal "Bob", t.name + end + + def test_inherited_model + teapot = CoolTeapot.create!(:name => "Bob") + teapot.reload + + assert_equal "Bob", teapot.name + assert_equal "mmm", teapot.aaahhh + end + + def test_generated_feature_methods + assert Teapot < Teapot::GeneratedFeatureMethods + end + + def test_exists + t = Teapot.create!(:name => "Ronnie Kemper") + assert Teapot.exists?(t) + end + + def test_predicate_builder + t = Teapot.create!(:name => "Bob") + assert_equal "Bob", Teapot.where(:id => [t]).first.name + assert_equal "Bob", Teapot.where(:id => t).first.name + end + + def test_nested_model + assert_equal "ceiling_teapots", Ceiling::Teapot.table_name + end +end + +class InclusionUnitTest < ActiveRecord::TestCase + def setup + @klass = Class.new { include ActiveRecord::Model } + end + + def test_non_abstract_class + assert !@klass.abstract_class? + end + + def test_abstract_class + @klass.abstract_class = true + assert @klass.abstract_class? + end + + def test_establish_connection + assert @klass.respond_to?(:establish_connection) + assert ActiveRecord::Model.respond_to?(:establish_connection) + end + + def test_adapter_connection + name = "#{ActiveRecord::Base.connection_config[:adapter]}_connection" + assert @klass.respond_to?(name) + assert ActiveRecord::Model.respond_to?(name) + end + + def test_connection_handler + assert_equal ActiveRecord::Base.connection_handler, @klass.connection_handler + end + + def test_mirrored_configuration + ActiveRecord::Base.time_zone_aware_attributes = true + assert @klass.time_zone_aware_attributes + ActiveRecord::Base.time_zone_aware_attributes = false + assert !@klass.time_zone_aware_attributes + ensure + ActiveRecord::Base.time_zone_aware_attributes = false + end + + # Doesn't really test anything, but this is here to ensure warnings don't occur + def test_included_twice + @klass.send :include, ActiveRecord::Model + end + + def test_deprecation_proxy + assert_equal ActiveRecord::Model.name, ActiveRecord::Model::DeprecationProxy.name + assert_equal ActiveRecord::Base.superclass, assert_deprecated { ActiveRecord::Model::DeprecationProxy.superclass } + + sup, sup2 = nil, nil + ActiveSupport.on_load(:__test_active_record_model_deprecation) do + sup = superclass + sup2 = send(:superclass) + end + assert_deprecated do + ActiveSupport.run_load_hooks(:__test_active_record_model_deprecation, ActiveRecord::Model::DeprecationProxy) + end + assert_equal ActiveRecord::Base.superclass, sup + assert_equal ActiveRecord::Base.superclass, sup2 + end +end + +class InclusionFixturesTest < ActiveRecord::TestCase + fixtures :teapots + + def test_fixtured_record + assert_equal "Bob", teapots(:bob).name + end + + def test_timestamped_fixture + assert_not_nil teapots(:bob).created_at + end +end diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index b5d8314541..02df464469 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -65,7 +65,6 @@ class InheritanceTest < ActiveRecord::TestCase end def test_company_descends_from_active_record - assert_raise(NoMethodError) { ActiveRecord::Base.descends_from_active_record? } assert AbstractCompany.descends_from_active_record?, 'AbstractCompany should descend from ActiveRecord::Base' assert Company.descends_from_active_record?, 'Company should descend from ActiveRecord::Base' assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base' @@ -236,11 +235,11 @@ class InheritanceTest < ActiveRecord::TestCase c.save end [ Company, Firm, Client].each { |klass| klass.reset_column_information } - Company.set_inheritance_column('ruby_type') + Company.inheritance_column = 'ruby_type' end def switch_to_default_inheritance_column [ Company, Firm, Client].each { |klass| klass.reset_column_information } - Company.set_inheritance_column('type') + Company.inheritance_column = 'type' end end diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb index 3ae7b63dff..8f1cdd47ea 100644 --- a/activerecord/test/cases/invertible_migration_test.rb +++ b/activerecord/test/cases/invertible_migration_test.rb @@ -88,5 +88,17 @@ module ActiveRecord LegacyMigration.down assert !ActiveRecord::Base.connection.table_exists?("horses"), "horses should not exist" end + + def test_migrate_down_with_table_name_prefix + ActiveRecord::Base.table_name_prefix = 'p_' + ActiveRecord::Base.table_name_suffix = '_s' + migration = InvertibleMigration.new + migration.migrate(:up) + assert_nothing_raised { migration.migrate(:down) } + assert !ActiveRecord::Base.connection.table_exists?("p_horses_s"), "p_horses_s should not exist" + ensure + ActiveRecord::Base.table_name_prefix = ActiveRecord::Base.table_name_suffix = '' + end + end end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 61baa55027..807274ca67 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -6,12 +6,15 @@ require 'models/reader' require 'models/legacy_thing' require 'models/reference' require 'models/string_key_object' +require 'models/car' +require 'models/engine' +require 'models/wheel' class LockWithoutDefault < ActiveRecord::Base; end class LockWithCustomColumnWithoutDefault < ActiveRecord::Base - set_table_name :lock_without_defaults_cust - set_locking_column :custom_lock_version + self.table_name = :lock_without_defaults_cust + self.locking_column = :custom_lock_version end class ReadonlyFirstNamePerson < Person @@ -125,6 +128,24 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_raise(ActiveRecord::StaleObjectError) { p2.save! } end + def test_lock_exception_record + p1 = Person.new(:first_name => 'mira') + assert_equal 0, p1.lock_version + + p1.first_name = 'mira2' + p1.save! + p2 = Person.find(p1.id) + assert_equal 0, p1.lock_version + assert_equal 0, p2.lock_version + + p1.first_name = 'mira3' + p1.save! + + p2.first_name = 'sue' + error = assert_raise(ActiveRecord::StaleObjectError) { p2.save! } + assert_equal(error.record.object_id, p2.object_id) + end + def test_lock_new_with_nil p1 = Person.new(:first_name => 'anika') p1.save! @@ -141,7 +162,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_equal 1, p1.lock_version end - def test_lock_column_name_existing t1 = LegacyThing.find(1) t2 = LegacyThing.find(1) @@ -207,6 +227,18 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_equal lock_version, p1.lock_version end end + + def test_polymorphic_destroy_with_dependencies_and_lock_version + car = Car.create! + + assert_difference 'car.wheels.count' do + car.wheels << Wheel.create! + end + assert_difference 'car.wheels.count', -1 do + car.destroy + end + assert car.destroyed? + end end class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase @@ -261,6 +293,8 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase assert_equal true, p1.frozen? assert_raises(ActiveRecord::RecordNotFound) { Person.find(p1.id) } assert_raises(ActiveRecord::RecordNotFound) { LegacyThing.find(t.id) } + ensure + remove_counter_column_from(Person, 'legacy_things_count') end private @@ -272,8 +306,8 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase model.update_all(col => 0) if current_adapter?(:OpenBaseAdapter) end - def remove_counter_column_from(model) - model.connection.remove_column model.table_name, :test_count + def remove_counter_column_from(model, col = :test_count) + model.connection.remove_column model.table_name, col model.reset_column_information end @@ -354,22 +388,32 @@ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db? end end + def test_with_lock_commits_transaction + person = Person.find 1 + person.with_lock do + person.first_name = 'fooman' + person.save! + end + assert_equal 'fooman', person.reload.first_name + end + + def test_with_lock_rolls_back_transaction + person = Person.find 1 + old = person.first_name + person.with_lock do + person.first_name = 'fooman' + person.save! + raise 'oops' + end rescue nil + assert_equal old, person.reload.first_name + end + if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) def test_no_locks_no_wait first, second = duel { Person.find 1 } assert first.end > second.end end - # Hit by ruby deadlock detection since connection checkout is mutexed. - if RUBY_VERSION < '1.9.0' - def test_second_lock_waits - assert [0.2, 1, 5].any? { |zzz| - first, second = duel(zzz) { Person.find 1, :lock => true } - second.end > first.end - } - end - end - protected def duel(zzz = 5) t0, t1, t2, t3 = nil, nil, nil, nil diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index 9e8475465e..d1f0ace184 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -5,7 +5,7 @@ require "active_support/log_subscriber/test_helper" class LogSubscriberTest < ActiveRecord::TestCase include ActiveSupport::LogSubscriber::TestHelper - include ActiveSupport::BufferedLogger::Severity + include ActiveSupport::Logger::Severity fixtures :posts @@ -13,6 +13,7 @@ class LogSubscriberTest < ActiveRecord::TestCase @old_logger = ActiveRecord::Base.logger @using_identity_map = ActiveRecord::IdentityMap.enabled? ActiveRecord::IdentityMap.enabled = false + Developer.primary_key super ActiveRecord::LogSubscriber.attach_to(:active_record) end diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb index ef35f3341e..8122857f52 100644 --- a/activerecord/test/cases/mass_assignment_security_test.rb +++ b/activerecord/test/cases/mass_assignment_security_test.rb @@ -50,6 +50,13 @@ module MassAssignmentTestHelpers assert_equal 'm', person.gender assert_equal 'rides a sweet bike', person.comments end + + def with_strict_sanitizer + ActiveRecord::Base.mass_assignment_sanitizer = :strict + yield + ensure + ActiveRecord::Base.mass_assignment_sanitizer = :logger + end end module MassAssignmentRelationTestHelpers @@ -231,7 +238,9 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase def test_protection_against_class_attribute_writers [:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names, - :default_timezone, :schema_format, :lock_optimistically, :record_timestamps].each do |method| + :default_timezone, :schema_format, :lock_optimistically, :timestamped_migrations, :default_scopes, + :connection_handler, :nested_attributes_options, :_attr_readonly, :attribute_types_cached_by_default, + :attribute_method_matchers, :time_zone_aware_attributes, :skip_time_zone_conversion_for_attributes].each do |method| assert_respond_to Task, method assert_respond_to Task, "#{method}=" assert_respond_to Task.new, method @@ -321,6 +330,13 @@ class MassAssignmentSecurityHasOneRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_one_build_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.build_best_friend(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create def test_has_one_create_with_attr_protected_attributes @@ -348,6 +364,13 @@ class MassAssignmentSecurityHasOneRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_one_create_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create! def test_has_one_create_with_bang_with_attr_protected_attributes @@ -375,6 +398,13 @@ class MassAssignmentSecurityHasOneRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_one_create_with_bang_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend!(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + end @@ -436,6 +466,13 @@ class MassAssignmentSecurityBelongsToRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_belongs_to_create_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend_of(attributes_hash.except(:id, :comments)) + assert_equal best_friend.id, @person.best_friend_of_id + end + end + # create! def test_belongs_to_create_with_bang_with_attr_protected_attributes @@ -463,6 +500,13 @@ class MassAssignmentSecurityBelongsToRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_belongs_to_create_with_bang_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend_of!(attributes_hash.except(:id, :comments)) + assert_equal best_friend.id, @person.best_friend_of_id + end + end + end @@ -497,6 +541,13 @@ class MassAssignmentSecurityHasManyRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_many_build_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.best_friends.build(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create def test_has_many_create_with_attr_protected_attributes @@ -524,6 +575,13 @@ class MassAssignmentSecurityHasManyRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_many_create_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.best_friends.create(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create! def test_has_many_create_with_bang_with_attr_protected_attributes @@ -551,6 +609,13 @@ class MassAssignmentSecurityHasManyRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_many_create_with_bang_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.best_friends.create!(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + end diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index 0ab4f30363..ebf6e26385 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -104,7 +104,7 @@ class MethodScopingTest < ActiveRecord::TestCase def test_scoped_find_include # with the include, will retrieve only developers for the given project scoped_developers = Developer.send(:with_scope, :find => { :include => :projects }) do - Developer.find(:all, :conditions => 'projects.id = 2') + Developer.find(:all, :conditions => { 'projects.id' => 2 }) end assert scoped_developers.include?(developers(:david)) assert !scoped_developers.include?(developers(:jamis)) @@ -204,7 +204,7 @@ class MethodScopingTest < ActiveRecord::TestCase def test_scoped_count_include # with the include, will retrieve only developers for the given project Developer.send(:with_scope, :find => { :include => :projects }) do - assert_equal 1, Developer.count(:conditions => 'projects.id = 2') + assert_equal 1, Developer.count(:conditions => { 'projects.id' => 2 }) end end @@ -339,7 +339,7 @@ class NestedScopingTest < ActiveRecord::TestCase def test_nested_scoped_find_include Developer.send(:with_scope, :find => { :include => :projects }) do - Developer.send(:with_scope, :find => { :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :conditions => { 'projects.id' => 2 } }) do assert_nothing_raised { Developer.find(1) } assert_equal('David', Developer.find(:first).name) end @@ -348,7 +348,7 @@ class NestedScopingTest < ActiveRecord::TestCase def test_nested_scoped_find_merged_include # :include's remain unique and don't "double up" when merging - Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :include => :projects, :conditions => { 'projects.id' => 2 } }) do Developer.send(:with_scope, :find => { :include => :projects }) do assert_equal 1, Developer.scoped.includes_values.uniq.length assert_equal 'David', Developer.find(:first).name @@ -356,7 +356,7 @@ class NestedScopingTest < ActiveRecord::TestCase end # the nested scope doesn't remove the first :include - Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :include => :projects, :conditions => { 'projects.id' => 2 } }) do Developer.send(:with_scope, :find => { :include => [] }) do assert_equal 1, Developer.scoped.includes_values.uniq.length assert_equal('David', Developer.find(:first).name) @@ -364,7 +364,7 @@ class NestedScopingTest < ActiveRecord::TestCase end # mixing array and symbol include's will merge correctly - Developer.send(:with_scope, :find => { :include => [:projects], :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :include => [:projects], :conditions => { 'projects.id' => 2 } }) do Developer.send(:with_scope, :find => { :include => :projects }) do assert_equal 1, Developer.scoped.includes_values.uniq.length assert_equal('David', Developer.find(:first).name) diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb new file mode 100644 index 0000000000..f0b1f74bd3 --- /dev/null +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -0,0 +1,328 @@ +require 'cases/helper' + +module ActiveRecord + class Migration + class ChangeSchemaTest < ActiveRecord::TestCase + attr_reader :connection, :table_name + + def setup + super + @connection = ActiveRecord::Base.connection + @table_name = :testings + end + + def teardown + super + connection.drop_table :testings rescue nil + ActiveRecord::Base.primary_key_prefix_type = nil + end + + def test_create_table_without_id + testing_table_with_only_foo_attribute do + assert_equal connection.columns(:testings).size, 1 + end + end + + def test_add_column_with_primary_key_attribute + testing_table_with_only_foo_attribute do + connection.add_column :testings, :id, :primary_key + assert_equal connection.columns(:testings).size, 2 + end + end + + def test_create_table_adds_id + connection.create_table :testings do |t| + t.column :foo, :string + end + + assert_equal %w(foo id), connection.columns(:testings).map(&:name).sort + end + + def test_create_table_with_not_null_column + connection.create_table :testings do |t| + t.column :foo, :string, :null => false + end + + assert_raises(ActiveRecord::StatementInvalid) do + connection.execute "insert into testings (foo) values (NULL)" + end + end + + def test_create_table_with_defaults + # MySQL doesn't allow defaults on TEXT or BLOB columns. + mysql = current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter) + + connection.create_table :testings do |t| + t.column :one, :string, :default => "hello" + t.column :two, :boolean, :default => true + t.column :three, :boolean, :default => false + t.column :four, :integer, :default => 1 + t.column :five, :text, :default => "hello" unless mysql + end + + columns = connection.columns(:testings) + one = columns.detect { |c| c.name == "one" } + two = columns.detect { |c| c.name == "two" } + three = columns.detect { |c| c.name == "three" } + four = columns.detect { |c| c.name == "four" } + five = columns.detect { |c| c.name == "five" } unless mysql + + assert_equal "hello", one.default + assert_equal true, two.default + assert_equal false, three.default + assert_equal 1, four.default + assert_equal "hello", five.default unless mysql + end + + def test_create_table_with_limits + connection.create_table :testings do |t| + t.column :foo, :string, :limit => 255 + + t.column :default_int, :integer + + t.column :one_int, :integer, :limit => 1 + t.column :four_int, :integer, :limit => 4 + t.column :eight_int, :integer, :limit => 8 + t.column :eleven_int, :integer, :limit => 11 + end + + columns = connection.columns(:testings) + foo = columns.detect { |c| c.name == "foo" } + assert_equal 255, foo.limit + + default = columns.detect { |c| c.name == "default_int" } + one = columns.detect { |c| c.name == "one_int" } + four = columns.detect { |c| c.name == "four_int" } + eight = columns.detect { |c| c.name == "eight_int" } + eleven = columns.detect { |c| c.name == "eleven_int" } + + if current_adapter?(:PostgreSQLAdapter) + assert_equal 'integer', default.sql_type + assert_equal 'smallint', one.sql_type + assert_equal 'integer', four.sql_type + assert_equal 'bigint', eight.sql_type + assert_equal 'integer', eleven.sql_type + elsif current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) + assert_match 'int(11)', default.sql_type + assert_match 'tinyint', one.sql_type + assert_match 'int', four.sql_type + assert_match 'bigint', eight.sql_type + assert_match 'int(11)', eleven.sql_type + elsif current_adapter?(:OracleAdapter) + assert_equal 'NUMBER(38)', default.sql_type + assert_equal 'NUMBER(1)', one.sql_type + assert_equal 'NUMBER(4)', four.sql_type + assert_equal 'NUMBER(8)', eight.sql_type + end + end + + def test_create_table_with_primary_key_prefix_as_table_name_with_underscore + ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore + + connection.create_table :testings do |t| + t.column :foo, :string + end + + assert_equal %w(foo testing_id), connection.columns(:testings).map(&:name).sort + end + + def test_create_table_with_primary_key_prefix_as_table_name + ActiveRecord::Base.primary_key_prefix_type = :table_name + + connection.create_table :testings do |t| + t.column :foo, :string + end + + assert_equal %w(foo testingid), connection.columns(:testings).map(&:name).sort + end + + def test_create_table_with_timestamps_should_create_datetime_columns + connection.create_table table_name do |t| + t.timestamps + end + created_columns = connection.columns(table_name) + + created_at_column = created_columns.detect {|c| c.name == 'created_at' } + updated_at_column = created_columns.detect {|c| c.name == 'updated_at' } + + assert !created_at_column.null + assert !updated_at_column.null + end + + def test_create_table_with_timestamps_should_create_datetime_columns_with_options + connection.create_table table_name do |t| + t.timestamps :null => false + end + created_columns = connection.columns(table_name) + + created_at_column = created_columns.detect {|c| c.name == 'created_at' } + updated_at_column = created_columns.detect {|c| c.name == 'updated_at' } + + assert !created_at_column.null + assert !updated_at_column.null + end + + def test_create_table_without_a_block + connection.create_table table_name + end + + def test_add_column_not_null_without_default + # Sybase, and SQLite3 will not allow you to add a NOT NULL + # column to a table without a default value. + if current_adapter?(:SybaseAdapter, :SQLite3Adapter) + skip "not supported on #{connection.class}" + end + + connection.create_table :testings do |t| + t.column :foo, :string + end + connection.add_column :testings, :bar, :string, :null => false + + assert_raise(ActiveRecord::StatementInvalid) do + connection.execute "insert into testings (foo, bar) values ('hello', NULL)" + end + end + + def test_add_column_not_null_with_default + connection.create_table :testings do |t| + t.column :foo, :string + end + + con = connection + connection.enable_identity_insert("testings", true) if current_adapter?(:SybaseAdapter) + connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}) values (1, 'hello')" + connection.enable_identity_insert("testings", false) if current_adapter?(:SybaseAdapter) + assert_nothing_raised {connection.add_column :testings, :bar, :string, :null => false, :default => "default" } + + assert_raises(ActiveRecord::StatementInvalid) do + unless current_adapter?(:OpenBaseAdapter) + connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) values (2, 'hello', NULL)" + else + connection.insert("INSERT INTO testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) VALUES (2, 'hello', NULL)", + "Testing Insert","id",2) + end + end + end + + def test_change_column_quotes_column_names + connection.create_table :testings do |t| + t.column :select, :string + end + + connection.change_column :testings, :select, :string, :limit => 10 + + # Oracle needs primary key value from sequence + if current_adapter?(:OracleAdapter) + connection.execute "insert into testings (id, #{connection.quote_column_name('select')}) values (testings_seq.nextval, '7 chars')" + else + connection.execute "insert into testings (#{connection.quote_column_name('select')}) values ('7 chars')" + end + end + + def test_keeping_default_and_notnull_constaint_on_change + connection.create_table :testings do |t| + t.column :title, :string + end + person_klass = Class.new(ActiveRecord::Base) + person_klass.table_name = 'testings' + + person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99 + person_klass.reset_column_information + assert_equal 99, person_klass.columns_hash["wealth"].default + assert_equal false, person_klass.columns_hash["wealth"].null + # Oracle needs primary key value from sequence + if current_adapter?(:OracleAdapter) + assert_nothing_raised {person_klass.connection.execute("insert into testings (id, title) values (testings_seq.nextval, 'tester')")} + else + assert_nothing_raised {person_klass.connection.execute("insert into testings (title) values ('tester')")} + end + + # change column default to see that column doesn't lose its not null definition + person_klass.connection.change_column_default "testings", "wealth", 100 + person_klass.reset_column_information + assert_equal 100, person_klass.columns_hash["wealth"].default + assert_equal false, person_klass.columns_hash["wealth"].null + + # rename column to see that column doesn't lose its not null and/or default definition + person_klass.connection.rename_column "testings", "wealth", "money" + person_klass.reset_column_information + assert_nil person_klass.columns_hash["wealth"] + assert_equal 100, person_klass.columns_hash["money"].default + assert_equal false, person_klass.columns_hash["money"].null + + # change column + person_klass.connection.change_column "testings", "money", :integer, :null => false, :default => 1000 + person_klass.reset_column_information + assert_equal 1000, person_klass.columns_hash["money"].default + assert_equal false, person_klass.columns_hash["money"].null + + # change column, make it nullable and clear default + person_klass.connection.change_column "testings", "money", :integer, :null => true, :default => nil + person_klass.reset_column_information + assert_nil person_klass.columns_hash["money"].default + assert_equal true, person_klass.columns_hash["money"].null + + # change_column_null, make it not nullable and set null values to a default value + person_klass.connection.execute('UPDATE testings SET money = NULL') + person_klass.connection.change_column_null "testings", "money", false, 2000 + person_klass.reset_column_information + assert_nil person_klass.columns_hash["money"].default + assert_equal false, person_klass.columns_hash["money"].null + assert_equal 2000, connection.select_values("SELECT money FROM testings").first.to_i + end + + def test_column_exists + connection.create_table :testings do |t| + t.column :foo, :string + end + + assert connection.column_exists?(:testings, :foo) + refute connection.column_exists?(:testings, :bar) + end + + def test_column_exists_with_type + connection.create_table :testings do |t| + t.column :foo, :string + t.column :bar, :decimal, :precision => 8, :scale => 2 + end + + assert connection.column_exists?(:testings, :foo, :string) + refute connection.column_exists?(:testings, :foo, :integer) + + assert connection.column_exists?(:testings, :bar, :decimal) + refute connection.column_exists?(:testings, :bar, :integer) + end + + def test_column_exists_with_definition + connection.create_table :testings do |t| + t.column :foo, :string, :limit => 100 + t.column :bar, :decimal, :precision => 8, :scale => 2 + end + + assert connection.column_exists?(:testings, :foo, :string, :limit => 100) + refute connection.column_exists?(:testings, :foo, :string, :limit => 50) + assert connection.column_exists?(:testings, :bar, :decimal, :precision => 8, :scale => 2) + refute connection.column_exists?(:testings, :bar, :decimal, :precision => 10, :scale => 2) + end + + def test_column_exists_on_table_with_no_options_parameter_supplied + connection.create_table :testings do |t| + t.string :foo + end + connection.change_table :testings do |t| + assert t.column_exists?(:foo) + assert !(t.column_exists?(:bar)) + end + end + + private + def testing_table_with_only_foo_attribute + connection.create_table :testings, :id => false do |t| + t.column :foo, :string + end + + yield + end + end + end +end diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb new file mode 100644 index 0000000000..040445ef12 --- /dev/null +++ b/activerecord/test/cases/migration/column_attributes_test.rb @@ -0,0 +1,188 @@ +require "cases/migration/helper" + +module ActiveRecord + class Migration + class ColumnAttributesTest < ActiveRecord::TestCase + include ActiveRecord::Migration::TestHelper + + self.use_transactional_fixtures = false + + def test_add_remove_single_field_using_string_arguments + refute TestModel.column_methods_hash.key?(:last_name) + + add_column 'test_models', 'last_name', :string + + TestModel.reset_column_information + + assert TestModel.column_methods_hash.key?(:last_name) + + remove_column 'test_models', 'last_name' + + TestModel.reset_column_information + refute TestModel.column_methods_hash.key?(:last_name) + end + + def test_add_remove_single_field_using_symbol_arguments + refute TestModel.column_methods_hash.key?(:last_name) + + add_column :test_models, :last_name, :string + + TestModel.reset_column_information + assert TestModel.column_methods_hash.key?(:last_name) + + remove_column :test_models, :last_name + + TestModel.reset_column_information + refute TestModel.column_methods_hash.key?(:last_name) + end + + def test_unabstracted_database_dependent_types + skip "not supported" unless current_adapter?(:MysqlAdapter, :Mysql2Adapter) + + add_column :test_models, :intelligence_quotient, :tinyint + TestModel.reset_column_information + assert_match(/tinyint/, TestModel.columns_hash['intelligence_quotient'].sql_type) + end + + # We specifically do a manual INSERT here, and then test only the SELECT + # functionality. This allows us to more easily catch INSERT being broken, + # but SELECT actually working fine. + def test_native_decimal_insert_manual_vs_automatic + correct_value = '0012345678901234567890.0123456789'.to_d + + connection.add_column "test_models", "wealth", :decimal, :precision => '30', :scale => '10' + + # Do a manual insertion + if current_adapter?(:OracleAdapter) + connection.execute "insert into test_models (id, wealth, created_at, updated_at) values (people_seq.nextval, 12345678901234567890.0123456789, sysdate, sysdate)" + elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings + connection.execute "insert into test_models (wealth, created_at, updated_at) values ('12345678901234567890.0123456789', 0, 0)" + elsif current_adapter?(:PostgreSQLAdapter) + connection.execute "insert into test_models (wealth, created_at, updated_at) values (12345678901234567890.0123456789, now(), now())" + else + connection.execute "insert into test_models (wealth, created_at, updated_at) values (12345678901234567890.0123456789, 0, 0)" + end + + # SELECT + row = TestModel.find(:first) + assert_kind_of BigDecimal, row.wealth + + # If this assert fails, that means the SELECT is broken! + unless current_adapter?(:SQLite3Adapter) + assert_equal correct_value, row.wealth + end + + # Reset to old state + TestModel.delete_all + + # Now use the Rails insertion + TestModel.create :wealth => BigDecimal.new("12345678901234567890.0123456789") + + # SELECT + row = TestModel.find(:first) + assert_kind_of BigDecimal, row.wealth + + # If these asserts fail, that means the INSERT (create function, or cast to SQL) is broken! + unless current_adapter?(:SQLite3Adapter) + assert_equal correct_value, row.wealth + end + end + + def test_add_column_with_precision_and_scale + connection.add_column 'test_models', 'wealth', :decimal, :precision => 9, :scale => 7 + + wealth_column = TestModel.columns_hash['wealth'] + assert_equal 9, wealth_column.precision + assert_equal 7, wealth_column.scale + end + + def test_change_column_preserve_other_column_precision_and_scale + skip "only on sqlite3" unless current_adapter?(:SQLite3Adapter) + + connection.add_column 'test_models', 'last_name', :string + connection.add_column 'test_models', 'wealth', :decimal, :precision => 9, :scale => 7 + + wealth_column = TestModel.columns_hash['wealth'] + assert_equal 9, wealth_column.precision + assert_equal 7, wealth_column.scale + + connection.change_column 'test_models', 'last_name', :string, :null => false + TestModel.reset_column_information + + wealth_column = TestModel.columns_hash['wealth'] + assert_equal 9, wealth_column.precision + assert_equal 7, wealth_column.scale + end + + def test_native_types + add_column "test_models", "first_name", :string + add_column "test_models", "last_name", :string + add_column "test_models", "bio", :text + add_column "test_models", "age", :integer + add_column "test_models", "height", :float + add_column "test_models", "wealth", :decimal, :precision => '30', :scale => '10' + add_column "test_models", "birthday", :datetime + add_column "test_models", "favorite_day", :date + add_column "test_models", "moment_of_truth", :datetime + add_column "test_models", "male", :boolean + + TestModel.create :first_name => 'bob', :last_name => 'bobsen', + :bio => "I was born ....", :age => 18, :height => 1.78, + :wealth => BigDecimal.new("12345678901234567890.0123456789"), + :birthday => 18.years.ago, :favorite_day => 10.days.ago, + :moment_of_truth => "1782-10-10 21:40:18", :male => true + + bob = TestModel.find(:first) + assert_equal 'bob', bob.first_name + assert_equal 'bobsen', bob.last_name + assert_equal "I was born ....", bob.bio + assert_equal 18, bob.age + + # Test for 30 significant digits (beyond the 16 of float), 10 of them + # after the decimal place. + + unless current_adapter?(:SQLite3Adapter) + assert_equal BigDecimal.new("0012345678901234567890.0123456789"), bob.wealth + end + + assert_equal true, bob.male? + + assert_equal String, bob.first_name.class + assert_equal String, bob.last_name.class + assert_equal String, bob.bio.class + assert_equal Fixnum, bob.age.class + assert_equal Time, bob.birthday.class + + if current_adapter?(:OracleAdapter, :SybaseAdapter) + # Sybase, and Oracle don't differentiate between date/time + assert_equal Time, bob.favorite_day.class + else + assert_equal Date, bob.favorite_day.class + end + + # Oracle adapter stores Time or DateTime with timezone value already in _before_type_cast column + # therefore no timezone change is done afterwards when default timezone is changed + unless current_adapter?(:OracleAdapter) + # Test DateTime column and defaults, including timezone. + # FIXME: moment of truth may be Time on 64-bit platforms. + if bob.moment_of_truth.is_a?(DateTime) + + with_env_tz 'US/Eastern' do + bob.reload + assert_equal DateTime.local_offset, bob.moment_of_truth.offset + assert_not_equal 0, bob.moment_of_truth.offset + assert_not_equal "Z", bob.moment_of_truth.zone + # US/Eastern is -5 hours from GMT + assert_equal Rational(-5, 24), bob.moment_of_truth.offset + assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM + assert_equal DateTime::ITALY, bob.moment_of_truth.start + end + end + end + + assert_instance_of TrueClass, bob.male? + assert_kind_of BigDecimal, bob.wealth + end + end + end +end diff --git a/activerecord/test/cases/migration/column_positioning_test.rb b/activerecord/test/cases/migration/column_positioning_test.rb new file mode 100644 index 0000000000..913d935f7c --- /dev/null +++ b/activerecord/test/cases/migration/column_positioning_test.rb @@ -0,0 +1,60 @@ +require 'cases/helper' + +module ActiveRecord + class Migration + class ColumnPositioningTest < ActiveRecord::TestCase + attr_reader :connection, :table_name + alias :conn :connection + + def setup + super + + unless current_adapter?(:MysqlAdapter, :Mysql2Adapter) + skip "not supported on #{connection.class}" + end + + @connection = ActiveRecord::Base.connection + + connection.create_table :testings, :id => false do |t| + t.column :first, :integer + t.column :second, :integer + t.column :third, :integer + end + end + + def teardown + super + connection.drop_table :testings rescue nil + ActiveRecord::Base.primary_key_prefix_type = nil + end + + def test_column_positioning + assert_equal %w(first second third), conn.columns(:testings).map {|c| c.name } + end + + def test_add_column_with_positioning + conn.add_column :testings, :new_col, :integer + assert_equal %w(first second third new_col), conn.columns(:testings).map {|c| c.name } + end + + def test_add_column_with_positioning_first + conn.add_column :testings, :new_col, :integer, :first => true + assert_equal %w(new_col first second third), conn.columns(:testings).map {|c| c.name } + end + + def test_add_column_with_positioning_after + conn.add_column :testings, :new_col, :integer, :after => :first + assert_equal %w(first new_col second third), conn.columns(:testings).map {|c| c.name } + end + + def test_change_column_with_positioning + conn.change_column :testings, :second, :integer, :first => true + assert_equal %w(second first third), conn.columns(:testings).map {|c| c.name } + + conn.change_column :testings, :second, :integer, :after => :third + assert_equal %w(first third second), conn.columns(:testings).map {|c| c.name } + end + + end + end +end diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb index d108b456f0..7d026961be 100644 --- a/activerecord/test/cases/migration/command_recorder_test.rb +++ b/activerecord/test/cases/migration/command_recorder_test.rb @@ -67,6 +67,24 @@ module ActiveRecord assert_equal [:drop_table, [:system_settings]], drop_table end + def test_invert_create_table_with_options + @recorder.record :create_table, [:people_reminders, {:id => false}] + drop_table = @recorder.inverse.first + assert_equal [:drop_table, [:people_reminders]], drop_table + end + + def test_invert_create_join_table + @recorder.record :create_join_table, [:musics, :artists] + drop_table = @recorder.inverse.first + assert_equal [:drop_table, [:artists_musics]], drop_table + end + + def test_invert_create_join_table_with_table_name + @recorder.record :create_join_table, [:musics, :artists, {:table_name => :catalog}] + drop_table = @recorder.inverse.first + assert_equal [:drop_table, [:catalog]], drop_table + end + def test_invert_rename_table @recorder.record :rename_table, [:old, :new] rename = @recorder.inverse.first diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb new file mode 100644 index 0000000000..0428d9ba76 --- /dev/null +++ b/activerecord/test/cases/migration/create_join_table_test.rb @@ -0,0 +1,70 @@ +require 'cases/helper' + +module ActiveRecord + class Migration + class CreateJoinTableTest < ActiveRecord::TestCase + attr_reader :connection + + def setup + super + @connection = ActiveRecord::Base.connection + end + + def test_create_join_table + connection.create_join_table :artists, :musics + + assert_equal %w(artist_id music_id), connection.columns(:artists_musics).map(&:name).sort + ensure + connection.drop_table :artists_musics + end + + def test_create_join_table_set_not_null_by_default + connection.create_join_table :artists, :musics + + assert_equal [false, false], connection.columns(:artists_musics).map(&:null) + ensure + connection.drop_table :artists_musics + end + + def test_create_join_table_with_strings + connection.create_join_table 'artists', 'musics' + + assert_equal %w(artist_id music_id), connection.columns(:artists_musics).map(&:name).sort + ensure + connection.drop_table :artists_musics + end + + def test_create_join_table_with_the_proper_order + connection.create_join_table :videos, :musics + + assert_equal %w(music_id video_id), connection.columns(:musics_videos).map(&:name).sort + ensure + connection.drop_table :musics_videos + end + + def test_create_join_table_with_the_table_name + connection.create_join_table :artists, :musics, :table_name => :catalog + + assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort + ensure + connection.drop_table :catalog + end + + def test_create_join_table_with_the_table_name_as_string + connection.create_join_table :artists, :musics, :table_name => 'catalog' + + assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort + ensure + connection.drop_table :catalog + end + + def test_create_join_table_with_column_options + connection.create_join_table :artists, :musics, :column_options => {:null => true} + + assert_equal [true, true], connection.columns(:artists_musics).map(&:null) + ensure + connection.drop_table :artists_musics + end + end + end +end diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb new file mode 100644 index 0000000000..fe53510ba2 --- /dev/null +++ b/activerecord/test/cases/migration/helper.rb @@ -0,0 +1,64 @@ +require "cases/helper" + +module ActiveRecord + class Migration + class << self + attr_accessor :message_count + end + + def puts(text="") + ActiveRecord::Migration.message_count ||= 0 + ActiveRecord::Migration.message_count += 1 + end + + module TestHelper + attr_reader :connection, :table_name + + class TestModel < ActiveRecord::Base + self.table_name = 'test_models' + end + + def setup + super + @connection = ActiveRecord::Base.connection + connection.create_table :test_models do |t| + t.timestamps + end + + TestModel.reset_column_information + end + + def teardown + super + TestModel.reset_table_name + TestModel.reset_sequence_name + connection.drop_table :test_models rescue nil + end + + private + def add_column(*args) + connection.add_column(*args) + end + + def remove_column(*args) + connection.remove_column(*args) + end + + def rename_column(*args) + connection.rename_column(*args) + end + + def add_index(*args) + connection.add_index(*args) + end + + def change_column(*args) + connection.change_column(*args) + end + + def rename_table(*args) + connection.rename_table(*args) + end + end + end +end diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb new file mode 100644 index 0000000000..89cf0f5e93 --- /dev/null +++ b/activerecord/test/cases/migration/index_test.rb @@ -0,0 +1,176 @@ +require 'cases/helper' + +module ActiveRecord + class Migration + class IndexTest < ActiveRecord::TestCase + attr_reader :connection, :table_name + + def setup + super + @connection = ActiveRecord::Base.connection + @table_name = :testings + + connection.create_table table_name do |t| + t.column :foo, :string, :limit => 100 + t.column :bar, :string, :limit => 100 + + t.string :first_name + t.string :last_name, :limit => 100 + t.string :key, :limit => 100 + t.boolean :administrator + end + end + + def teardown + super + connection.drop_table :testings rescue nil + ActiveRecord::Base.primary_key_prefix_type = nil + end + + def test_rename_index + skip "not supported on openbase" if current_adapter?(:OpenBaseAdapter) + + # keep the names short to make Oracle and similar behave + connection.add_index(table_name, [:foo], :name => 'old_idx') + connection.rename_index(table_name, 'old_idx', 'new_idx') + + # if the adapter doesn't support the indexes call, pick defaults that let the test pass + refute connection.index_name_exists?(table_name, 'old_idx', false) + assert connection.index_name_exists?(table_name, 'new_idx', true) + end + + def test_double_add_index + skip "not supported on openbase" if current_adapter?(:OpenBaseAdapter) + + connection.add_index(table_name, [:foo], :name => 'some_idx') + assert_raises(ArgumentError) { + connection.add_index(table_name, [:foo], :name => 'some_idx') + } + end + + def test_remove_nonexistent_index + skip "not supported on openbase" if current_adapter?(:OpenBaseAdapter) + + # we do this by name, so OpenBase is a wash as noted above + assert_raise(ArgumentError) { connection.remove_index(table_name, "no_such_index") } + end + + def test_add_index_name_length_limit + good_index_name = 'x' * connection.index_name_length + too_long_index_name = good_index_name + 'x' + + assert_raises(ArgumentError) { + connection.add_index(table_name, "foo", :name => too_long_index_name) + } + + refute connection.index_name_exists?(table_name, too_long_index_name, false) + connection.add_index(table_name, "foo", :name => good_index_name) + + assert connection.index_name_exists?(table_name, good_index_name, false) + connection.remove_index(table_name, :name => good_index_name) + end + + def test_index_symbol_names + connection.add_index table_name, :foo, :name => :symbol_index_name + assert connection.index_exists?(table_name, :foo, :name => :symbol_index_name) + + connection.remove_index table_name, :name => :symbol_index_name + refute connection.index_exists?(table_name, :foo, :name => :symbol_index_name) + end + + def test_index_exists + connection.add_index :testings, :foo + + assert connection.index_exists?(:testings, :foo) + assert !connection.index_exists?(:testings, :bar) + end + + def test_index_exists_on_multiple_columns + connection.add_index :testings, [:foo, :bar] + + assert connection.index_exists?(:testings, [:foo, :bar]) + end + + def test_unique_index_exists + connection.add_index :testings, :foo, :unique => true + + assert connection.index_exists?(:testings, :foo, :unique => true) + end + + def test_named_index_exists + connection.add_index :testings, :foo, :name => "custom_index_name" + + assert connection.index_exists?(:testings, :foo, :name => "custom_index_name") + end + + def test_add_index_attribute_length_limit + connection.add_index :testings, [:foo, :bar], :length => {:foo => 10, :bar => nil} + + assert connection.index_exists?(:testings, [:foo, :bar]) + end + + def test_add_index + connection.add_index("testings", "last_name") + connection.remove_index("testings", "last_name") + + # Orcl nds shrt indx nms. Sybs 2. + # OpenBase does not have named indexes. You must specify a single column name + unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) + connection.add_index("testings", ["last_name", "first_name"]) + connection.remove_index("testings", :column => ["last_name", "first_name"]) + + # Oracle adapter cannot have specified index name larger than 30 characters + # Oracle adapter is shortening index name when just column list is given + unless current_adapter?(:OracleAdapter) + connection.add_index("testings", ["last_name", "first_name"]) + connection.remove_index("testings", :name => :index_testings_on_last_name_and_first_name) + connection.add_index("testings", ["last_name", "first_name"]) + connection.remove_index("testings", "last_name_and_first_name") + end + connection.add_index("testings", ["last_name", "first_name"]) + connection.remove_index("testings", ["last_name", "first_name"]) + + connection.add_index("testings", ["last_name"], :length => 10) + connection.remove_index("testings", "last_name") + + connection.add_index("testings", ["last_name"], :length => {:last_name => 10}) + connection.remove_index("testings", ["last_name"]) + + connection.add_index("testings", ["last_name", "first_name"], :length => 10) + connection.remove_index("testings", ["last_name", "first_name"]) + + connection.add_index("testings", ["last_name", "first_name"], :length => {:last_name => 10, :first_name => 20}) + connection.remove_index("testings", ["last_name", "first_name"]) + end + + # quoting + # Note: changed index name from "key" to "key_idx" since "key" is a Firebird reserved word + # OpenBase does not have named indexes. You must specify a single column name + unless current_adapter?(:OpenBaseAdapter) + connection.add_index("testings", ["key"], :name => "key_idx", :unique => true) + connection.remove_index("testings", :name => "key_idx", :unique => true) + end + + # Sybase adapter does not support indexes on :boolean columns + # OpenBase does not have named indexes. You must specify a single column + unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) + connection.add_index("testings", %w(last_name first_name administrator), :name => "named_admin") + connection.remove_index("testings", :name => "named_admin") + end + + # Selected adapters support index sort order + if current_adapter?(:SQLite3Adapter, :MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter) + connection.add_index("testings", ["last_name"], :order => {:last_name => :desc}) + connection.remove_index("testings", ["last_name"]) + connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc}) + connection.remove_index("testings", ["last_name", "first_name"]) + connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc}) + connection.remove_index("testings", ["last_name", "first_name"]) + connection.add_index("testings", ["last_name", "first_name"], :order => :desc) + connection.remove_index("testings", ["last_name", "first_name"]) + end + end + + end + end +end diff --git a/activerecord/test/cases/migration/logger_test.rb b/activerecord/test/cases/migration/logger_test.rb new file mode 100644 index 0000000000..ee0c20747e --- /dev/null +++ b/activerecord/test/cases/migration/logger_test.rb @@ -0,0 +1,37 @@ +require "cases/helper" + +module ActiveRecord + class Migration + class LoggerTest < ActiveRecord::TestCase + # mysql can't roll back ddl changes + self.use_transactional_fixtures = false + + Migration = Struct.new(:name, :version) do + def migrate direction + # do nothing + end + end + + def setup + super + ActiveRecord::SchemaMigration.create_table + ActiveRecord::SchemaMigration.delete_all + end + + def teardown + super + ActiveRecord::SchemaMigration.drop_table + end + + def test_migration_should_be_run_without_logger + previous_logger = ActiveRecord::Base.logger + ActiveRecord::Base.logger = nil + migrations = [Migration.new('a', 1), Migration.new('b', 2), Migration.new('c', 3)] + ActiveRecord::Migrator.new(:up, migrations).migrate + ensure + ActiveRecord::Base.logger = previous_logger + end + end + end +end + diff --git a/activerecord/test/cases/migration/rename_column_test.rb b/activerecord/test/cases/migration/rename_column_test.rb new file mode 100644 index 0000000000..16e09fd80e --- /dev/null +++ b/activerecord/test/cases/migration/rename_column_test.rb @@ -0,0 +1,194 @@ +require "cases/migration/helper" + +module ActiveRecord + class Migration + class RenameColumnTest < ActiveRecord::TestCase + include ActiveRecord::Migration::TestHelper + + self.use_transactional_fixtures = false + + # FIXME: this is more of an integration test with AR::Base and the + # schema modifications. Maybe we should move this? + def test_add_rename + add_column "test_models", "girlfriend", :string + TestModel.reset_column_information + + TestModel.create :girlfriend => 'bobette' + + rename_column "test_models", "girlfriend", "exgirlfriend" + + TestModel.reset_column_information + bob = TestModel.find(:first) + + assert_equal "bobette", bob.exgirlfriend + end + + # FIXME: another integration test. We should decouple this from the + # AR::Base implementation. + def test_rename_column_using_symbol_arguments + add_column :test_models, :first_name, :string + + TestModel.create :first_name => 'foo' + + rename_column :test_models, :first_name, :nick_name + TestModel.reset_column_information + assert TestModel.column_names.include?("nick_name") + assert_equal ['foo'], TestModel.find(:all).map(&:nick_name) + end + + # FIXME: another integration test. We should decouple this from the + # AR::Base implementation. + def test_rename_column + add_column "test_models", "first_name", "string" + + TestModel.create :first_name => 'foo' + + rename_column "test_models", "first_name", "nick_name" + TestModel.reset_column_information + assert TestModel.column_names.include?("nick_name") + assert_equal ['foo'], TestModel.find(:all).map(&:nick_name) + end + + def test_rename_column_preserves_default_value_not_null + add_column 'test_models', 'salary', :integer, :default => 70000 + + default_before = connection.columns("test_models").find { |c| c.name == "salary" }.default + assert_equal 70000, default_before + + rename_column "test_models", "salary", "anual_salary" + + assert TestModel.column_names.include?("anual_salary") + default_after = connection.columns("test_models").find { |c| c.name == "anual_salary" }.default + assert_equal 70000, default_after + end + + def test_rename_nonexistent_column + exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) + ActiveRecord::StatementInvalid + else + ActiveRecord::ActiveRecordError + end + assert_raise(exception) do + rename_column "test_models", "nonexistent", "should_fail" + end + end + + def test_rename_column_with_sql_reserved_word + add_column 'test_models', 'first_name', :string + rename_column "test_models", "first_name", "group" + + assert TestModel.column_names.include?("group") + end + + def test_rename_column_with_an_index + add_column "test_models", :hat_name, :string + add_index :test_models, :hat_name + + # FIXME: we should test that the index goes away + rename_column "test_models", "hat_name", "name" + end + + def test_remove_column_with_index + add_column "test_models", :hat_name, :string + add_index :test_models, :hat_name + + # FIXME: we should test that the index goes away + remove_column("test_models", "hat_name") + end + + def test_remove_column_with_multi_column_index + add_column "test_models", :hat_size, :integer + add_column "test_models", :hat_style, :string, :limit => 100 + add_index "test_models", ["hat_style", "hat_size"], :unique => true + + # FIXME: we should test that the index goes away + remove_column("test_models", "hat_size") + end + + # FIXME: we need to test that these calls do something + def test_change_type_of_not_null_column + change_column "test_models", "updated_at", :datetime, :null => false + change_column "test_models", "updated_at", :datetime, :null => false + change_column "test_models", "updated_at", :datetime, :null => true + end + + def test_change_column_nullability + add_column "test_models", "funny", :boolean + assert TestModel.columns_hash["funny"].null, "Column 'funny' must initially allow nulls" + + change_column "test_models", "funny", :boolean, :null => false, :default => true + + TestModel.reset_column_information + refute TestModel.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point" + + change_column "test_models", "funny", :boolean, :null => true + TestModel.reset_column_information + assert TestModel.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point" + end + + def test_change_column + add_column 'test_models', 'age', :integer + add_column 'test_models', 'approved', :boolean, :default => true + + old_columns = connection.columns(TestModel.table_name) + + assert old_columns.find { |c| c.name == 'age' && c.type == :integer } + + change_column "test_models", "age", :string + + new_columns = connection.columns(TestModel.table_name) + + refute new_columns.find { |c| c.name == 'age' and c.type == :integer } + assert new_columns.find { |c| c.name == 'age' and c.type == :string } + + old_columns = connection.columns(TestModel.table_name) + assert old_columns.find { |c| + c.name == 'approved' && c.type == :boolean && c.default == true + } + + change_column :test_models, :approved, :boolean, :default => false + new_columns = connection.columns(TestModel.table_name) + + refute new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true } + assert new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == false } + change_column :test_models, :approved, :boolean, :default => true + end + + def test_change_column_with_nil_default + add_column "test_models", "contributor", :boolean, :default => true + assert TestModel.new.contributor? + + change_column "test_models", "contributor", :boolean, :default => nil + TestModel.reset_column_information + refute TestModel.new.contributor? + assert_nil TestModel.new.contributor + end + + def test_change_column_with_new_default + add_column "test_models", "administrator", :boolean, :default => true + assert TestModel.new.administrator? + + change_column "test_models", "administrator", :boolean, :default => false + TestModel.reset_column_information + refute TestModel.new.administrator? + end + + def test_change_column_default + add_column "test_models", "first_name", :string + connection.change_column_default "test_models", "first_name", "Tester" + + assert_equal "Tester", TestModel.new.first_name + end + + def test_change_column_default_to_null + add_column "test_models", "first_name", :string + connection.change_column_default "test_models", "first_name", nil + assert_nil TestModel.new.first_name + end + + def test_remove_column_no_second_parameter_raises_exception + assert_raise(ArgumentError) { connection.remove_column("funny") } + end + end + end +end diff --git a/activerecord/test/cases/migration/rename_table_test.rb b/activerecord/test/cases/migration/rename_table_test.rb new file mode 100644 index 0000000000..d5ff2c607f --- /dev/null +++ b/activerecord/test/cases/migration/rename_table_test.rb @@ -0,0 +1,72 @@ +require "cases/migration/helper" + +module ActiveRecord + class Migration + class RenameTableTest < ActiveRecord::TestCase + include ActiveRecord::Migration::TestHelper + + self.use_transactional_fixtures = false + + def setup + super + add_column 'test_models', :url, :string + remove_column 'test_models', :created_at + remove_column 'test_models', :updated_at + end + + def test_rename_table_for_sqlite_should_work_with_reserved_words + renamed = false + + skip "not supported" unless current_adapter?(:SQLite3Adapter) + + add_column :test_models, :url, :string + connection.rename_table :references, :old_references + connection.rename_table :test_models, :references + + renamed = true + + # Using explicit id in insert for compatibility across all databases + con = connection + con.execute "INSERT INTO 'references' (url, created_at, updated_at) VALUES ('http://rubyonrails.com', 0, 0)" + assert_equal 'http://rubyonrails.com', connection.select_value("SELECT url FROM 'references' WHERE id=1") + ensure + return unless renamed + connection.rename_table :references, :test_models + connection.rename_table :old_references, :references + end + + def test_rename_table + rename_table :test_models, :octopi + + # Using explicit id in insert for compatibility across all databases + con = connection + con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter) + + con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" + + con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter) + + assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1") + + rename_table :octopi, :test_models + end + + def test_rename_table_with_an_index + add_index :test_models, :url + + rename_table :test_models, :octopi + + # Using explicit id in insert for compatibility across all databases + con = ActiveRecord::Base.connection + con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter) + con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" + con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter) + + assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1") + assert connection.indexes(:octopi).first.columns.include?("url") + + rename_table :octopi, :test_models + end + end + end +end diff --git a/activerecord/test/cases/migration/table_and_index_test.rb b/activerecord/test/cases/migration/table_and_index_test.rb new file mode 100644 index 0000000000..8fd770abd1 --- /dev/null +++ b/activerecord/test/cases/migration/table_and_index_test.rb @@ -0,0 +1,24 @@ +require "cases/helper" + +module ActiveRecord + class Migration + class TableAndIndexTest < ActiveRecord::TestCase + def test_add_schema_info_respects_prefix_and_suffix + conn = ActiveRecord::Base.connection + + conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name) + # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters + ActiveRecord::Base.table_name_prefix = 'p_' + ActiveRecord::Base.table_name_suffix = '_s' + conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name) + + conn.initialize_schema_migrations_table + + assert_equal "p_unique_schema_migrations_s", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name] + ensure + ActiveRecord::Base.table_name_prefix = "" + ActiveRecord::Base.table_name_suffix = "" + end + end + end +end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 93a1249e43..575df2f84b 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require "cases/migration/helper" require 'bigdecimal/util' require 'models/person' @@ -6,2235 +7,941 @@ require 'models/topic' require 'models/developer' require MIGRATIONS_ROOT + "/valid/2_we_need_reminders" +require MIGRATIONS_ROOT + "/rename/1_we_need_things" +require MIGRATIONS_ROOT + "/rename/2_rename_things" require MIGRATIONS_ROOT + "/decimal/1_give_me_big_numbers" -if ActiveRecord::Base.connection.supports_migrations? - class BigNumber < ActiveRecord::Base; end +class BigNumber < ActiveRecord::Base; end - class Reminder < ActiveRecord::Base; end +class Reminder < ActiveRecord::Base; end - class ActiveRecord::Migration - class << self - attr_accessor :message_count - end - - def puts(text="") - ActiveRecord::Migration.message_count ||= 0 - ActiveRecord::Migration.message_count += 1 - end - end - - class MigrationTableAndIndexTest < ActiveRecord::TestCase - def test_add_schema_info_respects_prefix_and_suffix - conn = ActiveRecord::Base.connection +class Thing < ActiveRecord::Base; end - conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name) - # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters - ActiveRecord::Base.table_name_prefix = 'p_' - ActiveRecord::Base.table_name_suffix = '_s' - conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name) +class MigrationTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false - conn.initialize_schema_migrations_table + fixtures :people - assert_equal "p_unique_schema_migrations_s", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name] - ensure - ActiveRecord::Base.table_name_prefix = "" - ActiveRecord::Base.table_name_suffix = "" + def setup + super + %w(reminders people_reminders prefix_reminders_suffix).each do |table| + Reminder.connection.drop_table(table) rescue nil end + Reminder.reset_column_information + ActiveRecord::Migration.verbose = true + ActiveRecord::Migration.message_count = 0 end - class MigrationTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false - - fixtures :people - - def setup - ActiveRecord::Migration.verbose = true - ActiveRecord::Migration.message_count = 0 - end - - def teardown - ActiveRecord::Base.connection.initialize_schema_migrations_table - ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::Migrator.schema_migrations_table_name}" - - %w(reminders people_reminders prefix_reminders_suffix).each do |table| - Reminder.connection.drop_table(table) rescue nil - end - Reminder.reset_column_information - - %w(last_name key bio age height wealth birthday favorite_day - moment_of_truth male administrator funny).each do |column| - Person.connection.remove_column('people', column) rescue nil - end - Person.connection.remove_column("people", "first_name") rescue nil - Person.connection.remove_column("people", "middle_name") rescue nil - Person.connection.add_column("people", "first_name", :string, :limit => 40) - Person.reset_column_information - end - - def test_add_index - # Limit size of last_name and key columns to support Firebird index limitations - Person.connection.add_column "people", "last_name", :string, :limit => 100 - Person.connection.add_column "people", "key", :string, :limit => 100 - Person.connection.add_column "people", "administrator", :boolean - - assert_nothing_raised { Person.connection.add_index("people", "last_name") } - assert_nothing_raised { Person.connection.remove_index("people", "last_name") } - - # Orcl nds shrt indx nms. Sybs 2. - # OpenBase does not have named indexes. You must specify a single column name - unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) - assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) } - assert_nothing_raised { Person.connection.remove_index("people", :column => ["last_name", "first_name"]) } - # Oracle adapter cannot have specified index name larger than 30 characters - # Oracle adapter is shortening index name when just column list is given - unless current_adapter?(:OracleAdapter) - assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) } - assert_nothing_raised { Person.connection.remove_index("people", :name => :index_people_on_last_name_and_first_name) } - assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) } - assert_nothing_raised { Person.connection.remove_index("people", "last_name_and_first_name") } - end - assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) } - assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) } - assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :length => 10) } - assert_nothing_raised { Person.connection.remove_index("people", "last_name") } - assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :length => {:last_name => 10}) } - assert_nothing_raised { Person.connection.remove_index("people", ["last_name"]) } - assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :length => 10) } - assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) } - assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :length => {:last_name => 10, :first_name => 20}) } - assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) } - end - - # quoting - # Note: changed index name from "key" to "key_idx" since "key" is a Firebird reserved word - # OpenBase does not have named indexes. You must specify a single column name - unless current_adapter?(:OpenBaseAdapter) - Person.update_all "#{Person.connection.quote_column_name 'key'}=#{Person.connection.quote_column_name 'id'}" #some databases (including sqlite2 won't add a unique index if existing data non unique) - assert_nothing_raised { Person.connection.add_index("people", ["key"], :name => "key_idx", :unique => true) } - assert_nothing_raised { Person.connection.remove_index("people", :name => "key_idx", :unique => true) } - end - - # Sybase adapter does not support indexes on :boolean columns - # OpenBase does not have named indexes. You must specify a single column - unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) - assert_nothing_raised { Person.connection.add_index("people", %w(last_name first_name administrator), :name => "named_admin") } - assert_nothing_raised { Person.connection.remove_index("people", :name => "named_admin") } - end - end - - def test_index_symbol_names - assert_nothing_raised { Person.connection.add_index :people, :primary_contact_id, :name => :symbol_index_name } - assert Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name) - assert_nothing_raised { Person.connection.remove_index :people, :name => :symbol_index_name } - assert !Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name) - end - - def test_add_index_length_limit - good_index_name = 'x' * Person.connection.index_name_length - too_long_index_name = good_index_name + 'x' - assert_raise(ArgumentError) { Person.connection.add_index("people", "first_name", :name => too_long_index_name) } - assert !Person.connection.index_name_exists?("people", too_long_index_name, false) - assert_nothing_raised { Person.connection.add_index("people", "first_name", :name => good_index_name) } - assert Person.connection.index_name_exists?("people", good_index_name, false) - Person.connection.remove_index("people", :name => good_index_name) - end - - def test_remove_nonexistent_index - # we do this by name, so OpenBase is a wash as noted above - unless current_adapter?(:OpenBaseAdapter) - assert_raise(ArgumentError) { Person.connection.remove_index("people", "no_such_index") } - end - end - - def test_rename_index - unless current_adapter?(:OpenBaseAdapter) - # keep the names short to make Oracle and similar behave - Person.connection.add_index('people', [:first_name], :name => 'old_idx') - assert_nothing_raised { Person.connection.rename_index('people', 'old_idx', 'new_idx') } - # if the adapter doesn't support the indexes call, pick defaults that let the test pass - assert !Person.connection.index_name_exists?('people', 'old_idx', false) - assert Person.connection.index_name_exists?('people', 'new_idx', true) - end - end - - def test_double_add_index - unless current_adapter?(:OpenBaseAdapter) - Person.connection.add_index('people', [:first_name], :name => 'some_idx') - assert_raise(ArgumentError) { Person.connection.add_index('people', [:first_name], :name => 'some_idx') } - end - end - - def test_index_exists - Person.connection.create_table :testings do |t| - t.column :foo, :string, :limit => 100 - t.column :bar, :string, :limit => 100 - end - Person.connection.add_index :testings, :foo + def teardown + ActiveRecord::Base.connection.initialize_schema_migrations_table + ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::Migrator.schema_migrations_table_name}" - assert Person.connection.index_exists?(:testings, :foo) - assert !Person.connection.index_exists?(:testings, :bar) - ensure - Person.connection.drop_table :testings rescue nil + %w(things awesome_things prefix_things_suffix prefix_awesome_things_suffix).each do |table| + Thing.connection.drop_table(table) rescue nil end + Thing.reset_column_information - def test_index_exists_on_multiple_columns - Person.connection.create_table :testings do |t| - t.column :foo, :string, :limit => 100 - t.column :bar, :string, :limit => 100 - end - Person.connection.add_index :testings, [:foo, :bar] - - assert Person.connection.index_exists?(:testings, [:foo, :bar]) - ensure - Person.connection.drop_table :testings rescue nil + %w(reminders people_reminders prefix_reminders_suffix).each do |table| + Reminder.connection.drop_table(table) rescue nil end + Reminder.reset_column_information - def test_unique_index_exists - Person.connection.create_table :testings do |t| - t.column :foo, :string, :limit => 100 - end - Person.connection.add_index :testings, :foo, :unique => true - - assert Person.connection.index_exists?(:testings, :foo, :unique => true) - ensure - Person.connection.drop_table :testings rescue nil + %w(last_name key bio age height wealth birthday favorite_day + moment_of_truth male administrator funny).each do |column| + Person.connection.remove_column('people', column) rescue nil end + Person.connection.remove_column("people", "first_name") rescue nil + Person.connection.remove_column("people", "middle_name") rescue nil + Person.connection.add_column("people", "first_name", :string, :limit => 40) + Person.reset_column_information + end - def test_named_index_exists - Person.connection.create_table :testings do |t| - t.column :foo, :string, :limit => 100 - end - Person.connection.add_index :testings, :foo, :name => "custom_index_name" - - assert Person.connection.index_exists?(:testings, :foo, :name => "custom_index_name") - ensure - Person.connection.drop_table :testings rescue nil + def test_create_table_with_force_true_does_not_drop_nonexisting_table + if Person.connection.table_exists?(:testings2) + Person.connection.drop_table :testings2 end - def testing_table_with_only_foo_attribute - Person.connection.create_table :testings, :id => false do |t| - t.column :foo, :string - end + # using a copy as we need the drop_table method to + # continue to work for the ensure block of the test + temp_conn = Person.connection.dup - yield Person.connection - ensure - Person.connection.drop_table :testings rescue nil - end - protected :testing_table_with_only_foo_attribute + assert_not_equal temp_conn, Person.connection - def test_create_table_without_id - testing_table_with_only_foo_attribute do |connection| - assert_equal connection.columns(:testings).size, 1 - end - end - - def test_add_column_with_primary_key_attribute - testing_table_with_only_foo_attribute do |connection| - assert_nothing_raised { connection.add_column :testings, :id, :primary_key } - assert_equal connection.columns(:testings).size, 2 - end + temp_conn.create_table :testings2, :force => true do |t| + t.column :foo, :string end + ensure + Person.connection.drop_table :testings2 rescue nil + end - def test_create_table_adds_id - Person.connection.create_table :testings do |t| - t.column :foo, :string - end - - assert_equal %w(foo id), - Person.connection.columns(:testings).map { |c| c.name }.sort - ensure - Person.connection.drop_table :testings rescue nil - end - - def test_create_table_with_not_null_column - assert_nothing_raised do - Person.connection.create_table :testings do |t| - t.column :foo, :string, :null => false - end - end - - assert_raise(ActiveRecord::StatementInvalid) do - Person.connection.execute "insert into testings (foo) values (NULL)" - end - ensure - Person.connection.drop_table :testings rescue nil - end + def connection + ActiveRecord::Base.connection + end - def test_create_table_with_defaults - # MySQL doesn't allow defaults on TEXT or BLOB columns. - mysql = current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter) + def test_migration_instance_has_connection + migration = Class.new(ActiveRecord::Migration).new + assert_equal connection, migration.connection + end - Person.connection.create_table :testings do |t| - t.column :one, :string, :default => "hello" - t.column :two, :boolean, :default => true - t.column :three, :boolean, :default => false - t.column :four, :integer, :default => 1 - t.column :five, :text, :default => "hello" unless mysql + def test_method_missing_delegates_to_connection + migration = Class.new(ActiveRecord::Migration) { + def connection + Class.new { + def create_table; "hi mom!"; end + }.new end + }.new - columns = Person.connection.columns(:testings) - one = columns.detect { |c| c.name == "one" } - two = columns.detect { |c| c.name == "two" } - three = columns.detect { |c| c.name == "three" } - four = columns.detect { |c| c.name == "four" } - five = columns.detect { |c| c.name == "five" } unless mysql - - assert_equal "hello", one.default - assert_equal true, two.default - assert_equal false, three.default - assert_equal 1, four.default - assert_equal "hello", five.default unless mysql + assert_equal "hi mom!", migration.method_missing(:create_table) + end - ensure - Person.connection.drop_table :testings rescue nil + def test_add_table_with_decimals + Person.connection.drop_table :big_numbers rescue nil + + assert !BigNumber.table_exists? + GiveMeBigNumbers.up + + assert BigNumber.create( + :bank_balance => 1586.43, + :big_bank_balance => BigDecimal("1000234000567.95"), + :world_population => 6000000000, + :my_house_population => 3, + :value_of_e => BigDecimal("2.7182818284590452353602875") + ) + + b = BigNumber.find(:first) + assert_not_nil b + + assert_not_nil b.bank_balance + assert_not_nil b.big_bank_balance + assert_not_nil b.world_population + assert_not_nil b.my_house_population + assert_not_nil b.value_of_e + + # TODO: set world_population >= 2**62 to cover 64-bit platforms and test + # is_a?(Bignum) + assert_kind_of Integer, b.world_population + assert_equal 6000000000, b.world_population + assert_kind_of Fixnum, b.my_house_population + assert_equal 3, b.my_house_population + assert_kind_of BigDecimal, b.bank_balance + assert_equal BigDecimal("1586.43"), b.bank_balance + assert_kind_of BigDecimal, b.big_bank_balance + assert_equal BigDecimal("1000234000567.95"), b.big_bank_balance + + # This one is fun. The 'value_of_e' field is defined as 'DECIMAL' with + # precision/scale explicitly left out. By the SQL standard, numbers + # assigned to this field should be truncated but that's seldom respected. + if current_adapter?(:PostgreSQLAdapter) + # - PostgreSQL changes the SQL spec on columns declared simply as + # "decimal" to something more useful: instead of being given a scale + # of 0, they take on the compile-time limit for precision and scale, + # so the following should succeed unless you have used really wacky + # compilation options + # - SQLite2 has the default behavior of preserving all data sent in, + # so this happens there too + assert_kind_of BigDecimal, b.value_of_e + assert_equal BigDecimal("2.7182818284590452353602875"), b.value_of_e + elsif current_adapter?(:SQLite3Adapter) + # - SQLite3 stores a float, in violation of SQL + assert_kind_of BigDecimal, b.value_of_e + assert_in_delta BigDecimal("2.71828182845905"), b.value_of_e, 0.00000000000001 + else + # - SQL standard is an integer + assert_kind_of Fixnum, b.value_of_e + assert_equal 2, b.value_of_e end - def test_create_table_with_limits - assert_nothing_raised do - Person.connection.create_table :testings do |t| - t.column :foo, :string, :limit => 255 + GiveMeBigNumbers.down + assert_raise(ActiveRecord::StatementInvalid) { BigNumber.find(:first) } + end - t.column :default_int, :integer + def test_filtering_migrations + assert !Person.column_methods_hash.include?(:last_name) + assert !Reminder.table_exists? - t.column :one_int, :integer, :limit => 1 - t.column :four_int, :integer, :limit => 4 - t.column :eight_int, :integer, :limit => 8 - t.column :eleven_int, :integer, :limit => 11 - end - end + name_filter = lambda { |migration| migration.name == "ValidPeopleHaveLastNames" } + ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", &name_filter) - columns = Person.connection.columns(:testings) - foo = columns.detect { |c| c.name == "foo" } - assert_equal 255, foo.limit - - default = columns.detect { |c| c.name == "default_int" } - one = columns.detect { |c| c.name == "one_int" } - four = columns.detect { |c| c.name == "four_int" } - eight = columns.detect { |c| c.name == "eight_int" } - eleven = columns.detect { |c| c.name == "eleven_int" } - - if current_adapter?(:PostgreSQLAdapter) - assert_equal 'integer', default.sql_type - assert_equal 'smallint', one.sql_type - assert_equal 'integer', four.sql_type - assert_equal 'bigint', eight.sql_type - assert_equal 'integer', eleven.sql_type - elsif current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) - assert_match 'int(11)', default.sql_type - assert_match 'tinyint', one.sql_type - assert_match 'int', four.sql_type - assert_match 'bigint', eight.sql_type - assert_match 'int(11)', eleven.sql_type - elsif current_adapter?(:OracleAdapter) - assert_equal 'NUMBER(38)', default.sql_type - assert_equal 'NUMBER(1)', one.sql_type - assert_equal 'NUMBER(4)', four.sql_type - assert_equal 'NUMBER(8)', eight.sql_type - end - ensure - Person.connection.drop_table :testings rescue nil - end + Person.reset_column_information + assert Person.column_methods_hash.include?(:last_name) + assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } - def test_create_table_with_primary_key_prefix_as_table_name_with_underscore - ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore + ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", &name_filter) - Person.connection.create_table :testings do |t| - t.column :foo, :string - end + Person.reset_column_information + assert !Person.column_methods_hash.include?(:last_name) + assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } + end - assert_equal %w(foo testing_id), Person.connection.columns(:testings).map { |c| c.name }.sort - ensure - Person.connection.drop_table :testings rescue nil - ActiveRecord::Base.primary_key_prefix_type = nil + class MockMigration < ActiveRecord::Migration + attr_reader :went_up, :went_down + def initialize + @went_up = false + @went_down = false end - def test_create_table_with_primary_key_prefix_as_table_name - ActiveRecord::Base.primary_key_prefix_type = :table_name - - Person.connection.create_table :testings do |t| - t.column :foo, :string - end - - assert_equal %w(foo testingid), Person.connection.columns(:testings).map { |c| c.name }.sort - ensure - Person.connection.drop_table :testings rescue nil - ActiveRecord::Base.primary_key_prefix_type = nil + def up + @went_up = true + super end - def test_create_table_with_force_true_does_not_drop_nonexisting_table - if Person.connection.table_exists?(:testings2) - Person.connection.drop_table :testings2 - end - - # using a copy as we need the drop_table method to - # continue to work for the ensure block of the test - temp_conn = Person.connection.dup - temp_conn.expects(:drop_table).never - temp_conn.create_table :testings2, :force => true do |t| - t.column :foo, :string - end - ensure - Person.connection.drop_table :testings2 rescue nil + def down + @went_down = true + super end + end - def test_create_table_with_timestamps_should_create_datetime_columns - table_name = :testings - - Person.connection.create_table table_name do |t| - t.timestamps - end - created_columns = Person.connection.columns(table_name) - - created_at_column = created_columns.detect {|c| c.name == 'created_at' } - updated_at_column = created_columns.detect {|c| c.name == 'updated_at' } - - assert created_at_column.null - assert updated_at_column.null - ensure - Person.connection.drop_table table_name rescue nil - end - - def test_create_table_with_timestamps_should_create_datetime_columns_with_options - table_name = :testings - - Person.connection.create_table table_name do |t| - t.timestamps :null => false - end - created_columns = Person.connection.columns(table_name) - - created_at_column = created_columns.detect {|c| c.name == 'created_at' } - updated_at_column = created_columns.detect {|c| c.name == 'updated_at' } + def test_instance_based_migration_up + migration = MockMigration.new + assert !migration.went_up, 'have not gone up' + assert !migration.went_down, 'have not gone down' - assert !created_at_column.null - assert !updated_at_column.null - ensure - Person.connection.drop_table table_name rescue nil - end + migration.migrate :up + assert migration.went_up, 'have gone up' + assert !migration.went_down, 'have not gone down' + end - def test_create_table_without_a_block - table_name = :testings - Person.connection.create_table table_name - ensure - Person.connection.drop_table table_name rescue nil - end + def test_instance_based_migration_down + migration = MockMigration.new + assert !migration.went_up, 'have not gone up' + assert !migration.went_down, 'have not gone down' - # Sybase, and SQLite3 will not allow you to add a NOT NULL - # column to a table without a default value. - unless current_adapter?(:SybaseAdapter, :SQLite3Adapter) - def test_add_column_not_null_without_default - Person.connection.create_table :testings do |t| - t.column :foo, :string - end - Person.connection.add_column :testings, :bar, :string, :null => false + migration.migrate :down + assert !migration.went_up, 'have gone up' + assert migration.went_down, 'have not gone down' + end - assert_raise(ActiveRecord::StatementInvalid) do - Person.connection.execute "insert into testings (foo, bar) values ('hello', NULL)" - end - ensure - Person.connection.drop_table :testings rescue nil - end + def test_migrator_one_up_with_exception_and_rollback + unless ActiveRecord::Base.connection.supports_ddl_transactions? + skip "not supported on #{ActiveRecord::Base.connection.class}" end - def test_add_column_not_null_with_default - Person.connection.create_table :testings do |t| - t.column :foo, :string - end - - con = Person.connection - Person.connection.enable_identity_insert("testings", true) if current_adapter?(:SybaseAdapter) - Person.connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}) values (1, 'hello')" - Person.connection.enable_identity_insert("testings", false) if current_adapter?(:SybaseAdapter) - assert_nothing_raised {Person.connection.add_column :testings, :bar, :string, :null => false, :default => "default" } - - assert_raise(ActiveRecord::StatementInvalid) do - unless current_adapter?(:OpenBaseAdapter) - Person.connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) values (2, 'hello', NULL)" - else - Person.connection.insert("INSERT INTO testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) VALUES (2, 'hello', NULL)", - "Testing Insert","id",2) - end - end - ensure - Person.connection.drop_table :testings rescue nil - end - - # We specifically do a manual INSERT here, and then test only the SELECT - # functionality. This allows us to more easily catch INSERT being broken, - # but SELECT actually working fine. - def test_native_decimal_insert_manual_vs_automatic - correct_value = '0012345678901234567890.0123456789'.to_d - - Person.delete_all - Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10' - Person.reset_column_information - - # Do a manual insertion - if current_adapter?(:OracleAdapter) - Person.connection.execute "insert into people (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)" - elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings - Person.connection.execute "insert into people (wealth) values ('12345678901234567890.0123456789')" - else - Person.connection.execute "insert into people (wealth) values (12345678901234567890.0123456789)" - end - - # SELECT - row = Person.find(:first) - assert_kind_of BigDecimal, row.wealth + refute Person.column_methods_hash.include?(:last_name) - # If this assert fails, that means the SELECT is broken! - unless current_adapter?(:SQLite3Adapter) - assert_equal correct_value, row.wealth - end + migration = Struct.new(:name, :version) { + def migrate(x); raise 'Something broke'; end + }.new('zomg', 100) - # Reset to old state - Person.delete_all + migrator = ActiveRecord::Migrator.new(:up, [migration], 100) - # Now use the Rails insertion - assert_nothing_raised { Person.create :wealth => BigDecimal.new("12345678901234567890.0123456789") } + e = assert_raise(StandardError) { migrator.migrate } - # SELECT - row = Person.find(:first) - assert_kind_of BigDecimal, row.wealth + assert_equal "An error has occurred, this and all later migrations canceled:\n\nSomething broke", e.message - # If these asserts fail, that means the INSERT (create function, or cast to SQL) is broken! - unless current_adapter?(:SQLite3Adapter) - assert_equal correct_value, row.wealth - end - - # Reset to old state - Person.connection.del_column "people", "wealth" rescue nil - Person.reset_column_information - end - - def test_add_column_with_precision_and_scale - Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7 - Person.reset_column_information - - wealth_column = Person.columns_hash['wealth'] - assert_equal 9, wealth_column.precision - assert_equal 7, wealth_column.scale - end - - def test_native_types - Person.delete_all - Person.connection.add_column "people", "last_name", :string - Person.connection.add_column "people", "bio", :text - Person.connection.add_column "people", "age", :integer - Person.connection.add_column "people", "height", :float - Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10' - Person.connection.add_column "people", "birthday", :datetime - Person.connection.add_column "people", "favorite_day", :date - Person.connection.add_column "people", "moment_of_truth", :datetime - Person.connection.add_column "people", "male", :boolean - Person.reset_column_information - - assert_nothing_raised do - Person.create :first_name => 'bob', :last_name => 'bobsen', - :bio => "I was born ....", :age => 18, :height => 1.78, - :wealth => BigDecimal.new("12345678901234567890.0123456789"), - :birthday => 18.years.ago, :favorite_day => 10.days.ago, - :moment_of_truth => "1782-10-10 21:40:18", :male => true - end - - bob = Person.find(:first) - assert_equal 'bob', bob.first_name - assert_equal 'bobsen', bob.last_name - assert_equal "I was born ....", bob.bio - assert_equal 18, bob.age + Person.reset_column_information + refute Person.column_methods_hash.include?(:last_name) + end - # Test for 30 significant digits (beyond the 16 of float), 10 of them - # after the decimal place. + def test_schema_migrations_table_name + ActiveRecord::Base.table_name_prefix = "prefix_" + ActiveRecord::Base.table_name_suffix = "_suffix" + Reminder.reset_table_name + assert_equal "prefix_schema_migrations_suffix", ActiveRecord::Migrator.schema_migrations_table_name + ActiveRecord::Base.table_name_prefix = "" + ActiveRecord::Base.table_name_suffix = "" + Reminder.reset_table_name + assert_equal "schema_migrations", ActiveRecord::Migrator.schema_migrations_table_name + ensure + ActiveRecord::Base.table_name_prefix = "" + ActiveRecord::Base.table_name_suffix = "" + end - unless current_adapter?(:SQLite3Adapter) - assert_equal BigDecimal.new("0012345678901234567890.0123456789"), bob.wealth - end + def test_proper_table_name + assert_equal "table", ActiveRecord::Migrator.proper_table_name('table') + assert_equal "table", ActiveRecord::Migrator.proper_table_name(:table) + assert_equal "reminders", ActiveRecord::Migrator.proper_table_name(Reminder) + Reminder.reset_table_name + assert_equal Reminder.table_name, ActiveRecord::Migrator.proper_table_name(Reminder) + + # Use the model's own prefix/suffix if a model is given + ActiveRecord::Base.table_name_prefix = "ARprefix_" + ActiveRecord::Base.table_name_suffix = "_ARsuffix" + Reminder.table_name_prefix = 'prefix_' + Reminder.table_name_suffix = '_suffix' + Reminder.reset_table_name + assert_equal "prefix_reminders_suffix", ActiveRecord::Migrator.proper_table_name(Reminder) + Reminder.table_name_prefix = '' + Reminder.table_name_suffix = '' + Reminder.reset_table_name + + # Use AR::Base's prefix/suffix if string or symbol is given + ActiveRecord::Base.table_name_prefix = "prefix_" + ActiveRecord::Base.table_name_suffix = "_suffix" + Reminder.reset_table_name + assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name('table') + assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name(:table) + ActiveRecord::Base.table_name_prefix = "" + ActiveRecord::Base.table_name_suffix = "" + Reminder.reset_table_name + end - assert_equal true, bob.male? + def test_rename_table_with_prefix_and_suffix + assert !Thing.table_exists? + ActiveRecord::Base.table_name_prefix = 'prefix_' + ActiveRecord::Base.table_name_suffix = '_suffix' + Thing.reset_table_name + Thing.reset_sequence_name + WeNeedThings.up + + assert Thing.create("content" => "hello world") + assert_equal "hello world", Thing.find(:first).content + + RenameThings.up + Thing.table_name = "prefix_awesome_things_suffix" + + assert_equal "hello world", Thing.find(:first).content + ensure + ActiveRecord::Base.table_name_prefix = '' + ActiveRecord::Base.table_name_suffix = '' + Thing.reset_table_name + Thing.reset_sequence_name + end - assert_equal String, bob.first_name.class - assert_equal String, bob.last_name.class - assert_equal String, bob.bio.class - assert_equal Fixnum, bob.age.class - assert_equal Time, bob.birthday.class + def test_add_drop_table_with_prefix_and_suffix + assert !Reminder.table_exists? + ActiveRecord::Base.table_name_prefix = 'prefix_' + ActiveRecord::Base.table_name_suffix = '_suffix' + Reminder.reset_table_name + Reminder.reset_sequence_name + WeNeedReminders.up + assert Reminder.create("content" => "hello world", "remind_at" => Time.now) + assert_equal "hello world", Reminder.find(:first).content + + WeNeedReminders.down + assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } + ensure + ActiveRecord::Base.table_name_prefix = '' + ActiveRecord::Base.table_name_suffix = '' + Reminder.reset_table_name + Reminder.reset_sequence_name + end - if current_adapter?(:OracleAdapter, :SybaseAdapter) - # Sybase, and Oracle don't differentiate between date/time - assert_equal Time, bob.favorite_day.class - else - assert_equal Date, bob.favorite_day.class - end + def test_create_table_with_binary_column + Person.connection.drop_table :binary_testings rescue nil - # Oracle adapter stores Time or DateTime with timezone value already in _before_type_cast column - # therefore no timezone change is done afterwards when default timezone is changed - unless current_adapter?(:OracleAdapter) - # Test DateTime column and defaults, including timezone. - # FIXME: moment of truth may be Time on 64-bit platforms. - if bob.moment_of_truth.is_a?(DateTime) - - with_env_tz 'US/Eastern' do - bob.reload - assert_equal DateTime.local_offset, bob.moment_of_truth.offset - assert_not_equal 0, bob.moment_of_truth.offset - assert_not_equal "Z", bob.moment_of_truth.zone - # US/Eastern is -5 hours from GMT - assert_equal Rational(-5, 24), bob.moment_of_truth.offset - assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM - assert_equal DateTime::ITALY, bob.moment_of_truth.start - end - end + assert_nothing_raised { + Person.connection.create_table :binary_testings do |t| + t.column "data", :binary, :null => false end + } - assert_instance_of TrueClass, bob.male? - assert_kind_of BigDecimal, bob.wealth - end + columns = Person.connection.columns(:binary_testings) + data_column = columns.detect { |c| c.name == "data" } if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) - def test_unabstracted_database_dependent_types - Person.delete_all - - ActiveRecord::Migration.add_column :people, :intelligence_quotient, :tinyint - Person.reset_column_information - assert_match(/tinyint/, Person.columns_hash['intelligence_quotient'].sql_type) - ensure - ActiveRecord::Migration.remove_column :people, :intelligence_quotient rescue nil - end - end - - def test_add_remove_single_field_using_string_arguments - assert !Person.column_methods_hash.include?(:last_name) - - ActiveRecord::Migration.add_column 'people', 'last_name', :string - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - - ActiveRecord::Migration.remove_column 'people', 'last_name' - - Person.reset_column_information - assert !Person.column_methods_hash.include?(:last_name) - end - - def test_add_remove_single_field_using_symbol_arguments - assert !Person.column_methods_hash.include?(:last_name) - - ActiveRecord::Migration.add_column :people, :last_name, :string - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - - ActiveRecord::Migration.remove_column :people, :last_name - - Person.reset_column_information - assert !Person.column_methods_hash.include?(:last_name) - end - - if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) - def testing_table_for_positioning - Person.connection.create_table :testings, :id => false do |t| - t.column :first, :integer - t.column :second, :integer - t.column :third, :integer - end - - yield Person.connection - ensure - Person.connection.drop_table :testings rescue nil - end - protected :testing_table_for_positioning - - def test_column_positioning - testing_table_for_positioning do |conn| - assert_equal %w(first second third), conn.columns(:testings).map {|c| c.name } - end - end - - def test_add_column_with_positioning - testing_table_for_positioning do |conn| - conn.add_column :testings, :new_col, :integer - assert_equal %w(first second third new_col), conn.columns(:testings).map {|c| c.name } - end - testing_table_for_positioning do |conn| - conn.add_column :testings, :new_col, :integer, :first => true - assert_equal %w(new_col first second third), conn.columns(:testings).map {|c| c.name } - end - testing_table_for_positioning do |conn| - conn.add_column :testings, :new_col, :integer, :after => :first - assert_equal %w(first new_col second third), conn.columns(:testings).map {|c| c.name } - end - end - - def test_change_column_with_positioning - testing_table_for_positioning do |conn| - conn.change_column :testings, :second, :integer, :first => true - assert_equal %w(second first third), conn.columns(:testings).map {|c| c.name } - end - testing_table_for_positioning do |conn| - conn.change_column :testings, :second, :integer, :after => :third - assert_equal %w(first third second), conn.columns(:testings).map {|c| c.name } - end - end - end - - def test_add_rename - Person.delete_all - - begin - Person.connection.add_column "people", "girlfriend", :string - Person.reset_column_information - Person.create :girlfriend => 'bobette' - - Person.connection.rename_column "people", "girlfriend", "exgirlfriend" - - Person.reset_column_information - bob = Person.find(:first) - - assert_equal "bobette", bob.exgirlfriend - ensure - Person.connection.remove_column("people", "girlfriend") rescue nil - Person.connection.remove_column("people", "exgirlfriend") rescue nil - end - - end - - def test_rename_column_using_symbol_arguments - begin - names_before = Person.find(:all).map(&:first_name) - Person.connection.rename_column :people, :first_name, :nick_name - Person.reset_column_information - assert Person.column_names.include?("nick_name") - assert_equal names_before, Person.find(:all).map(&:nick_name) - ensure - Person.connection.remove_column("people","nick_name") - Person.connection.add_column("people","first_name", :string) - end - end - - def test_rename_column - begin - names_before = Person.find(:all).map(&:first_name) - Person.connection.rename_column "people", "first_name", "nick_name" - Person.reset_column_information - assert Person.column_names.include?("nick_name") - assert_equal names_before, Person.find(:all).map(&:nick_name) - ensure - Person.connection.remove_column("people","nick_name") - Person.connection.add_column("people","first_name", :string) - end - end - - def test_rename_column_preserves_default_value_not_null - begin - default_before = Developer.connection.columns("developers").find { |c| c.name == "salary" }.default - assert_equal 70000, default_before - Developer.connection.rename_column "developers", "salary", "anual_salary" - Developer.reset_column_information - assert Developer.column_names.include?("anual_salary") - default_after = Developer.connection.columns("developers").find { |c| c.name == "anual_salary" }.default - assert_equal 70000, default_after - ensure - Developer.connection.rename_column "developers", "anual_salary", "salary" - Developer.reset_column_information - end - end - - def test_rename_nonexistent_column - ActiveRecord::Base.connection.create_table(:hats) do |table| - table.column :hat_name, :string, :default => nil - end - exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) - ActiveRecord::StatementInvalid - else - ActiveRecord::ActiveRecordError - end - assert_raise(exception) do - Person.connection.rename_column "hats", "nonexistent", "should_fail" - end - ensure - ActiveRecord::Base.connection.drop_table(:hats) - end - - def test_rename_column_with_sql_reserved_word - begin - assert_nothing_raised { Person.connection.rename_column "people", "first_name", "group" } - Person.reset_column_information - assert Person.column_names.include?("group") - ensure - Person.connection.remove_column("people", "group") rescue nil - Person.connection.add_column("people", "first_name", :string) rescue nil - end - end - - def test_rename_column_with_an_index - ActiveRecord::Base.connection.create_table(:hats) do |table| - table.column :hat_name, :string, :limit => 100 - table.column :hat_size, :integer - end - Person.connection.add_index :hats, :hat_name - assert_nothing_raised do - Person.connection.rename_column "hats", "hat_name", "name" - end - ensure - ActiveRecord::Base.connection.drop_table(:hats) - end - - def test_remove_column_with_index - ActiveRecord::Base.connection.create_table(:hats) do |table| - table.column :hat_name, :string, :limit => 100 - table.column :hat_size, :integer - end - ActiveRecord::Base.connection.add_index "hats", "hat_size" - - assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") } - ensure - ActiveRecord::Base.connection.drop_table(:hats) - end - - def test_remove_column_with_multi_column_index - ActiveRecord::Base.connection.create_table(:hats) do |table| - table.column :hat_name, :string, :limit => 100 - table.column :hat_size, :integer - table.column :hat_style, :string, :limit => 100 - end - ActiveRecord::Base.connection.add_index "hats", ["hat_style", "hat_size"], :unique => true - - assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") } - ensure - ActiveRecord::Base.connection.drop_table(:hats) - end - - def test_remove_column_no_second_parameter_raises_exception - assert_raise(ArgumentError) { Person.connection.remove_column("funny") } + assert_equal '', data_column.default + else + assert_nil data_column.default end - def test_change_type_of_not_null_column - assert_nothing_raised do - Topic.connection.change_column "topics", "written_on", :datetime, :null => false - Topic.reset_column_information - - Topic.connection.change_column "topics", "written_on", :datetime, :null => false - Topic.reset_column_information - - Topic.connection.change_column "topics", "written_on", :datetime, :null => true - Topic.reset_column_information - end - end + Person.connection.drop_table :binary_testings rescue nil + end - if current_adapter?(:SQLite3Adapter) - def test_rename_table_for_sqlite_should_work_with_reserved_words - begin - assert_nothing_raised do - ActiveRecord::Base.connection.rename_table :references, :old_references - ActiveRecord::Base.connection.create_table :octopuses do |t| - t.column :url, :string - end - end - - assert_nothing_raised { ActiveRecord::Base.connection.rename_table :octopuses, :references } - - # Using explicit id in insert for compatibility across all databases - con = ActiveRecord::Base.connection - assert_nothing_raised do - con.execute "INSERT INTO 'references' (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://rubyonrails.com')" - end - assert_equal 'http://rubyonrails.com', ActiveRecord::Base.connection.select_value("SELECT url FROM 'references' WHERE id=1") - - ensure - ActiveRecord::Base.connection.drop_table :references - ActiveRecord::Base.connection.rename_table :old_references, :references - end - end - end + def test_create_table_with_custom_sequence_name + skip "not supported" unless current_adapter? :OracleAdapter - def test_rename_table + # table name is 29 chars, the standard sequence name will + # be 33 chars and should be shortened + assert_nothing_raised do begin - ActiveRecord::Base.connection.create_table :octopuses do |t| - t.column :url, :string + Person.connection.create_table :table_with_name_thats_just_ok do |t| + t.column :foo, :string, :null => false end - ActiveRecord::Base.connection.rename_table :octopuses, :octopi - - # Using explicit id in insert for compatibility across all databases - con = ActiveRecord::Base.connection - con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter) - assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" } - con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter) - - assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1") - ensure - ActiveRecord::Base.connection.drop_table :octopuses rescue nil - ActiveRecord::Base.connection.drop_table :octopi rescue nil + Person.connection.drop_table :table_with_name_thats_just_ok rescue nil end end - def test_change_column_nullability - Person.delete_all - Person.connection.add_column "people", "funny", :boolean - Person.reset_column_information - assert Person.columns_hash["funny"].null, "Column 'funny' must initially allow nulls" - Person.connection.change_column "people", "funny", :boolean, :null => false, :default => true - Person.reset_column_information - assert !Person.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point" - Person.connection.change_column "people", "funny", :boolean, :null => true - Person.reset_column_information - assert Person.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point" - end - - def test_rename_table_with_an_index + # should be all good w/ a custom sequence name + assert_nothing_raised do begin - ActiveRecord::Base.connection.create_table :octopuses do |t| - t.column :url, :string + Person.connection.create_table :table_with_name_thats_just_ok, + :sequence_name => 'suitably_short_seq' do |t| + t.column :foo, :string, :null => false end - ActiveRecord::Base.connection.add_index :octopuses, :url - ActiveRecord::Base.connection.rename_table :octopuses, :octopi - - # Using explicit id in insert for compatibility across all databases - con = ActiveRecord::Base.connection - con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter) - assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" } - con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter) + Person.connection.execute("select suitably_short_seq.nextval from dual") - assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1") - assert ActiveRecord::Base.connection.indexes(:octopi).first.columns.include?("url") ensure - ActiveRecord::Base.connection.drop_table :octopuses rescue nil - ActiveRecord::Base.connection.drop_table :octopi rescue nil + Person.connection.drop_table :table_with_name_thats_just_ok, + :sequence_name => 'suitably_short_seq' rescue nil end end - def test_change_column - Person.connection.add_column 'people', 'age', :integer - label = "test_change_column Columns" - old_columns = Person.connection.columns(Person.table_name, label) - assert old_columns.find { |c| c.name == 'age' and c.type == :integer } - - assert_nothing_raised { Person.connection.change_column "people", "age", :string } - - new_columns = Person.connection.columns(Person.table_name, label) - assert_nil new_columns.find { |c| c.name == 'age' and c.type == :integer } - assert new_columns.find { |c| c.name == 'age' and c.type == :string } - - old_columns = Topic.connection.columns(Topic.table_name, label) - assert old_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true } - assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => false } - new_columns = Topic.connection.columns(Topic.table_name, label) - assert_nil new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true } - assert new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == false } - assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => true } - end - - def test_change_column_with_nil_default - Person.connection.add_column "people", "contributor", :boolean, :default => true - Person.reset_column_information - assert Person.new.contributor? - - assert_nothing_raised { Person.connection.change_column "people", "contributor", :boolean, :default => nil } - Person.reset_column_information - assert !Person.new.contributor? - assert_nil Person.new.contributor - ensure - Person.connection.remove_column("people", "contributor") rescue nil - end - - def test_change_column_with_new_default - Person.connection.add_column "people", "administrator", :boolean, :default => true - Person.reset_column_information - assert Person.new.administrator? - - assert_nothing_raised { Person.connection.change_column "people", "administrator", :boolean, :default => false } - Person.reset_column_information - assert !Person.new.administrator? - ensure - Person.connection.remove_column("people", "administrator") rescue nil - end - - def test_change_column_default - Person.connection.change_column_default "people", "first_name", "Tester" - Person.reset_column_information - assert_equal "Tester", Person.new.first_name - end - - def test_change_column_quotes_column_names - Person.connection.create_table :testings do |t| - t.column :select, :string - end - - assert_nothing_raised { Person.connection.change_column :testings, :select, :string, :limit => 10 } - - # Oracle needs primary key value from sequence - if current_adapter?(:OracleAdapter) - assert_nothing_raised { Person.connection.execute "insert into testings (id, #{Person.connection.quote_column_name('select')}) values (testings_seq.nextval, '7 chars')" } - else - assert_nothing_raised { Person.connection.execute "insert into testings (#{Person.connection.quote_column_name('select')}) values ('7 chars')" } - end - ensure - Person.connection.drop_table :testings rescue nil - end - - def test_keeping_default_and_notnull_constaint_on_change - Person.connection.create_table :testings do |t| - t.column :title, :string - end - person_klass = Class.new(Person) - person_klass.set_table_name 'testings' - - person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99 - person_klass.reset_column_information - assert_equal 99, person_klass.columns_hash["wealth"].default - assert_equal false, person_klass.columns_hash["wealth"].null - # Oracle needs primary key value from sequence - if current_adapter?(:OracleAdapter) - assert_nothing_raised {person_klass.connection.execute("insert into testings (id, title) values (testings_seq.nextval, 'tester')")} - else - assert_nothing_raised {person_klass.connection.execute("insert into testings (title) values ('tester')")} - end - - # change column default to see that column doesn't lose its not null definition - person_klass.connection.change_column_default "testings", "wealth", 100 - person_klass.reset_column_information - assert_equal 100, person_klass.columns_hash["wealth"].default - assert_equal false, person_klass.columns_hash["wealth"].null - - # rename column to see that column doesn't lose its not null and/or default definition - person_klass.connection.rename_column "testings", "wealth", "money" - person_klass.reset_column_information - assert_nil person_klass.columns_hash["wealth"] - assert_equal 100, person_klass.columns_hash["money"].default - assert_equal false, person_klass.columns_hash["money"].null - - # change column - person_klass.connection.change_column "testings", "money", :integer, :null => false, :default => 1000 - person_klass.reset_column_information - assert_equal 1000, person_klass.columns_hash["money"].default - assert_equal false, person_klass.columns_hash["money"].null - - # change column, make it nullable and clear default - person_klass.connection.change_column "testings", "money", :integer, :null => true, :default => nil - person_klass.reset_column_information - assert_nil person_klass.columns_hash["money"].default - assert_equal true, person_klass.columns_hash["money"].null - - # change_column_null, make it not nullable and set null values to a default value - person_klass.connection.execute('UPDATE testings SET money = NULL') - person_klass.connection.change_column_null "testings", "money", false, 2000 - person_klass.reset_column_information - assert_nil person_klass.columns_hash["money"].default - assert_equal false, person_klass.columns_hash["money"].null - assert_equal [2000], Person.connection.select_values("SELECT money FROM testings").map { |s| s.to_i }.sort - ensure - Person.connection.drop_table :testings rescue nil - end - - def test_change_column_default_to_null - Person.connection.change_column_default "people", "first_name", nil - Person.reset_column_information - assert_nil Person.new.first_name - end - - def test_column_exists - Person.connection.create_table :testings do |t| - t.column :foo, :string - end - - assert Person.connection.column_exists?(:testings, :foo) - assert !Person.connection.column_exists?(:testings, :bar) - ensure - Person.connection.drop_table :testings rescue nil - end - - def test_column_exists_with_type - Person.connection.create_table :testings do |t| - t.column :foo, :string - t.column :bar, :decimal, :precision => 8, :scale => 2 - end - - assert Person.connection.column_exists?(:testings, :foo, :string) - assert !Person.connection.column_exists?(:testings, :foo, :integer) - assert Person.connection.column_exists?(:testings, :bar, :decimal) - assert !Person.connection.column_exists?(:testings, :bar, :integer) - ensure - Person.connection.drop_table :testings rescue nil - end - - def test_column_exists_with_definition - Person.connection.create_table :testings do |t| - t.column :foo, :string, :limit => 100 - t.column :bar, :decimal, :precision => 8, :scale => 2 - end - - assert Person.connection.column_exists?(:testings, :foo, :string, :limit => 100) - assert !Person.connection.column_exists?(:testings, :foo, :string, :limit => 50) - assert Person.connection.column_exists?(:testings, :bar, :decimal, :precision => 8, :scale => 2) - assert !Person.connection.column_exists?(:testings, :bar, :decimal, :precision => 10, :scale => 2) - ensure - Person.connection.drop_table :testings rescue nil + # confirm the custom sequence got dropped + assert_raise(ActiveRecord::StatementInvalid) do + Person.connection.execute("select suitably_short_seq.nextval from dual") end + end - def test_column_exists_on_table_with_no_options_parameter_supplied - Person.connection.create_table :testings do |t| - t.string :foo - end - Person.connection.change_table :testings do |t| - assert t.column_exists?(:foo) - assert !(t.column_exists?(:bar)) - end + protected + def with_env_tz(new_tz = 'US/Eastern') + old_tz, ENV['TZ'] = ENV['TZ'], new_tz + yield ensure - Person.connection.drop_table :testings rescue nil - end - - def test_add_table - assert !Reminder.table_exists? - - WeNeedReminders.up - - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content - - WeNeedReminders.down - assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } - end - - def test_add_table_with_decimals - Person.connection.drop_table :big_numbers rescue nil - - assert !BigNumber.table_exists? - GiveMeBigNumbers.up - - assert BigNumber.create( - :bank_balance => 1586.43, - :big_bank_balance => BigDecimal("1000234000567.95"), - :world_population => 6000000000, - :my_house_population => 3, - :value_of_e => BigDecimal("2.7182818284590452353602875") - ) - - b = BigNumber.find(:first) - assert_not_nil b - - assert_not_nil b.bank_balance - assert_not_nil b.big_bank_balance - assert_not_nil b.world_population - assert_not_nil b.my_house_population - assert_not_nil b.value_of_e - - # TODO: set world_population >= 2**62 to cover 64-bit platforms and test - # is_a?(Bignum) - assert_kind_of Integer, b.world_population - assert_equal 6000000000, b.world_population - assert_kind_of Fixnum, b.my_house_population - assert_equal 3, b.my_house_population - assert_kind_of BigDecimal, b.bank_balance - assert_equal BigDecimal("1586.43"), b.bank_balance - assert_kind_of BigDecimal, b.big_bank_balance - assert_equal BigDecimal("1000234000567.95"), b.big_bank_balance - - # This one is fun. The 'value_of_e' field is defined as 'DECIMAL' with - # precision/scale explicitly left out. By the SQL standard, numbers - # assigned to this field should be truncated but that's seldom respected. - if current_adapter?(:PostgreSQLAdapter) - # - PostgreSQL changes the SQL spec on columns declared simply as - # "decimal" to something more useful: instead of being given a scale - # of 0, they take on the compile-time limit for precision and scale, - # so the following should succeed unless you have used really wacky - # compilation options - # - SQLite2 has the default behavior of preserving all data sent in, - # so this happens there too - assert_kind_of BigDecimal, b.value_of_e - assert_equal BigDecimal("2.7182818284590452353602875"), b.value_of_e - elsif current_adapter?(:SQLite3Adapter) - # - SQLite3 stores a float, in violation of SQL - assert_kind_of BigDecimal, b.value_of_e - assert_in_delta BigDecimal("2.71828182845905"), b.value_of_e, 0.00000000000001 - else - # - SQL standard is an integer - assert_kind_of Fixnum, b.value_of_e - assert_equal 2, b.value_of_e - end - - GiveMeBigNumbers.down - assert_raise(ActiveRecord::StatementInvalid) { BigNumber.find(:first) } - end - - def test_migrator - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid") - - assert_equal 3, ActiveRecord::Migrator.current_version - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content - - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid") - - assert_equal 0, ActiveRecord::Migrator.current_version - Person.reset_column_information - assert !Person.column_methods_hash.include?(:last_name) - assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } - end - - class MockMigration < ActiveRecord::Migration - attr_reader :went_up, :went_down - def initialize - @went_up = false - @went_down = false - end - - def up - @went_up = true - super - end - - def down - @went_down = true - super - end + old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') end +end - def test_instance_based_migration_up - migration = MockMigration.new - assert !migration.went_up, 'have not gone up' - assert !migration.went_down, 'have not gone down' - - migration.migrate :up - assert migration.went_up, 'have gone up' - assert !migration.went_down, 'have not gone down' - end - - def test_instance_based_migration_down - migration = MockMigration.new - assert !migration.went_up, 'have not gone up' - assert !migration.went_down, 'have not gone down' - - migration.migrate :down - assert !migration.went_up, 'have gone up' - assert migration.went_down, 'have not gone down' - end - - def test_migrator_one_up - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 2) - - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content - end - - def test_migrator_one_down - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid") - - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 1) - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - end - - def test_migrator_one_up_one_down - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) - - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - end - - def test_migrator_double_up - assert_equal(0, ActiveRecord::Migrator.current_version) - ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) - assert_nothing_raised { ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) } - assert_equal(1, ActiveRecord::Migrator.current_version) - end - - def test_migrator_double_down - assert_equal(0, ActiveRecord::Migrator.current_version) - ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) - ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) - assert_nothing_raised { ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) } - assert_equal(0, ActiveRecord::Migrator.current_version) - end - - if ActiveRecord::Base.connection.supports_ddl_transactions? - def test_migrator_one_up_with_exception_and_rollback - assert !Person.column_methods_hash.include?(:last_name) - - e = assert_raise(StandardError) do - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/broken", 100) - end - - assert_equal "An error has occurred, this and all later migrations canceled:\n\nSomething broke", e.message - - Person.reset_column_information - assert !Person.column_methods_hash.include?(:last_name) - end +class ReservedWordsMigrationTest < ActiveRecord::TestCase + def test_drop_index_from_table_named_values + connection = Person.connection + connection.create_table :values, :force => true do |t| + t.integer :value end - def test_finds_migrations - migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid").migrations - - [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i| - assert_equal migrations[i].version, pair.first - assert_equal migrations[i].name, pair.last - end + assert_nothing_raised do + connection.add_index :values, :value + connection.remove_index :values, :column => :value end - def test_finds_migrations_from_two_directories - directories = [MIGRATIONS_ROOT + '/valid_with_timestamps', MIGRATIONS_ROOT + '/to_copy_with_timestamps'] - migrations = ActiveRecord::Migrator.new(:up, directories).migrations - - [[20090101010101, "PeopleHaveHobbies"], - [20090101010202, "PeopleHaveDescriptions"], - [20100101010101, "ValidWithTimestampsPeopleHaveLastNames"], - [20100201010101, "ValidWithTimestampsWeNeedReminders"], - [20100301010101, "ValidWithTimestampsInnocentJointable"]].each_with_index do |pair, i| - assert_equal pair.first, migrations[i].version - assert_equal pair.last, migrations[i].name - end - end + connection.drop_table :values rescue nil + end +end - def test_finds_pending_migrations - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2", 1) - migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/interleaved/pass_2").pending_migrations - assert_equal 1, migrations.size - assert_equal migrations[0].version, 3 - assert_equal migrations[0].name, 'InterleavedInnocentJointable' +class ChangeTableMigrationsTest < ActiveRecord::TestCase + def setup + @connection = Person.connection + @connection.create_table :delete_me, :force => true do |t| end + end - def test_relative_migrations - list = Dir.chdir(MIGRATIONS_ROOT) do - ActiveRecord::Migrator.up("valid/", 1) - end + def teardown + Person.connection.drop_table :delete_me rescue nil + end - migration_proxy = list.find { |item| - item.name == 'ValidPeopleHaveLastNames' - } - assert migration_proxy, 'should find pending migration' + def test_references_column_type_adds_id + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {}) + t.references :customer end + end - def test_only_loads_pending_migrations - # migrate up to 1 - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - - proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", nil) - - names = proxies.map(&:name) - assert !names.include?('ValidPeopleHaveLastNames') - assert names.include?('WeNeedReminders') - assert names.include?('InnocentJointable') + def test_remove_references_column_type_removes_id + with_change_table do |t| + @connection.expects(:remove_column).with(:delete_me, 'customer_id') + t.remove_references :customer end + end - def test_target_version_zero_should_run_only_once - # migrate up to 1 - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) - - # migrate down to 0 - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) - - # migrate down to 0 again - proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) - assert_equal [], proxies + def test_add_belongs_to_works_like_add_references + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {}) + t.belongs_to :customer end + end - def test_migrator_db_has_no_schema_migrations_table - # Oracle adapter raises error if semicolon is present as last character - if current_adapter?(:OracleAdapter) - ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations") - else - ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations;") - end - assert_nothing_raised do - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) - end + def test_remove_belongs_to_works_like_remove_references + with_change_table do |t| + @connection.expects(:remove_column).with(:delete_me, 'customer_id') + t.remove_belongs_to :customer end + end - def test_migrator_verbosity - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - assert_not_equal 0, ActiveRecord::Migration.message_count - ActiveRecord::Migration.message_count = 0 - - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) - assert_not_equal 0, ActiveRecord::Migration.message_count - ActiveRecord::Migration.message_count = 0 + def test_references_column_type_with_polymorphic_adds_type + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {}) + @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {}) + t.references :taggable, :polymorphic => true end + end - def test_migrator_verbosity_off - ActiveRecord::Migration.verbose = false - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - assert_equal 0, ActiveRecord::Migration.message_count - ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) - assert_equal 0, ActiveRecord::Migration.message_count + def test_remove_references_column_type_with_polymorphic_removes_type + with_change_table do |t| + @connection.expects(:remove_column).with(:delete_me, 'taggable_type') + @connection.expects(:remove_column).with(:delete_me, 'taggable_id') + t.remove_references :taggable, :polymorphic => true end + end - def test_migrator_going_down_due_to_version_target - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) - - assert !Person.column_methods_hash.include?(:last_name) - assert !Reminder.table_exists? - - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content + def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {:null => false}) + @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {:null => false}) + t.references :taggable, :polymorphic => true, :null => false end + end - def test_migrator_rollback - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") - assert_equal(3, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(2, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(1, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(0, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal(0, ActiveRecord::Migrator.current_version) + def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag + with_change_table do |t| + @connection.expects(:remove_column).with(:delete_me, 'taggable_type') + @connection.expects(:remove_column).with(:delete_me, 'taggable_id') + t.remove_references :taggable, :polymorphic => true, :null => false end + end - def test_migrator_forward - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) - assert_equal(1, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid", 2) - assert_equal(3, ActiveRecord::Migrator.current_version) - - ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid") - assert_equal(3, ActiveRecord::Migrator.current_version) + def test_timestamps_creates_updated_at_and_created_at + with_change_table do |t| + @connection.expects(:add_timestamps).with(:delete_me) + t.timestamps end + end - def test_get_all_versions - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") - assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal([1,2], ActiveRecord::Migrator.get_all_versions) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal([1], ActiveRecord::Migrator.get_all_versions) - - ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") - assert_equal([], ActiveRecord::Migrator.get_all_versions) + def test_remove_timestamps_creates_updated_at_and_created_at + with_change_table do |t| + @connection.expects(:remove_timestamps).with(:delete_me) + t.remove_timestamps end + end - def test_schema_migrations_table_name - ActiveRecord::Base.table_name_prefix = "prefix_" - ActiveRecord::Base.table_name_suffix = "_suffix" - Reminder.reset_table_name - assert_equal "prefix_schema_migrations_suffix", ActiveRecord::Migrator.schema_migrations_table_name - ActiveRecord::Base.table_name_prefix = "" - ActiveRecord::Base.table_name_suffix = "" - Reminder.reset_table_name - assert_equal "schema_migrations", ActiveRecord::Migrator.schema_migrations_table_name - ensure - ActiveRecord::Base.table_name_prefix = "" - ActiveRecord::Base.table_name_suffix = "" - end - - def test_proper_table_name - assert_equal "table", ActiveRecord::Migrator.proper_table_name('table') - assert_equal "table", ActiveRecord::Migrator.proper_table_name(:table) - assert_equal "reminders", ActiveRecord::Migrator.proper_table_name(Reminder) - Reminder.reset_table_name - assert_equal Reminder.table_name, ActiveRecord::Migrator.proper_table_name(Reminder) - - # Use the model's own prefix/suffix if a model is given - ActiveRecord::Base.table_name_prefix = "ARprefix_" - ActiveRecord::Base.table_name_suffix = "_ARsuffix" - Reminder.table_name_prefix = 'prefix_' - Reminder.table_name_suffix = '_suffix' - Reminder.reset_table_name - assert_equal "prefix_reminders_suffix", ActiveRecord::Migrator.proper_table_name(Reminder) - Reminder.table_name_prefix = '' - Reminder.table_name_suffix = '' - Reminder.reset_table_name - - # Use AR::Base's prefix/suffix if string or symbol is given - ActiveRecord::Base.table_name_prefix = "prefix_" - ActiveRecord::Base.table_name_suffix = "_suffix" - Reminder.reset_table_name - assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name('table') - assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name(:table) - ActiveRecord::Base.table_name_prefix = "" - ActiveRecord::Base.table_name_suffix = "" - Reminder.reset_table_name - end - - def test_add_drop_table_with_prefix_and_suffix - assert !Reminder.table_exists? - ActiveRecord::Base.table_name_prefix = 'prefix_' - ActiveRecord::Base.table_name_suffix = '_suffix' - Reminder.reset_table_name - Reminder.reset_sequence_name - WeNeedReminders.up - assert Reminder.create("content" => "hello world", "remind_at" => Time.now) - assert_equal "hello world", Reminder.find(:first).content - - WeNeedReminders.down - assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } - ensure - ActiveRecord::Base.table_name_prefix = '' - ActiveRecord::Base.table_name_suffix = '' - Reminder.reset_table_name - Reminder.reset_sequence_name + def string_column + if current_adapter?(:PostgreSQLAdapter) + "character varying(255)" + elsif current_adapter?(:OracleAdapter) + 'VARCHAR2(255)' + else + 'varchar(255)' end + end - def test_create_table_with_binary_column - Person.connection.drop_table :binary_testings rescue nil - - assert_nothing_raised { - Person.connection.create_table :binary_testings do |t| - t.column "data", :binary, :null => false - end - } - - columns = Person.connection.columns(:binary_testings) - data_column = columns.detect { |c| c.name == "data" } - - if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) - assert_equal '', data_column.default - else - assert_nil data_column.default - end - - Person.connection.drop_table :binary_testings rescue nil + def integer_column + if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) + 'int(11)' + elsif current_adapter?(:OracleAdapter) + 'NUMBER(38)' + else + 'integer' end + end - def test_migrator_with_duplicates - assert_raise(ActiveRecord::DuplicateMigrationVersionError) do - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate", nil) - end + def test_integer_creates_integer_column + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, :foo, integer_column, {}) + @connection.expects(:add_column).with(:delete_me, :bar, integer_column, {}) + t.integer :foo, :bar end + end - def test_migrator_with_duplicate_names - assert_raise(ActiveRecord::DuplicateMigrationNameError, "Multiple migrations have the name Chunky") do - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate_names", nil) - end + def test_string_creates_string_column + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, :foo, string_column, {}) + @connection.expects(:add_column).with(:delete_me, :bar, string_column, {}) + t.string :foo, :bar end + end - def test_migrator_with_missing_version_numbers - assert_raise(ActiveRecord::UnknownMigrationVersionError) do - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/missing", 500) - end + def test_column_creates_column + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, :bar, :integer, {}) + t.column :bar, :integer end + end - def test_create_table_with_custom_sequence_name - return unless current_adapter? :OracleAdapter - - # table name is 29 chars, the standard sequence name will - # be 33 chars and should be shortened - assert_nothing_raised do - begin - Person.connection.create_table :table_with_name_thats_just_ok do |t| - t.column :foo, :string, :null => false - end - ensure - Person.connection.drop_table :table_with_name_thats_just_ok rescue nil - end - end - - # should be all good w/ a custom sequence name - assert_nothing_raised do - begin - Person.connection.create_table :table_with_name_thats_just_ok, - :sequence_name => 'suitably_short_seq' do |t| - t.column :foo, :string, :null => false - end - - Person.connection.execute("select suitably_short_seq.nextval from dual") - - ensure - Person.connection.drop_table :table_with_name_thats_just_ok, - :sequence_name => 'suitably_short_seq' rescue nil - end - end - - # confirm the custom sequence got dropped - assert_raise(ActiveRecord::StatementInvalid) do - Person.connection.execute("select suitably_short_seq.nextval from dual") - end + def test_column_creates_column_with_options + with_change_table do |t| + @connection.expects(:add_column).with(:delete_me, :bar, :integer, {:null => false}) + t.column :bar, :integer, :null => false end - - protected - def with_env_tz(new_tz = 'US/Eastern') - old_tz, ENV['TZ'] = ENV['TZ'], new_tz - yield - ensure - old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') - end - end - class SexyMigrationsTest < ActiveRecord::TestCase - def test_references_column_type_adds_id - with_new_table do |t| - t.expects(:column).with('customer_id', :integer, {}) - t.references :customer - end + def test_index_creates_index + with_change_table do |t| + @connection.expects(:add_index).with(:delete_me, :bar, {}) + t.index :bar end + end - def test_references_column_type_with_polymorphic_adds_type - with_new_table do |t| - t.expects(:column).with('taggable_type', :string, {}) - t.expects(:column).with('taggable_id', :integer, {}) - t.references :taggable, :polymorphic => true - end + def test_index_creates_index_with_options + with_change_table do |t| + @connection.expects(:add_index).with(:delete_me, :bar, {:unique => true}) + t.index :bar, :unique => true end + end - def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag - with_new_table do |t| - t.expects(:column).with('taggable_type', :string, {:null => false}) - t.expects(:column).with('taggable_id', :integer, {:null => false}) - t.references :taggable, :polymorphic => true, :null => false - end + def test_index_exists + with_change_table do |t| + @connection.expects(:index_exists?).with(:delete_me, :bar, {}) + t.index_exists?(:bar) end + end - def test_belongs_to_works_like_references - with_new_table do |t| - t.expects(:column).with('customer_id', :integer, {}) - t.belongs_to :customer - end + def test_index_exists_with_options + with_change_table do |t| + @connection.expects(:index_exists?).with(:delete_me, :bar, {:unique => true}) + t.index_exists?(:bar, :unique => true) end + end - def test_timestamps_creates_updated_at_and_created_at - with_new_table do |t| - t.expects(:column).with(:created_at, :datetime, kind_of(Hash)) - t.expects(:column).with(:updated_at, :datetime, kind_of(Hash)) - t.timestamps - end + def test_change_changes_column + with_change_table do |t| + @connection.expects(:change_column).with(:delete_me, :bar, :string, {}) + t.change :bar, :string end + end - def test_integer_creates_integer_column - with_new_table do |t| - t.expects(:column).with(:foo, 'integer', {}) - t.expects(:column).with(:bar, 'integer', {}) - t.integer :foo, :bar - end + def test_change_changes_column_with_options + with_change_table do |t| + @connection.expects(:change_column).with(:delete_me, :bar, :string, {:null => true}) + t.change :bar, :string, :null => true end + end - def test_string_creates_string_column - with_new_table do |t| - t.expects(:column).with(:foo, 'string', {}) - t.expects(:column).with(:bar, 'string', {}) - t.string :foo, :bar - end + def test_change_default_changes_column + with_change_table do |t| + @connection.expects(:change_column_default).with(:delete_me, :bar, :string) + t.change_default :bar, :string end + end - if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:SQLite3Adapter) || current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter) - def test_xml_creates_xml_column - type = current_adapter?(:PostgreSQLAdapter) ? 'xml' : :text - - with_new_table do |t| - t.expects(:column).with(:data, type, {}) - t.xml :data - end - end - else - def test_xml_creates_xml_column - with_new_table do |t| - assert_raises(NotImplementedError) do - t.xml :data - end - end - end + def test_remove_drops_single_column + with_change_table do |t| + @connection.expects(:remove_column).with(:delete_me, [:bar]) + t.remove :bar end + end - protected - def with_new_table - Person.connection.create_table :delete_me, :force => true do |t| - yield t - end - ensure - Person.connection.drop_table :delete_me rescue nil + def test_remove_drops_multiple_columns + with_change_table do |t| + @connection.expects(:remove_column).with(:delete_me, [:bar, :baz]) + t.remove :bar, :baz end + end - end # SexyMigrationsTest - - class MigrationLoggerTest < ActiveRecord::TestCase - def test_migration_should_be_run_without_logger - previous_logger = ActiveRecord::Base.logger - ActiveRecord::Base.logger = nil - assert_nothing_raised do - ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") - end - ensure - ActiveRecord::Base.logger = previous_logger + def test_remove_index_removes_index_with_options + with_change_table do |t| + @connection.expects(:remove_index).with(:delete_me, {:unique => true}) + t.remove_index :unique => true end end - class InterleavedMigrationsTest < ActiveRecord::TestCase - def test_migrator_interleaved_migrations - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_1") - - assert_nothing_raised do - ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2") - end - - Person.reset_column_information - assert Person.column_methods_hash.include?(:last_name) - - assert_nothing_raised do - proxies = ActiveRecord::Migrator.down( - MIGRATIONS_ROOT + "/interleaved/pass_3") - names = proxies.map(&:name) - assert names.include?('InterleavedPeopleHaveLastNames') - assert names.include?('InterleavedInnocentJointable') - end + def test_rename_renames_column + with_change_table do |t| + @connection.expects(:rename_column).with(:delete_me, :bar, :baz) + t.rename :bar, :baz end end - class ReservedWordsMigrationTest < ActiveRecord::TestCase - def test_drop_index_from_table_named_values - connection = Person.connection - connection.create_table :values, :force => true do |t| - t.integer :value - end - - assert_nothing_raised do - connection.add_index :values, :value - connection.remove_index :values, :column => :value - end - - connection.drop_table :values rescue nil + protected + def with_change_table + Person.connection.change_table :delete_me do |t| + yield t end end +end - - class ChangeTableMigrationsTest < ActiveRecord::TestCase +if ActiveRecord::Base.connection.supports_bulk_alter? + class BulkAlterTableMigrationsTest < ActiveRecord::TestCase def setup @connection = Person.connection - @connection.create_table :delete_me, :force => true do |t| - end + @connection.create_table(:delete_me, :force => true) {|t| } end def teardown - Person.connection.drop_table :delete_me rescue nil + Person.connection.drop_table(:delete_me) rescue nil end - def test_references_column_type_adds_id - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {}) - t.references :customer + def test_adding_multiple_columns + assert_queries(1) do + with_bulk_change_table do |t| + t.column :name, :string + t.string :qualification, :experience + t.integer :age, :default => 0 + t.date :birthdate + t.timestamps + end end - end - def test_remove_references_column_type_removes_id - with_change_table do |t| - @connection.expects(:remove_column).with(:delete_me, 'customer_id') - t.remove_references :customer - end + assert_equal 8, columns.size + [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type } + assert_equal 0, column(:age).default end - def test_add_belongs_to_works_like_add_references - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {}) - t.belongs_to :customer + def test_removing_columns + with_bulk_change_table do |t| + t.string :qualification, :experience end - end - def test_remove_belongs_to_works_like_remove_references - with_change_table do |t| - @connection.expects(:remove_column).with(:delete_me, 'customer_id') - t.remove_belongs_to :customer - end - end + [:qualification, :experience].each {|c| assert column(c) } - def test_references_column_type_with_polymorphic_adds_type - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {}) - @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {}) - t.references :taggable, :polymorphic => true + assert_queries(1) do + with_bulk_change_table do |t| + t.remove :qualification, :experience + t.string :qualification_experience + end end - end - def test_remove_references_column_type_with_polymorphic_removes_type - with_change_table do |t| - @connection.expects(:remove_column).with(:delete_me, 'taggable_type') - @connection.expects(:remove_column).with(:delete_me, 'taggable_id') - t.remove_references :taggable, :polymorphic => true - end + [:qualification, :experience].each {|c| assert ! column(c) } + assert column(:qualification_experience) end - def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {:null => false}) - @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {:null => false}) - t.references :taggable, :polymorphic => true, :null => false + def test_adding_indexes + with_bulk_change_table do |t| + t.string :username + t.string :name + t.integer :age end - end - def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag - with_change_table do |t| - @connection.expects(:remove_column).with(:delete_me, 'taggable_type') - @connection.expects(:remove_column).with(:delete_me, 'taggable_id') - t.remove_references :taggable, :polymorphic => true, :null => false - end - end - - def test_timestamps_creates_updated_at_and_created_at - with_change_table do |t| - @connection.expects(:add_timestamps).with(:delete_me) - t.timestamps + # Adding an index fires a query every time to check if an index already exists or not + assert_queries(3) do + with_bulk_change_table do |t| + t.index :username, :unique => true, :name => :awesome_username_index + t.index [:name, :age] + end end - end - def test_remove_timestamps_creates_updated_at_and_created_at - with_change_table do |t| - @connection.expects(:remove_timestamps).with(:delete_me) - t.remove_timestamps - end - end + assert_equal 2, indexes.size - def string_column - if current_adapter?(:PostgreSQLAdapter) - "character varying(255)" - elsif current_adapter?(:OracleAdapter) - 'VARCHAR2(255)' - else - 'varchar(255)' - end - end + name_age_index = index(:index_delete_me_on_name_and_age) + assert_equal ['name', 'age'].sort, name_age_index.columns.sort + assert ! name_age_index.unique - def integer_column - if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) - 'int(11)' - elsif current_adapter?(:OracleAdapter) - 'NUMBER(38)' - else - 'integer' - end + assert index(:awesome_username_index).unique end - def test_integer_creates_integer_column - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, :foo, integer_column, {}) - @connection.expects(:add_column).with(:delete_me, :bar, integer_column, {}) - t.integer :foo, :bar + def test_removing_index + with_bulk_change_table do |t| + t.string :name + t.index :name end - end - def test_string_creates_string_column - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, :foo, string_column, {}) - @connection.expects(:add_column).with(:delete_me, :bar, string_column, {}) - t.string :foo, :bar - end - end + assert index(:index_delete_me_on_name) - def test_column_creates_column - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, :bar, :integer, {}) - t.column :bar, :integer + assert_queries(3) do + with_bulk_change_table do |t| + t.remove_index :name + t.index :name, :name => :new_name_index, :unique => true + end end - end - def test_column_creates_column_with_options - with_change_table do |t| - @connection.expects(:add_column).with(:delete_me, :bar, :integer, {:null => false}) - t.column :bar, :integer, :null => false - end - end + assert ! index(:index_delete_me_on_name) - def test_index_creates_index - with_change_table do |t| - @connection.expects(:add_index).with(:delete_me, :bar, {}) - t.index :bar - end + new_name_index = index(:new_name_index) + assert new_name_index.unique end - def test_index_creates_index_with_options - with_change_table do |t| - @connection.expects(:add_index).with(:delete_me, :bar, {:unique => true}) - t.index :bar, :unique => true + def test_changing_columns + with_bulk_change_table do |t| + t.string :name + t.date :birthdate end - end - def test_index_exists - with_change_table do |t| - @connection.expects(:index_exists?).with(:delete_me, :bar, {}) - t.index_exists?(:bar) - end - end + assert ! column(:name).default + assert_equal :date, column(:birthdate).type - def test_index_exists_with_options - with_change_table do |t| - @connection.expects(:index_exists?).with(:delete_me, :bar, {:unique => true}) - t.index_exists?(:bar, :unique => true) + # One query for columns (delete_me table) + # One query for primary key (delete_me table) + # One query to do the bulk change + assert_queries(3) do + with_bulk_change_table do |t| + t.change :name, :string, :default => 'NONAME' + t.change :birthdate, :datetime + end end - end - def test_change_changes_column - with_change_table do |t| - @connection.expects(:change_column).with(:delete_me, :bar, :string, {}) - t.change :bar, :string - end + assert_equal 'NONAME', column(:name).default + assert_equal :datetime, column(:birthdate).type end - def test_change_changes_column_with_options - with_change_table do |t| - @connection.expects(:change_column).with(:delete_me, :bar, :string, {:null => true}) - t.change :bar, :string, :null => true - end - end + protected - def test_change_default_changes_column - with_change_table do |t| - @connection.expects(:change_column_default).with(:delete_me, :bar, :string) - t.change_default :bar, :string - end - end + def with_bulk_change_table + # Reset columns/indexes cache as we're changing the table + @columns = @indexes = nil - def test_remove_drops_single_column - with_change_table do |t| - @connection.expects(:remove_column).with(:delete_me, [:bar]) - t.remove :bar + Person.connection.change_table(:delete_me, :bulk => true) do |t| + yield t end end - def test_remove_drops_multiple_columns - with_change_table do |t| - @connection.expects(:remove_column).with(:delete_me, [:bar, :baz]) - t.remove :bar, :baz - end + def column(name) + columns.detect {|c| c.name == name.to_s } end - def test_remove_index_removes_index_with_options - with_change_table do |t| - @connection.expects(:remove_index).with(:delete_me, {:unique => true}) - t.remove_index :unique => true - end + def columns + @columns ||= Person.connection.columns('delete_me') end - def test_rename_renames_column - with_change_table do |t| - @connection.expects(:rename_column).with(:delete_me, :bar, :baz) - t.rename :bar, :baz - end + def index(name) + indexes.detect {|i| i.name == name.to_s } end - protected - def with_change_table - Person.connection.change_table :delete_me do |t| - yield t - end + def indexes + @indexes ||= Person.connection.indexes('delete_me') end - end + end # AlterTableMigrationsTest - if ActiveRecord::Base.connection.supports_bulk_alter? - class BulkAlterTableMigrationsTest < ActiveRecord::TestCase - def setup - @connection = Person.connection - @connection.create_table(:delete_me, :force => true) {|t| } - end - - def teardown - Person.connection.drop_table(:delete_me) rescue nil - end - - def test_adding_multiple_columns - assert_queries(1) do - with_bulk_change_table do |t| - t.column :name, :string - t.string :qualification, :experience - t.integer :age, :default => 0 - t.date :birthdate - t.timestamps - end - end - - assert_equal 8, columns.size - [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type } - assert_equal 0, column(:age).default - end - - def test_removing_columns - with_bulk_change_table do |t| - t.string :qualification, :experience - end - - [:qualification, :experience].each {|c| assert column(c) } - - assert_queries(1) do - with_bulk_change_table do |t| - t.remove :qualification, :experience - t.string :qualification_experience - end - end - - [:qualification, :experience].each {|c| assert ! column(c) } - assert column(:qualification_experience) - end - - def test_adding_indexes - with_bulk_change_table do |t| - t.string :username - t.string :name - t.integer :age - end - - # Adding an index fires a query every time to check if an index already exists or not - assert_queries(3) do - with_bulk_change_table do |t| - t.index :username, :unique => true, :name => :awesome_username_index - t.index [:name, :age] - end - end - - assert_equal 2, indexes.size - - name_age_index = index(:index_delete_me_on_name_and_age) - assert_equal ['name', 'age'].sort, name_age_index.columns.sort - assert ! name_age_index.unique - - assert index(:awesome_username_index).unique - end - - def test_removing_index - with_bulk_change_table do |t| - t.string :name - t.index :name - end - - assert index(:index_delete_me_on_name) - - assert_queries(3) do - with_bulk_change_table do |t| - t.remove_index :name - t.index :name, :name => :new_name_index, :unique => true - end - end - - assert ! index(:index_delete_me_on_name) - - new_name_index = index(:new_name_index) - assert new_name_index.unique - end - - def test_changing_columns - with_bulk_change_table do |t| - t.string :name - t.date :birthdate - end - - assert ! column(:name).default - assert_equal :date, column(:birthdate).type - - # One query for columns (delete_me table) - # One query for primary key (delete_me table) - # One query to do the bulk change - assert_queries(3) do - with_bulk_change_table do |t| - t.change :name, :string, :default => 'NONAME' - t.change :birthdate, :datetime - end - end - - assert_equal 'NONAME', column(:name).default - assert_equal :datetime, column(:birthdate).type - end - - protected - - def with_bulk_change_table - # Reset columns/indexes cache as we're changing the table - @columns = @indexes = nil - - Person.connection.change_table(:delete_me, :bulk => true) do |t| - yield t - end - end - - def column(name) - columns.detect {|c| c.name == name.to_s } - end - - def columns - @columns ||= Person.connection.columns('delete_me') - end - - def index(name) - indexes.detect {|i| i.name == name.to_s } - end +end - def indexes - @indexes ||= Person.connection.indexes('delete_me') - end - end # AlterTableMigrationsTest +class CopyMigrationsTest < ActiveRecord::TestCase + def setup + end + def clear + ActiveRecord::Base.timestamped_migrations = true + to_delete = Dir[@migrations_path + "/*.rb"] - @existing_migrations + File.delete(*to_delete) end - class CopyMigrationsTest < ActiveRecord::TestCase - def setup - end + def test_copying_migrations_without_timestamps + ActiveRecord::Base.timestamped_migrations = false + @migrations_path = MIGRATIONS_ROOT + "/valid" + @existing_migrations = Dir[@migrations_path + "/*.rb"] + + copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) + assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") + assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename) + + expected = "# This migration comes from bukkits (originally 1)" + assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp + + files_count = Dir[@migrations_path + "/*.rb"].length + copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) + assert_equal files_count, Dir[@migrations_path + "/*.rb"].length + assert copied.empty? + ensure + clear + end - def clear - ActiveRecord::Base.timestamped_migrations = true - to_delete = Dir[@migrations_path + "/*.rb"] - @existing_migrations - File.delete(*to_delete) - end + def test_copying_migrations_without_timestamps_from_2_sources + ActiveRecord::Base.timestamped_migrations = false + @migrations_path = MIGRATIONS_ROOT + "/valid" + @existing_migrations = Dir[@migrations_path + "/*.rb"] + + sources = ActiveSupport::OrderedHash.new + sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy" + sources[:omg] = MIGRATIONS_ROOT + "/to_copy2" + ActiveRecord::Migration.copy(@migrations_path, sources) + assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") + assert File.exists?(@migrations_path + "/6_create_articles.omg.rb") + assert File.exists?(@migrations_path + "/7_create_comments.omg.rb") + + files_count = Dir[@migrations_path + "/*.rb"].length + ActiveRecord::Migration.copy(@migrations_path, sources) + assert_equal files_count, Dir[@migrations_path + "/*.rb"].length + ensure + clear + end - def test_copying_migrations_without_timestamps - ActiveRecord::Base.timestamped_migrations = false - @migrations_path = MIGRATIONS_ROOT + "/valid" - @existing_migrations = Dir[@migrations_path + "/*.rb"] + def test_copying_migrations_with_timestamps + @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" + @existing_migrations = Dir[@migrations_path + "/*.rb"] - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) - assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb") - assert_equal [@migrations_path + "/4_people_have_hobbies.rb", @migrations_path + "/5_people_have_descriptions.rb"], copied.map(&:filename) + Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do + copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") + expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb", + @migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"] + assert_equal expected, copied.map(&:filename) files_count = Dir[@migrations_path + "/*.rb"].length - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert copied.empty? - ensure - clear end + ensure + clear + end - def test_copying_migrations_without_timestamps_from_2_sources - ActiveRecord::Base.timestamped_migrations = false - @migrations_path = MIGRATIONS_ROOT + "/valid" - @existing_migrations = Dir[@migrations_path + "/*.rb"] + def test_copying_migrations_with_timestamps_from_2_sources + @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" + @existing_migrations = Dir[@migrations_path + "/*.rb"] - sources = ActiveSupport::OrderedHash.new - sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy" - sources[:omg] = MIGRATIONS_ROOT + "/to_copy2" - ActiveRecord::Migration.copy(@migrations_path, sources) - assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb") - assert File.exists?(@migrations_path + "/6_create_articles.rb") - assert File.exists?(@migrations_path + "/7_create_comments.rb") + sources = ActiveSupport::OrderedHash.new + sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" + sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps2" + + Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do + copied = ActiveRecord::Migration.copy(@migrations_path, sources) + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101012_create_articles.omg.rb") + assert File.exists?(@migrations_path + "/20100726101013_create_comments.omg.rb") + assert_equal 4, copied.length files_count = Dir[@migrations_path + "/*.rb"].length ActiveRecord::Migration.copy(@migrations_path, sources) assert_equal files_count, Dir[@migrations_path + "/*.rb"].length - ensure - clear end + ensure + clear + end - def test_copying_migrations_with_timestamps - @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" - @existing_migrations = Dir[@migrations_path + "/*.rb"] + def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_future + @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" + @existing_migrations = Dir[@migrations_path + "/*.rb"] - Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") - expected = [@migrations_path + "/20100726101010_people_have_hobbies.rb", - @migrations_path + "/20100726101011_people_have_descriptions.rb"] - assert_equal expected, copied.map(&:filename) + Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do + ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb") - files_count = Dir[@migrations_path + "/*.rb"].length - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert_equal files_count, Dir[@migrations_path + "/*.rb"].length - assert copied.empty? - end - ensure - clear + files_count = Dir[@migrations_path + "/*.rb"].length + copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + assert_equal files_count, Dir[@migrations_path + "/*.rb"].length + assert copied.empty? end + ensure + clear + end - def test_copying_migrations_with_timestamps_from_2_sources - @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" - @existing_migrations = Dir[@migrations_path + "/*.rb"] + def test_skipping_migrations + @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" + @existing_migrations = Dir[@migrations_path + "/*.rb"] - sources = ActiveSupport::OrderedHash.new - sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" - sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps2" + sources = ActiveSupport::OrderedHash.new + sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" + sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_name_collision" - Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do - copied = ActiveRecord::Migration.copy(@migrations_path, sources) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") - assert File.exists?(@migrations_path + "/20100726101012_create_articles.rb") - assert File.exists?(@migrations_path + "/20100726101013_create_comments.rb") - assert_equal 4, copied.length + skipped = [] + on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } + copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) + assert_equal 2, copied.length - files_count = Dir[@migrations_path + "/*.rb"].length - ActiveRecord::Migration.copy(@migrations_path, sources) - assert_equal files_count, Dir[@migrations_path + "/*.rb"].length - end - ensure - clear - end + assert_equal 1, skipped.length + assert_equal ["omg PeopleHaveHobbies"], skipped + ensure + clear + end - def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_future - @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" - @existing_migrations = Dir[@migrations_path + "/*.rb"] + def test_skip_is_not_called_if_migrations_are_from_the_same_plugin + @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" + @existing_migrations = Dir[@migrations_path + "/*.rb"] - Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do - ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.rb") + sources = ActiveSupport::OrderedHash.new + sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" - files_count = Dir[@migrations_path + "/*.rb"].length - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert_equal files_count, Dir[@migrations_path + "/*.rb"].length - assert copied.empty? - end - ensure - clear - end + skipped = [] + on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } + copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) + ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) - def test_skipping_migrations - @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" - @existing_migrations = Dir[@migrations_path + "/*.rb"] + assert_equal 2, copied.length + assert_equal 0, skipped.length + ensure + clear + end - sources = ActiveSupport::OrderedHash.new - sources[:bukkits] = sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" + def test_copying_migrations_to_non_existing_directory + @migrations_path = MIGRATIONS_ROOT + "/non_existing" + @existing_migrations = [] - skipped = [] - on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } - copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) + Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do + copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") assert_equal 2, copied.length - - assert_equal 2, skipped.length - assert_equal ["bukkits PeopleHaveHobbies", "bukkits PeopleHaveDescriptions"], skipped - ensure - clear - end - - def test_copying_migrations_to_non_existing_directory - @migrations_path = MIGRATIONS_ROOT + "/non_existing" - @existing_migrations = [] - - Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") - assert_equal 2, copied.length - end - ensure - clear - Dir.delete(@migrations_path) end + ensure + clear + Dir.delete(@migrations_path) + end - def test_copying_migrations_to_empty_directory - @migrations_path = MIGRATIONS_ROOT + "/empty" - @existing_migrations = [] + def test_copying_migrations_to_empty_directory + @migrations_path = MIGRATIONS_ROOT + "/empty" + @existing_migrations = [] - Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") - assert_equal 2, copied.length - end - ensure - clear + Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do + copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") + assert_equal 2, copied.length end + ensure + clear end end diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb new file mode 100644 index 0000000000..1e16addcf3 --- /dev/null +++ b/activerecord/test/cases/migrator_test.rb @@ -0,0 +1,377 @@ +require "cases/helper" +require "cases/migration/helper" + +module ActiveRecord + class MigratorTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + + # Use this class to sense if migrations have gone + # up or down. + class Sensor < ActiveRecord::Migration + attr_reader :went_up, :went_down + + def initialize name = self.class.name, version = nil + super + @went_up = false + @went_down = false + end + + def up; @went_up = true; end + def down; @went_down = true; end + end + + def setup + super + ActiveRecord::SchemaMigration.create_table + ActiveRecord::SchemaMigration.delete_all rescue nil + end + + def teardown + super + ActiveRecord::SchemaMigration.delete_all rescue nil + end + + def test_migrator_with_duplicate_names + assert_raises(ActiveRecord::DuplicateMigrationNameError, "Multiple migrations have the name Chunky") do + list = [Migration.new('Chunky'), Migration.new('Chunky')] + ActiveRecord::Migrator.new(:up, list) + end + end + + def test_migrator_with_duplicate_versions + assert_raises(ActiveRecord::DuplicateMigrationVersionError) do + list = [Migration.new('Foo', 1), Migration.new('Bar', 1)] + ActiveRecord::Migrator.new(:up, list) + end + end + + def test_migrator_with_missing_version_numbers + assert_raises(ActiveRecord::UnknownMigrationVersionError) do + list = [Migration.new('Foo', 1), Migration.new('Bar', 2)] + ActiveRecord::Migrator.new(:up, list, 3).run + end + end + + def test_finds_migrations + migrations = ActiveRecord::Migrator.migrations(MIGRATIONS_ROOT + "/valid") + + [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i| + assert_equal migrations[i].version, pair.first + assert_equal migrations[i].name, pair.last + end + end + + def test_finds_migrations_in_subdirectories + migrations = ActiveRecord::Migrator.migrations(MIGRATIONS_ROOT + "/valid_with_subdirectories") + + [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i| + assert_equal migrations[i].version, pair.first + assert_equal migrations[i].name, pair.last + end + end + + def test_finds_migrations_from_two_directories + directories = [MIGRATIONS_ROOT + '/valid_with_timestamps', MIGRATIONS_ROOT + '/to_copy_with_timestamps'] + migrations = ActiveRecord::Migrator.migrations directories + + [[20090101010101, "PeopleHaveHobbies"], + [20090101010202, "PeopleHaveDescriptions"], + [20100101010101, "ValidWithTimestampsPeopleHaveLastNames"], + [20100201010101, "ValidWithTimestampsWeNeedReminders"], + [20100301010101, "ValidWithTimestampsInnocentJointable"]].each_with_index do |pair, i| + assert_equal pair.first, migrations[i].version + assert_equal pair.last, migrations[i].name + end + end + + def test_deprecated_constructor + assert_deprecated do + ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid") + end + end + + def test_relative_migrations + list = Dir.chdir(MIGRATIONS_ROOT) do + ActiveRecord::Migrator.migrations("valid/") + end + + migration_proxy = list.find { |item| + item.name == 'ValidPeopleHaveLastNames' + } + assert migration_proxy, 'should find pending migration' + end + + def test_finds_pending_migrations + ActiveRecord::SchemaMigration.create!(:version => '1') + migration_list = [ Migration.new('foo', 1), Migration.new('bar', 3) ] + migrations = ActiveRecord::Migrator.new(:up, migration_list).pending_migrations + + assert_equal 1, migrations.size + assert_equal migration_list.last, migrations.first + end + + def test_migrator_interleaved_migrations + pass_one = [Sensor.new('One', 1)] + + ActiveRecord::Migrator.new(:up, pass_one).migrate + assert pass_one.first.went_up + refute pass_one.first.went_down + + pass_two = [Sensor.new('One', 1), Sensor.new('Three', 3)] + ActiveRecord::Migrator.new(:up, pass_two).migrate + refute pass_two[0].went_up + assert pass_two[1].went_up + assert pass_two.all? { |x| !x.went_down } + + pass_three = [Sensor.new('One', 1), + Sensor.new('Two', 2), + Sensor.new('Three', 3)] + + ActiveRecord::Migrator.new(:down, pass_three).migrate + assert pass_three[0].went_down + refute pass_three[1].went_down + assert pass_three[2].went_down + end + + def test_up_calls_up + migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] + ActiveRecord::Migrator.new(:up, migrations).migrate + assert migrations.all? { |m| m.went_up } + assert migrations.all? { |m| !m.went_down } + assert_equal 2, ActiveRecord::Migrator.current_version + end + + def test_down_calls_down + test_up_calls_up + + migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] + ActiveRecord::Migrator.new(:down, migrations).migrate + assert migrations.all? { |m| !m.went_up } + assert migrations.all? { |m| m.went_down } + assert_equal 0, ActiveRecord::Migrator.current_version + end + + def test_current_version + ActiveRecord::SchemaMigration.create!(:version => '1000') + assert_equal 1000, ActiveRecord::Migrator.current_version + end + + def test_migrator_one_up + calls, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:up, migrations, 2).migrate + assert_equal [[:up, 2]], calls + end + + def test_migrator_one_down + calls, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations).migrate + assert_equal [[:up, 1], [:up, 2], [:up, 3]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 1).migrate + + assert_equal [[:down, 3], [:down, 2]], calls + end + + def test_migrator_one_up_one_down + calls, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal [[:down, 1]], calls + end + + def test_migrator_double_up + calls, migrations = sensors(3) + assert_equal(0, ActiveRecord::Migrator.current_version) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [], calls + end + + def test_migrator_double_down + calls, migrations = sensors(3) + + assert_equal(0, ActiveRecord::Migrator.current_version) + + ActiveRecord::Migrator.new(:up, migrations, 1).run + assert_equal [[:up, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 1).run + assert_equal [[:down, 1]], calls + calls.clear + + ActiveRecord::Migrator.new(:down, migrations, 1).run + assert_equal [], calls + + assert_equal(0, ActiveRecord::Migrator.current_version) + end + + def test_migrator_verbosity + _, migrations = sensors(3) + + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_not_equal 0, ActiveRecord::Migration.message_count + + ActiveRecord::Migration.message_count = 0 + + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_not_equal 0, ActiveRecord::Migration.message_count + ActiveRecord::Migration.message_count = 0 + end + + def test_migrator_verbosity_off + _, migrations = sensors(3) + + ActiveRecord::Migration.message_count = 0 + ActiveRecord::Migration.verbose = false + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal 0, ActiveRecord::Migration.message_count + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal 0, ActiveRecord::Migration.message_count + end + + def test_target_version_zero_should_run_only_once + calls, migrations = sensors(3) + + # migrate up to 1 + ActiveRecord::Migrator.new(:up, migrations, 1).migrate + assert_equal [[:up, 1]], calls + calls.clear + + # migrate down to 0 + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal [[:down, 1]], calls + calls.clear + + # migrate down to 0 again + ActiveRecord::Migrator.new(:down, migrations, 0).migrate + assert_equal [], calls + end + + def test_migrator_going_down_due_to_version_target + calls, migrator = migrator_class(3) + + migrator.up("valid", 1) + assert_equal [[:up, 1]], calls + calls.clear + + migrator.migrate("valid", 0) + assert_equal [[:down, 1]], calls + calls.clear + + migrator.migrate("valid") + assert_equal [[:up, 1], [:up, 2], [:up, 3]], calls + end + + def test_migrator_rollback + _, migrator = migrator_class(3) + + migrator.migrate("valid") + assert_equal(3, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(2, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(1, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(0, ActiveRecord::Migrator.current_version) + + migrator.rollback("valid") + assert_equal(0, ActiveRecord::Migrator.current_version) + end + + def test_migrator_db_has_no_schema_migrations_table + _, migrator = migrator_class(3) + + ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations") + refute ActiveRecord::Base.connection.table_exists?('schema_migrations') + migrator.migrate("valid", 1) + assert ActiveRecord::Base.connection.table_exists?('schema_migrations') + end + + def test_migrator_forward + _, migrator = migrator_class(3) + migrator.migrate("/valid", 1) + assert_equal(1, ActiveRecord::Migrator.current_version) + + migrator.forward("/valid", 2) + assert_equal(3, ActiveRecord::Migrator.current_version) + + migrator.forward("/valid") + assert_equal(3, ActiveRecord::Migrator.current_version) + end + + def test_only_loads_pending_migrations + # migrate up to 1 + ActiveRecord::SchemaMigration.create!(:version => '1') + + calls, migrator = migrator_class(3) + migrator.migrate("valid", nil) + + assert_equal [[:up, 2], [:up, 3]], calls + end + + def test_get_all_versions + _, migrator = migrator_class(3) + + migrator.migrate("valid") + assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions) + + migrator.rollback("valid") + assert_equal([1,2], ActiveRecord::Migrator.get_all_versions) + + migrator.rollback("valid") + assert_equal([1], ActiveRecord::Migrator.get_all_versions) + + migrator.rollback("valid") + assert_equal([], ActiveRecord::Migrator.get_all_versions) + end + + private + def m(name, version, &block) + x = Sensor.new name, version + x.extend(Module.new { + define_method(:up) { block.call(:up, x); super() } + define_method(:down) { block.call(:down, x); super() } + }) if block_given? + end + + def sensors(count) + calls = [] + migrations = count.times.map { |i| + m(nil, i + 1) { |c,migration| + calls << [c, migration.version] + } + } + [calls, migrations] + end + + def migrator_class(count) + calls, migrations = sensors(count) + + migrator = Class.new(Migrator).extend(Module.new { + define_method(:migrations) { |paths| + migrations + } + }) + [calls, migrator] + end + end +end diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index a2041af16a..f7a5d05582 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -72,7 +72,7 @@ class ModulesTest < ActiveRecord::TestCase clients = [] assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do - clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}, :conditions => 'accounts.id IS NOT NULL') + clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}, :conditions => 'accounts.id IS NOT NULL', :references => :accounts) clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}) end diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index bd51388e05..e704322b5d 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -85,7 +85,6 @@ class MultipleDbTest < ActiveRecord::TestCase end def test_arel_table_engines - assert_not_equal Entrant.arel_engine, Course.arel_engine assert_equal Entrant.arel_engine, Bird.arel_engine end end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 4a09a87322..e17ba76437 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -1,5 +1,4 @@ require "cases/helper" -require 'active_support/core_ext/array/random_access' require 'models/post' require 'models/topic' require 'models/comment' @@ -337,6 +336,11 @@ class NamedScopeTest < ActiveRecord::TestCase end end + def test_should_not_duplicates_where_values + where_values = Topic.where("1=1").scope_with_lambda.where_values + assert_equal ["1=1"], where_values + end + def test_chaining_with_duplicate_joins join = "INNER JOIN comments ON comments.post_id = posts.id" post = Post.find(1) diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 67a9ed6cd8..2ae9cb4888 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -45,6 +45,14 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase end end + def test_should_not_build_a_new_record_using_reject_all_even_if_destroy_is_given + pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") + pirate.birds_with_reject_all_blank_attributes = [{:name => '', :color => '', :_destroy => '0'}] + pirate.save! + + assert pirate.birds_with_reject_all_blank.empty? + end + def test_should_not_build_a_new_record_if_reject_all_blank_returns_false pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") pirate.birds_with_reject_all_blank_attributes = [{:name => '', :color => ''}] diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 379cf5b44e..fba3006ebe 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -3,19 +3,21 @@ require "models/project" require "timeout" class PooledConnectionsTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + def setup @per_test_teardown = [] - @connection = ActiveRecord::Base.remove_connection + @connection = ActiveRecord::Model.remove_connection end def teardown - ActiveRecord::Base.clear_all_connections! - ActiveRecord::Base.establish_connection(@connection) + ActiveRecord::Model.clear_all_connections! + ActiveRecord::Model.establish_connection(@connection) @per_test_teardown.each {|td| td.call } end def checkout_connections - ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 0.3})) + ActiveRecord::Model.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 0.3})) @connections = [] @timed_out = 0 @@ -31,24 +33,16 @@ class PooledConnectionsTest < ActiveRecord::TestCase end # Will deadlock due to lack of Monitor timeouts in 1.9 - if RUBY_VERSION < '1.9' - def test_pooled_connection_checkout - checkout_connections - assert_equal 2, @connections.length - assert_equal 2, @timed_out - end - end - def checkout_checkin_connections(pool_size, threads) - ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :wait_timeout => 0.5})) + ActiveRecord::Model.establish_connection(@connection.merge({:pool => pool_size, :wait_timeout => 0.5})) @connection_count = 0 @timed_out = 0 threads.times do Thread.new do begin - conn = ActiveRecord::Base.connection_pool.checkout + conn = ActiveRecord::Model.connection_pool.checkout sleep 0.1 - ActiveRecord::Base.connection_pool.checkin conn + ActiveRecord::Model.connection_pool.checkin conn @connection_count += 1 rescue ActiveRecord::ConnectionTimeoutError @timed_out += 1 @@ -61,85 +55,13 @@ class PooledConnectionsTest < ActiveRecord::TestCase checkout_checkin_connections 1, 2 assert_equal 2, @connection_count assert_equal 0, @timed_out - assert_equal 1, ActiveRecord::Base.connection_pool.connections.size - end - - def test_pooled_connection_checkin_two - checkout_checkin_connections 2, 3 - assert_equal 3, @connection_count - assert_equal 0, @timed_out - assert_equal 1, ActiveRecord::Base.connection_pool.connections.size - end - - def test_pooled_connection_checkout_existing_first - ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1})) - conn_pool = ActiveRecord::Base.connection_pool - conn = conn_pool.checkout - conn_pool.checkin(conn) - conn = conn_pool.checkout - assert ActiveRecord::ConnectionAdapters::AbstractAdapter === conn - conn_pool.checkin(conn) - end - - def test_not_connected_defined_connection_returns_false - ActiveRecord::Base.establish_connection(@connection) - assert ! ActiveRecord::Base.connected? - end - - def test_undefined_connection_returns_false - old_handler = ActiveRecord::Base.connection_handler - ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new - assert ! ActiveRecord::Base.connected? - ensure - ActiveRecord::Base.connection_handler = old_handler + assert_equal 1, ActiveRecord::Model.connection_pool.connections.size end - def test_connection_config - ActiveRecord::Base.establish_connection(@connection) - assert_equal @connection, ActiveRecord::Base.connection_config - end - - def test_with_connection_nesting_safety - ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1, :wait_timeout => 0.1})) - - before_count = Project.count - - add_record('one') - - ActiveRecord::Base.connection.transaction do - add_record('two') - # Have another thread try to screw up the transaction - Thread.new do - ActiveRecord::Base.connection.rollback_db_transaction - ActiveRecord::Base.connection_pool.release_connection - end - add_record('three') - end - - after_count = Project.count - assert_equal 3, after_count - before_count - end - - def test_connection_pool_callbacks - checked_out, checked_in = false, false - ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do - set_callback(:checkout, :after) { checked_out = true } - set_callback(:checkin, :before) { checked_in = true } - end - @per_test_teardown << proc do - ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do - reset_callbacks :checkout - reset_callbacks :checkin - end - end - checkout_checkin_connections 1, 1 - assert checked_out - assert checked_in - end private def add_record(name) - ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name } + ActiveRecord::Model.connection_pool.with_connection { Project.create! :name => name } end end unless current_adapter?(:FrontBase) || in_memory_db? diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb index 05a41d8a0a..e6e50a4cd4 100644 --- a/activerecord/test/cases/primary_keys_test.rb +++ b/activerecord/test/cases/primary_keys_test.rb @@ -23,6 +23,11 @@ class PrimaryKeysTest < ActiveRecord::TestCase assert_equal keyboard.to_key, [keyboard.id] end + def test_read_attribute_with_custom_primary_key + keyboard = Keyboard.create! + assert_equal keyboard.key_number, keyboard.read_attribute(:id) + end + def test_to_key_with_primary_key_after_destroy topic = Topic.find(1) topic.destroy @@ -142,7 +147,72 @@ class PrimaryKeysTest < ActiveRecord::TestCase assert_equal k.connection.quote_column_name("id"), k.quoted_primary_key k.primary_key = "foo" assert_equal k.connection.quote_column_name("foo"), k.quoted_primary_key - k.set_primary_key "bar" - assert_equal k.connection.quote_column_name("bar"), k.quoted_primary_key + end + + def test_two_models_with_same_table_but_different_primary_key + k1 = Class.new(ActiveRecord::Base) + k1.table_name = 'posts' + k1.primary_key = 'id' + + k2 = Class.new(ActiveRecord::Base) + k2.table_name = 'posts' + k2.primary_key = 'title' + + assert k1.columns.find { |c| c.name == 'id' }.primary + assert !k1.columns.find { |c| c.name == 'title' }.primary + assert k1.columns_hash['id'].primary + assert !k1.columns_hash['title'].primary + + assert !k2.columns.find { |c| c.name == 'id' }.primary + assert k2.columns.find { |c| c.name == 'title' }.primary + assert !k2.columns_hash['id'].primary + assert k2.columns_hash['title'].primary + end + + def test_models_with_same_table_have_different_columns + k1 = Class.new(ActiveRecord::Base) + k1.table_name = 'posts' + + k2 = Class.new(ActiveRecord::Base) + k2.table_name = 'posts' + + k1.columns.zip(k2.columns).each do |col1, col2| + assert !col1.equal?(col2) + end + end +end + +class PrimaryKeyWithNoConnectionTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + + def test_set_primary_key_with_no_connection + return skip("disconnect wipes in-memory db") if in_memory_db? + + connection = ActiveRecord::Model.remove_connection + + model = Class.new(ActiveRecord::Base) + model.primary_key = 'foo' + + assert_equal 'foo', model.primary_key + + ActiveRecord::Model.establish_connection(connection) + + assert_equal 'foo', model.primary_key + end +end + +if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) + class PrimaryKeyWithAnsiQuotesTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + + def test_primaery_key_method_with_ansi_quotes + con = ActiveRecord::Base.connection + con.execute("SET SESSION sql_mode='ANSI_QUOTES'") + assert_equal "id", con.primary_key("topics") + ensure + con.reconnect! + end + end end + diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index e3ad0cad90..f36f4237b1 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -3,7 +3,7 @@ require 'models/topic' require 'models/task' require 'models/category' require 'models/post' - +require 'rack' class QueryCacheTest < ActiveRecord::TestCase fixtures :tasks, :topics, :categories, :posts, :categories_posts @@ -43,6 +43,7 @@ class QueryCacheTest < ActiveRecord::TestCase called = false mw = ActiveRecord::QueryCache.new lambda { |env| called = true + [200, {}, nil] } mw.call({}) assert called, 'middleware should delegate' @@ -53,6 +54,7 @@ class QueryCacheTest < ActiveRecord::TestCase Task.find 1 Task.find 1 assert_equal 1, ActiveRecord::Base.connection.query_cache.length + [200, {}, nil] } mw.call({}) end @@ -62,6 +64,7 @@ class QueryCacheTest < ActiveRecord::TestCase mw = ActiveRecord::QueryCache.new lambda { |env| assert ActiveRecord::Base.connection.query_cache_enabled, 'cache on' + [200, {}, nil] } mw.call({}) end @@ -83,7 +86,7 @@ class QueryCacheTest < ActiveRecord::TestCase end def test_cache_off_after_close - mw = ActiveRecord::QueryCache.new lambda { |env| } + mw = ActiveRecord::QueryCache.new lambda { |env| [200, {}, nil] } body = mw.call({}).last assert ActiveRecord::Base.connection.query_cache_enabled, 'cache enabled' @@ -94,6 +97,7 @@ class QueryCacheTest < ActiveRecord::TestCase def test_cache_clear_after_close mw = ActiveRecord::QueryCache.new lambda { |env| Post.find(:first) + [200, {}, nil] } body = mw.call({}).last @@ -147,13 +151,16 @@ class QueryCacheTest < ActiveRecord::TestCase end def test_cache_does_not_wrap_string_results_in_arrays - require 'sqlite3/version' if current_adapter?(:SQLite3Adapter) + if current_adapter?(:SQLite3Adapter) + require 'sqlite3/version' + sqlite3_version = RUBY_PLATFORM =~ /java/ ? Jdbc::SQLite3::VERSION : SQLite3::VERSION + end Task.cache do # Oracle adapter returns count() as Fixnum or Float if current_adapter?(:OracleAdapter) assert_kind_of Numeric, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") - elsif current_adapter?(:SQLite3Adapter) && SQLite3::VERSION > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter) + elsif current_adapter?(:SQLite3Adapter) && sqlite3_version > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter) # Future versions of the sqlite3 adapter will return numeric assert_instance_of Fixnum, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") @@ -167,6 +174,18 @@ end class QueryCacheExpiryTest < ActiveRecord::TestCase fixtures :tasks, :posts, :categories, :categories_posts + def test_cache_gets_cleared_after_migration + # warm the cache + Post.find(1) + + # change the column definition + Post.connection.change_column :posts, :title, :string, :limit => 80 + assert_nothing_raised { Post.find(1) } + + # restore the old definition + Post.connection.change_column :posts, :title, :string + end + def test_find Task.connection.expects(:clear_query_cache).times(1) @@ -229,14 +248,3 @@ class QueryCacheExpiryTest < ActiveRecord::TestCase end end end - -class QueryCacheBodyProxyTest < ActiveRecord::TestCase - - test "is polite to it's body and responds to it" do - body = Class.new(String) { def to_path; "/path"; end }.new - proxy = ActiveRecord::QueryCache::BodyProxy.new(nil, body) - assert proxy.respond_to?(:to_path) - assert_equal proxy.to_path, "/path" - end - -end diff --git a/activerecord/test/cases/reaper_test.rb b/activerecord/test/cases/reaper_test.rb new file mode 100644 index 0000000000..576ab60090 --- /dev/null +++ b/activerecord/test/cases/reaper_test.rb @@ -0,0 +1,81 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class ReaperTest < ActiveRecord::TestCase + attr_reader :pool + + def setup + super + @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec + end + + def teardown + super + @pool.connections.each(&:close) + end + + class FakePool + attr_reader :reaped + + def initialize + @reaped = false + end + + def reap + @reaped = true + end + end + + # A reaper with nil time should never reap connections + def test_nil_time + fp = FakePool.new + assert !fp.reaped + reaper = ConnectionPool::Reaper.new(fp, nil) + reaper.run + assert !fp.reaped + end + + def test_some_time + fp = FakePool.new + assert !fp.reaped + + reaper = ConnectionPool::Reaper.new(fp, 0.0001) + reaper.run + until fp.reaped + Thread.pass + end + assert fp.reaped + end + + def test_pool_has_reaper + assert pool.reaper + end + + def test_reaping_frequency_configuration + spec = ActiveRecord::Base.connection_pool.spec.dup + spec.config[:reaping_frequency] = 100 + pool = ConnectionPool.new spec + assert_equal 100, pool.reaper.frequency + end + + def test_connection_pool_starts_reaper + spec = ActiveRecord::Base.connection_pool.spec.dup + spec.config[:reaping_frequency] = 0.0001 + + pool = ConnectionPool.new spec + pool.timeout = 0 + + conn = pool.checkout + count = pool.connections.length + + conn.extend(Module.new { def active?; false; end; }) + + while count == pool.connections.length + Thread.pass + end + assert_equal(count - 1, pool.connections.length) + end + end + end +end diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 41312e8661..16f05f2198 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -18,6 +18,7 @@ require 'models/subscriber' require 'models/subscription' require 'models/tag' require 'models/sponsor' +require 'models/edge' class ReflectionTest < ActiveRecord::TestCase include ActiveRecord::Reflection @@ -35,25 +36,25 @@ class ReflectionTest < ActiveRecord::TestCase def test_read_attribute_names assert_equal( - %w( id title author_name author_email_address bonus_time written_on last_read content group approved replies_count parent_id parent_title type created_at updated_at ).sort, + %w( id title author_name author_email_address bonus_time written_on last_read content important group approved replies_count parent_id parent_title type created_at updated_at ).sort, @first.attribute_names.sort ) end def test_columns - assert_equal 16, Topic.columns.length + assert_equal 17, Topic.columns.length end def test_columns_are_returned_in_the_order_they_were_declared column_names = Topic.columns.map { |column| column.name } - assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content approved replies_count parent_id parent_title type group created_at updated_at), column_names + assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content important approved replies_count parent_id parent_title type group created_at updated_at), column_names end def test_content_columns content_columns = Topic.content_columns content_column_names = content_columns.map {|column| column.name} - assert_equal 12, content_columns.length - assert_equal %w(title author_name author_email_address written_on bonus_time last_read content group approved parent_title created_at updated_at).sort, content_column_names.sort + assert_equal 13, content_columns.length + assert_equal %w(title author_name author_email_address written_on bonus_time last_read content important group approved parent_title created_at updated_at).sort, content_column_names.sort end def test_column_string_type_and_limit @@ -188,8 +189,8 @@ class ReflectionTest < ActiveRecord::TestCase def test_reflection_of_all_associations # FIXME these assertions bust a lot - assert_equal 36, Firm.reflect_on_all_associations.size - assert_equal 26, Firm.reflect_on_all_associations(:has_many).size + assert_equal 39, Firm.reflect_on_all_associations.size + assert_equal 29, Firm.reflect_on_all_associations(:has_many).size assert_equal 10, Firm.reflect_on_all_associations(:has_one).size assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size end @@ -244,7 +245,7 @@ class ReflectionTest < ActiveRecord::TestCase # Normal association assert_equal "id", Author.reflect_on_association(:posts).association_primary_key.to_s assert_equal "name", Author.reflect_on_association(:essay).association_primary_key.to_s - assert_equal "id", Tagging.reflect_on_association(:taggable).association_primary_key.to_s + assert_equal "name", Essay.reflect_on_association(:writer).association_primary_key.to_s # Through association (uses the :primary_key option from the source reflection) assert_equal "nick", Author.reflect_on_association(:subscribers).association_primary_key.to_s @@ -252,11 +253,25 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal "custom_primary_key", Author.reflect_on_association(:tags_with_primary_key).association_primary_key.to_s # nested end + def test_association_primary_key_raises_when_missing_primary_key + reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :edge, {}, Author) + assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.association_primary_key } + + through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, {}, Author) + through.stubs(:source_reflection).returns(stub_everything(:options => {}, :class_name => 'Edge')) + assert_raises(ActiveRecord::UnknownPrimaryKey) { through.association_primary_key } + end + def test_active_record_primary_key assert_equal "nick", Subscriber.reflect_on_association(:subscriptions).active_record_primary_key.to_s assert_equal "name", Author.reflect_on_association(:essay).active_record_primary_key.to_s end + def test_active_record_primary_key_raises_when_missing_primary_key + reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :author, {}, Edge) + assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.active_record_primary_key } + end + def test_foreign_type assert_equal "sponsorable_type", Sponsor.reflect_on_association(:sponsorable).foreign_type.to_s assert_equal "sponsorable_type", Sponsor.reflect_on_association(:thing).foreign_type.to_s @@ -304,6 +319,16 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s end + def test_through_reflection_conditions_do_not_modify_other_reflections + orig_conds = Post.reflect_on_association(:first_blue_tags_2).conditions.inspect + Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions + assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).conditions.inspect + end + + def test_symbol_for_class_name + assert_equal Client, Firm.reflect_on_association(:unsorted_clients_with_symbol).klass + end + private def assert_reflection(klass, association, options) assert reflection = klass.reflect_on_association(association) diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 1e2093273e..edf38cb7a3 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -106,7 +106,7 @@ class RelationScopingTest < ActiveRecord::TestCase def test_scoped_find_include # with the include, will retrieve only developers for the given project scoped_developers = Developer.includes(:projects).scoping do - Developer.where('projects.id = 2').all + Developer.where('projects.id' => 2).all end assert scoped_developers.include?(developers(:david)) assert !scoped_developers.include?(developers(:jamis)) @@ -421,6 +421,12 @@ class DefaultScopingTest < ActiveRecord::TestCase assert_equal expected, received end + def test_order_after_reorder_combines_orders + expected = Developer.order('name DESC, id DESC').collect { |dev| [dev.name, dev.id] } + received = Developer.order('name ASC').reorder('name DESC').order('id DESC').collect { |dev| [dev.name, dev.id] } + assert_equal expected, received + end + def test_nested_exclusive_scope expected = Developer.find(:all, :limit => 100).collect { |dev| dev.salary } received = DeveloperOrderedBySalary.send(:with_exclusive_scope, :find => { :limit => 100 }) do diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index b23ead6feb..ac6dee3c6a 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -20,7 +20,7 @@ module ActiveRecord end def test_single_values - assert_equal [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order].map(&:to_s).sort, + assert_equal [:limit, :offset, :lock, :readonly, :from, :reordering, :reverse_order, :uniq].map(&:to_s).sort, Relation::SINGLE_VALUE_METHODS.map(&:to_s).sort end @@ -44,7 +44,7 @@ module ActiveRecord end def test_multi_value_methods - assert_equal [:select, :group, :order, :joins, :where, :having, :bind].map(&:to_s).sort, + assert_equal [:select, :group, :order, :joins, :where, :having, :bind, :references].map(&:to_s).sort, Relation::MULTI_VALUE_METHODS.map(&:to_s).sort end @@ -135,5 +135,24 @@ module ActiveRecord relation.eager_load_values << :b assert relation.eager_loading? end + + def test_references_values + relation = Relation.new :a, :b + assert_equal [], relation.references_values + relation = relation.references(:foo).references(:omg, :lol) + assert_equal ['foo', 'omg', 'lol'], relation.references_values + end + + def test_references_values_dont_duplicate + relation = Relation.new :a, :b + relation = relation.references(:foo).references(:foo) + assert_equal ['foo'], relation.references_values + end + + def test_apply_finder_options_takes_references + relation = Relation.new :a, :b + relation = relation.apply_finder_options(:references => :foo) + assert_equal ['foo'], relation.references_values + end end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 95408a5f29..0471d03f3b 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -184,12 +184,12 @@ class RelationTest < ActiveRecord::TestCase end def test_finding_with_complex_order_and_limit - tags = Tag.includes(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a + tags = Tag.includes(:taggings).references(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a assert_equal 1, tags.length end def test_finding_with_complex_order - tags = Tag.includes(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").to_a + tags = Tag.includes(:taggings).references(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").to_a assert_equal 3, tags.length end @@ -215,6 +215,19 @@ class RelationTest < ActiveRecord::TestCase assert_equal [2, 4, 6, 8, 10], even_ids.sort end + def test_none + assert_no_queries do + assert_equal [], Developer.none + assert_equal [], Developer.scoped.none + end + end + + def test_none_chainable + assert_no_queries do + assert_equal [], Developer.none.where(:name => 'David') + end + end + def test_joins_with_nil_argument assert_nothing_raised { DependentFirm.joins(nil).first } end @@ -1104,7 +1117,9 @@ class RelationTest < ActiveRecord::TestCase ) ) - assert scope.eager_loading? + assert_deprecated do + assert scope.eager_loading? + end end def test_ordering_with_extra_spaces @@ -1148,4 +1163,65 @@ class RelationTest < ActiveRecord::TestCase assert_equal posts(:thinking), comments(:more_greetings).post assert_equal posts(:welcome), comments(:greetings).post end + + def test_uniq + tag1 = Tag.create(:name => 'Foo') + tag2 = Tag.create(:name => 'Foo') + + query = Tag.select(:name).where(:id => [tag1.id, tag2.id]) + + assert_equal ['Foo', 'Foo'], query.map(&:name) + assert_sql(/DISTINCT/) do + assert_equal ['Foo'], query.uniq.map(&:name) + end + assert_sql(/DISTINCT/) do + assert_equal ['Foo'], query.uniq(true).map(&:name) + end + assert_equal ['Foo', 'Foo'], query.uniq(true).uniq(false).map(&:name) + end + + def test_references_triggers_eager_loading + scope = Post.includes(:comments) + assert !scope.eager_loading? + assert scope.references(:comments).eager_loading? + end + + def test_references_doesnt_trigger_eager_loading_if_reference_not_included + scope = Post.references(:comments) + assert !scope.eager_loading? + end + + def test_automatically_added_where_references + scope = Post.where(:comments => { :body => "Bla" }) + assert_equal ['comments'], scope.references_values + + scope = Post.where('comments.body' => 'Bla') + assert_equal ['comments'], scope.references_values + end + + def test_automatically_added_having_references + scope = Post.having(:comments => { :body => "Bla" }) + assert_equal ['comments'], scope.references_values + + scope = Post.having('comments.body' => 'Bla') + assert_equal ['comments'], scope.references_values + end + + def test_automatically_added_order_references + scope = Post.order('comments.body') + assert_equal ['comments'], scope.references_values + + scope = Post.order('comments.body', 'yaks.body') + assert_equal ['comments', 'yaks'], scope.references_values + + # Don't infer yaks, let's not go down that road again... + scope = Post.order('comments.body, yaks.body') + assert_equal ['comments'], scope.references_values + + scope = Post.order('comments.body asc') + assert_equal ['comments'], scope.references_values + + scope = Post.order('foo(comments.body)') + assert_equal [], scope.references_values + end end diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 71ff727b7f..abeb56fd3f 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -2,7 +2,13 @@ require "cases/helper" class SchemaDumperTest < ActiveRecord::TestCase + def initialize(*) + super + ActiveRecord::SchemaMigration.create_table + end + def setup + super @stream = StringIO.new end @@ -13,10 +19,18 @@ class SchemaDumperTest < ActiveRecord::TestCase @stream.string end - if "string".encoding_aware? - def test_magic_comment - assert_match "# encoding: #{@stream.external_encoding.name}", standard_dump + def test_dump_schema_information_outputs_lexically_ordered_versions + versions = %w{ 20100101010101 20100201010101 20100301010101 } + versions.reverse.each do |v| + ActiveRecord::SchemaMigration.create!(:version => v) end + + schema_info = ActiveRecord::Base.connection.dump_schema_information + assert_match(/20100201010101.*20100301010101/m, schema_info) + end + + def test_magic_comment + assert_match "# encoding: #{@stream.external_encoding.name}", standard_dump end def test_schema_dump @@ -238,4 +252,9 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r(:id => false), match[1], "no table id not preserved" assert_match %r{t.string[[:space:]]+"id",[[:space:]]+:null => false$}, match[2], "non-primary key id column not preserved" end + + def test_schema_dump_keeps_id_false_when_id_is_false_and_unique_not_null_column_added + output = standard_dump + assert_match %r{create_table "subscribers", :id => false}, output + end end diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb index 61b04b3e37..a4c065e667 100644 --- a/activerecord/test/cases/serialization_test.rb +++ b/activerecord/test/cases/serialization_test.rb @@ -13,7 +13,8 @@ class SerializationTest < ActiveRecord::TestCase :created_at => Time.utc(2006, 8, 1), :awesome => false, :preferences => { :gem => '<strong>ruby</strong>' }, - :alternative_id => nil + :alternative_id => nil, + :id => nil } end @@ -24,7 +25,7 @@ class SerializationTest < ActiveRecord::TestCase end def test_serialize_should_be_reversible - for format in FORMATS + FORMATS.each do |format| @serialized = Contact.new.send("to_#{format}") contact = Contact.new.send("from_#{format}", @serialized) @@ -33,7 +34,7 @@ class SerializationTest < ActiveRecord::TestCase end def test_serialize_should_allow_attribute_only_filtering - for format in FORMATS + FORMATS.each do |format| @serialized = Contact.new(@contact_attributes).send("to_#{format}", :only => [ :age, :name ]) contact = Contact.new.send("from_#{format}", @serialized) assert_equal @contact_attributes[:name], contact.name, "For #{format}" @@ -42,7 +43,7 @@ class SerializationTest < ActiveRecord::TestCase end def test_serialize_should_allow_attribute_except_filtering - for format in FORMATS + FORMATS.each do |format| @serialized = Contact.new(@contact_attributes).send("to_#{format}", :except => [ :age, :name ]) contact = Contact.new.send("from_#{format}", @serialized) assert_nil contact.name, "For #{format}" diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb index 258cee7aba..a3b8ab74d9 100644 --- a/activerecord/test/cases/session_store/session_test.rb +++ b/activerecord/test/cases/session_store/session_test.rb @@ -5,11 +5,15 @@ require 'active_record/session_store' module ActiveRecord class SessionStore class SessionTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? && ActiveRecord::Base.connection.supports_ddl_transactions? + self.use_transactional_fixtures = false + + attr_reader :session_klass def setup super + ActiveRecord::Base.connection.schema_cache.clear! Session.drop_table! if Session.table_exists? + @session_klass = Class.new(Session) end def test_data_column_name @@ -60,8 +64,8 @@ module ActiveRecord def test_find_by_session_id Session.create_table! session_id = "10" - s = Session.create!(:data => 'world', :session_id => session_id) - t = Session.find_by_session_id(session_id) + s = session_klass.create!(:data => 'world', :session_id => session_id) + t = session_klass.find_by_session_id(session_id) assert_equal s, t assert_equal s.data, t.data Session.drop_table! diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb new file mode 100644 index 0000000000..40520d6da2 --- /dev/null +++ b/activerecord/test/cases/store_test.rb @@ -0,0 +1,43 @@ +require 'cases/helper' +require 'models/admin' +require 'models/admin/user' + +class StoreTest < ActiveRecord::TestCase + setup do + @john = Admin::User.create(:name => 'John Doe', :color => 'black', :remember_login => true) + end + + test "reading store attributes through accessors" do + assert_equal 'black', @john.color + assert_nil @john.homepage + end + + test "writing store attributes through accessors" do + @john.color = 'red' + @john.homepage = '37signals.com' + + assert_equal 'red', @john.color + assert_equal '37signals.com', @john.homepage + end + + test "accessing attributes not exposed by accessors" do + @john.settings[:icecream] = 'graeters' + @john.save + + assert_equal 'graeters', @john.reload.settings[:icecream] + end + + test "updating the store will mark it as changed" do + @john.color = 'red' + assert @john.settings_changed? + end + + test "object initialization with not nullable column" do + assert_equal true, @john.remember_login + end + + test "writing with not nullable column" do + @john.remember_login = false + assert_equal false, @john.remember_login + end +end diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb new file mode 100644 index 0000000000..f0fefe6c48 --- /dev/null +++ b/activerecord/test/cases/test_case.rb @@ -0,0 +1,63 @@ +require 'active_support/test_case' + +module ActiveRecord + # = Active Record Test Case + # + # Defines some test assertions to test against SQL queries. + class TestCase < ActiveSupport::TestCase #:nodoc: + setup :cleanup_identity_map + + def setup + cleanup_identity_map + end + + def teardown + ActiveRecord::SQLCounter.log.clear + end + + def cleanup_identity_map + ActiveRecord::IdentityMap.clear + end + + def assert_date_from_db(expected, actual, message = nil) + # SybaseAdapter doesn't have a separate column type just for dates, + # so the time is in the string and incorrectly formatted + if current_adapter?(:SybaseAdapter) + assert_equal expected.to_s, actual.to_date.to_s, message + else + assert_equal expected.to_s, actual.to_s, message + end + end + + def assert_sql(*patterns_to_match) + ActiveRecord::SQLCounter.log = [] + yield + ActiveRecord::SQLCounter.log + ensure + failed_patterns = [] + patterns_to_match.each do |pattern| + failed_patterns << pattern unless ActiveRecord::SQLCounter.log.any?{ |sql| pattern === sql } + end + assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}" + end + + def assert_queries(num = 1) + ActiveRecord::SQLCounter.log = [] + yield + ensure + assert_equal num, ActiveRecord::SQLCounter.log.size, "#{ActiveRecord::SQLCounter.log.size} instead of #{num} queries were executed.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}" + end + + def assert_no_queries(&block) + prev_ignored_sql = ActiveRecord::SQLCounter.ignored_sql + ActiveRecord::SQLCounter.ignored_sql = [] + assert_queries(0, &block) + ensure + ActiveRecord::SQLCounter.ignored_sql = prev_ignored_sql + end + + def sqlite3? connection + connection.class.name.split('::').last == "SQLite3Adapter" + end + end +end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 4445a12e1d..447aa29ffe 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -60,6 +60,16 @@ class TimestampTest < ActiveRecord::TestCase Developer.record_timestamps = true end + def test_saving_when_instance_record_timestamps_is_false_doesnt_update_its_timestamp + @developer.record_timestamps = false + assert Developer.record_timestamps + + @developer.name = "John Smith" + @developer.save! + + assert_equal @previously_updated_at, @developer.updated_at + end + def test_touching_an_attribute_updates_timestamp previously_created_at = @developer.created_at @developer.touch(:created_at) diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index 85f222bca2..f8b3e01a49 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -6,7 +6,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase fixtures :topics class TopicWithCallbacks < ActiveRecord::Base - set_table_name :topics + self.table_name = :topics after_commit{|record| record.send(:do_after_commit, nil)} after_commit(:on => :create){|record| record.send(:do_after_commit, :create)} @@ -252,7 +252,7 @@ class TransactionObserverCallbacksTest < ActiveRecord::TestCase fixtures :topics class TopicWithObserverAttached < ActiveRecord::Base - set_table_name :topics + self.table_name = :topics def history @history ||= [] end diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 110a18772f..203dd054f1 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -563,6 +563,7 @@ if current_adapter?(:PostgreSQLAdapter) topic.approved = !topic.approved? topic.save! end + Topic.connection.close end end @@ -598,6 +599,7 @@ if current_adapter?(:PostgreSQLAdapter) dev = Developer.find(1) assert_equal original_salary, dev.salary end + Developer.connection.close end end @@ -610,6 +612,7 @@ if current_adapter?(:PostgreSQLAdapter) assert_equal original_salary, Developer.find(1).salary end end + Developer.connection.close end threads.each { |t| t.join } diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index f85fb4e5da..5a69054445 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -4,16 +4,16 @@ class TestRecord < ActiveRecord::Base end class TestUnconnectedAdapter < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_fixtures = false def setup - @underlying = ActiveRecord::Base.connection - @specification = ActiveRecord::Base.remove_connection + @underlying = ActiveRecord::Model.connection + @specification = ActiveRecord::Model.remove_connection end def teardown @underlying = nil - ActiveRecord::Base.establish_connection(@specification) + ActiveRecord::Model.establish_connection(@specification) load_schema if in_memory_db? end diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb index 56e345990f..c72b7b35cd 100644 --- a/activerecord/test/cases/validations/association_validation_test.rb +++ b/activerecord/test/cases/validations/association_validation_test.rb @@ -61,6 +61,16 @@ class AssociationValidationTest < ActiveRecord::TestCase assert r.valid? end + def test_validates_associated_marked_for_destruction + Topic.validates_associated(:replies) + Reply.validates_presence_of(:content) + t = Topic.new + t.replies << Reply.new + assert t.invalid? + t.replies.first.mark_for_destruction + assert t.valid? + end + def test_validates_associated_with_custom_message_using_quotes Reply.validates_associated :topic, :message=> "This string contains 'single' and \"double\" quotes" Topic.validates_presence_of :content @@ -81,14 +91,12 @@ class AssociationValidationTest < ActiveRecord::TestCase end def test_validates_size_of_association_utf8 - with_kcode('UTF8') do - assert_nothing_raised { 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 + assert_nothing_raised { 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_presence_of_belongs_to_association__parent_is_new_record @@ -110,4 +118,21 @@ class AssociationValidationTest < ActiveRecord::TestCase end end + def test_validates_associated_models_in_the_same_context + Topic.validates_presence_of :title, :on => :custom_context + Topic.validates_associated :replies + Reply.validates_presence_of :title, :on => :custom_context + + t = Topic.new('title' => '') + r = t.replies.new('title' => '') + + assert t.valid? + assert !t.valid?(:custom_context) + + t.title = "Longer" + assert !t.valid?(:custom_context), "Should NOT be valid if the associated object is not valid in the same context." + + r.title = "Longer" + assert t.valid?(:custom_context), "Should be valid if the associated object is not valid in the same context." + end end diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 0f1b3667cc..79442d68b0 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -45,6 +45,18 @@ class UniquenessValidationTest < ActiveRecord::TestCase assert t2.save, "Should now save t2 as unique" end + def test_validates_uniqueness_with_nil_value + Topic.validates_uniqueness_of(:title) + + t = Topic.new("title" => nil) + assert t.save, "Should save t as unique" + + t2 = Topic.new("title" => nil) + assert !t2.valid?, "Shouldn't be valid" + assert !t2.save, "Shouldn't save t2 as unique" + assert_equal ["has already been taken"], t2.errors[:title] + end + def test_validates_uniqueness_with_validates Topic.validates :title, :uniqueness => true Topic.create!('title' => 'abc') @@ -80,6 +92,30 @@ class UniquenessValidationTest < ActiveRecord::TestCase assert r3.valid?, "Saving r3" end + def test_validate_uniqueness_with_object_scope + Reply.validates_uniqueness_of(:content, :scope => :topic) + + t = Topic.create("title" => "I'm unique!") + + r1 = t.replies.create "title" => "r1", "content" => "hello world" + assert r1.valid?, "Saving r1" + + r2 = t.replies.create "title" => "r2", "content" => "hello world" + assert !r2.valid?, "Saving r2 first time" + end + + def test_validate_uniqueness_with_object_arg + Reply.validates_uniqueness_of(:topic) + + t = Topic.create("title" => "I'm unique!") + + r1 = t.replies.create "title" => "r1", "content" => "hello world" + assert r1.valid?, "Saving r1" + + r2 = t.replies.create "title" => "r2", "content" => "hello world" + assert !r2.valid?, "Saving r2 first time" + end + def test_validate_uniqueness_scoped_to_defining_class t = Topic.create("title" => "What, me worry?") @@ -149,16 +185,14 @@ class UniquenessValidationTest < ActiveRecord::TestCase assert t2.valid?, "should validate with nil" assert t2.save, "should save with nil" - with_kcode('UTF8') do - t_utf8 = Topic.new("title" => "Я тоже уникальный!") - assert t_utf8.save, "Should save t_utf8 as unique" + t_utf8 = Topic.new("title" => "Я тоже уникальный!") + assert t_utf8.save, "Should save t_utf8 as unique" - # If database hasn't UTF-8 character set, this test fails - if Topic.find(t_utf8, :select => 'LOWER(title) AS title').title == "я тоже уникальный!" - t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!") - assert !t2_utf8.valid?, "Shouldn't be valid" - assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique" - end + # If database hasn't UTF-8 character set, this test fails + if Topic.find(t_utf8, :select => 'LOWER(title) AS title').title == "я тоже уникальный!" + t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!") + assert !t2_utf8.valid?, "Shouldn't be valid" + assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique" end end @@ -256,13 +290,11 @@ class UniquenessValidationTest < ActiveRecord::TestCase end def test_validate_uniqueness_with_limit_and_utf8 - with_kcode('UTF8') do - # Event.title is limited to 5 characters - e1 = Event.create(:title => "一二三四五") - assert e1.valid?, "Could not create an event with a unique, 5 character title" - e2 = Event.create(:title => "一二三四五六七八") - assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique" - end + # Event.title is limited to 5 characters + e1 = Event.create(:title => "一二三四五") + assert e1.valid?, "Could not create an event with a unique, 5 character title" + e2 = Event.create(:title => "一二三四五六七八") + assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique" end def test_validate_straight_inheritance_uniqueness diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index c3e494866b..e575a98170 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -8,7 +8,7 @@ require 'models/parrot' require 'models/company' class ProtectedPerson < ActiveRecord::Base - set_table_name 'people' + self.table_name = 'people' attr_accessor :addon attr_protected :first_name end diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 0b54c309d1..302913e095 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -1,14 +1,20 @@ -require "cases/helper" +require 'cases/helper' require 'models/topic' class YamlSerializationTest < ActiveRecord::TestCase fixtures :topics def test_to_yaml_with_time_with_zone_should_not_raise_exception + tz = Time.zone Time.zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"] ActiveRecord::Base.time_zone_aware_attributes = true + topic = Topic.new(:written_on => DateTime.now) assert_nothing_raised { topic.to_yaml } + + ensure + Time.zone = tz + ActiveRecord::Base.time_zone_aware_attributes = false end def test_roundtrip @@ -18,6 +24,11 @@ class YamlSerializationTest < ActiveRecord::TestCase assert_equal topic, t end + def test_roundtrip_serialized_column + topic = Topic.new(:content => {:omg=>:lol}) + assert_equal({:omg=>:lol}, YAML.load(YAML.dump(topic)).content) + end + def test_encode_with_coder topic = Topic.first coder = {} @@ -25,22 +36,17 @@ class YamlSerializationTest < ActiveRecord::TestCase assert_equal({'attributes' => topic.attributes}, coder) end - begin - require 'psych' - - def test_psych_roundtrip - topic = Topic.first - assert topic - t = Psych.load Psych.dump topic - assert_equal topic, t - end - - def test_psych_roundtrip_new_object - topic = Topic.new - assert topic - t = Psych.load Psych.dump topic - assert_equal topic.attributes, t.attributes - end - rescue LoadError + def test_psych_roundtrip + topic = Topic.first + assert topic + t = Psych.load Psych.dump topic + assert_equal topic, t + end + + def test_psych_roundtrip_new_object + topic = Topic.new + assert topic + t = Psych.load Psych.dump topic + assert_equal topic.attributes, t.attributes end end diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml index 8c1a45430e..f450efd839 100644 --- a/activerecord/test/config.example.yml +++ b/activerecord/test/config.example.yml @@ -37,11 +37,13 @@ connections: db2: arunit: + adapter: ibm_db host: localhost username: arunit password: arunit database: arunit arunit2: + adapter: ibm_db host: localhost username: arunit password: arunit diff --git a/activerecord/test/fixtures/admin/randomly_named_a9.yml b/activerecord/test/fixtures/admin/randomly_named_a9.yml new file mode 100644 index 0000000000..bc51c83112 --- /dev/null +++ b/activerecord/test/fixtures/admin/randomly_named_a9.yml @@ -0,0 +1,7 @@ +first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/admin/randomly_named_b0.yml b/activerecord/test/fixtures/admin/randomly_named_b0.yml new file mode 100644 index 0000000000..bc51c83112 --- /dev/null +++ b/activerecord/test/fixtures/admin/randomly_named_b0.yml @@ -0,0 +1,7 @@ +first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/developers.yml b/activerecord/test/fixtures/developers.yml index 308bf75de2..3656564f63 100644 --- a/activerecord/test/fixtures/developers.yml +++ b/activerecord/test/fixtures/developers.yml @@ -8,7 +8,7 @@ jamis: name: Jamis salary: 150000 -<% for digit in 3..10 %> +<% (3..10).each do |digit| %> dev_<%= digit %>: id: <%= digit %> name: fixture_<%= digit %> diff --git a/activerecord/test/fixtures/dog_lovers.yml b/activerecord/test/fixtures/dog_lovers.yml new file mode 100644 index 0000000000..d3e5e4a1aa --- /dev/null +++ b/activerecord/test/fixtures/dog_lovers.yml @@ -0,0 +1,4 @@ +david: + id: 1 + bred_dogs_count: 0 + trained_dogs_count: 1 diff --git a/activerecord/test/fixtures/dogs.yml b/activerecord/test/fixtures/dogs.yml new file mode 100644 index 0000000000..16d19be2c5 --- /dev/null +++ b/activerecord/test/fixtures/dogs.yml @@ -0,0 +1,3 @@ +sophie: + id: 1 + trainer_id: 1 diff --git a/activerecord/test/fixtures/other_topics.yml b/activerecord/test/fixtures/other_topics.yml new file mode 100644 index 0000000000..93f48aedc4 --- /dev/null +++ b/activerecord/test/fixtures/other_topics.yml @@ -0,0 +1,42 @@ +first: + id: 1 + title: The First Topic + author_name: David + author_email_address: david@loudthinking.com + written_on: 2003-07-16t15:28:11.2233+01:00 + last_read: 2004-04-15 + bonus_time: 2005-01-30t15:28:00.00+01:00 + content: Have a nice day + approved: false + replies_count: 1 + +second: + id: 2 + title: The Second Topic of the day + author_name: Mary + written_on: 2004-07-15t15:28:00.0099+01:00 + content: Have a nice day + approved: true + replies_count: 0 + parent_id: 1 + type: Reply + +third: + id: 3 + title: The Third Topic of the day + author_name: Carl + written_on: 2005-07-15t15:28:00.0099+01:00 + content: I'm a troll + approved: true + replies_count: 1 + +fourth: + id: 4 + title: The Fourth Topic of the day + author_name: Carl + written_on: 2006-07-15t15:28:00.0099+01:00 + content: Why not? + approved: true + type: Reply + parent_id: 3 + diff --git a/activerecord/test/fixtures/randomly_named_a9.yml b/activerecord/test/fixtures/randomly_named_a9.yml new file mode 100644 index 0000000000..bc51c83112 --- /dev/null +++ b/activerecord/test/fixtures/randomly_named_a9.yml @@ -0,0 +1,7 @@ +first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/teapots.yml b/activerecord/test/fixtures/teapots.yml new file mode 100644 index 0000000000..ff515beb45 --- /dev/null +++ b/activerecord/test/fixtures/teapots.yml @@ -0,0 +1,3 @@ +bob: + id: 1 + name: Bob diff --git a/activerecord/test/migrations/broken/100_migration_that_raises_exception.rb b/activerecord/test/migrations/broken/100_migration_that_raises_exception.rb deleted file mode 100644 index ffb224dad9..0000000000 --- a/activerecord/test/migrations/broken/100_migration_that_raises_exception.rb +++ /dev/null @@ -1,10 +0,0 @@ -class MigrationThatRaisesException < ActiveRecord::Migration - def self.up - add_column "people", "last_name", :string - raise 'Something broke' - end - - def self.down - remove_column "people", "last_name" - end -end diff --git a/activerecord/test/migrations/duplicate/3_foo.rb b/activerecord/test/migrations/duplicate/3_foo.rb deleted file mode 100644 index 916fe580fa..0000000000 --- a/activerecord/test/migrations/duplicate/3_foo.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Foo < ActiveRecord::Migration - def self.up - end - - def self.down - end -end
\ No newline at end of file diff --git a/activerecord/test/migrations/duplicate_names/20080507052938_chunky.rb b/activerecord/test/migrations/duplicate_names/20080507052938_chunky.rb deleted file mode 100644 index 5fe5089e18..0000000000 --- a/activerecord/test/migrations/duplicate_names/20080507052938_chunky.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Chunky < ActiveRecord::Migration - def self.up - end - - def self.down - end -end diff --git a/activerecord/test/migrations/duplicate_names/20080507053028_chunky.rb b/activerecord/test/migrations/duplicate_names/20080507053028_chunky.rb deleted file mode 100644 index 5fe5089e18..0000000000 --- a/activerecord/test/migrations/duplicate_names/20080507053028_chunky.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Chunky < ActiveRecord::Migration - def self.up - end - - def self.down - end -end diff --git a/activerecord/test/migrations/interleaved/pass_1/3_interleaved_innocent_jointable.rb b/activerecord/test/migrations/interleaved/pass_1/3_interleaved_innocent_jointable.rb deleted file mode 100644 index bf912fbfc8..0000000000 --- a/activerecord/test/migrations/interleaved/pass_1/3_interleaved_innocent_jointable.rb +++ /dev/null @@ -1,12 +0,0 @@ -class InterleavedInnocentJointable < ActiveRecord::Migration - def self.up - create_table("people_reminders", :id => false) do |t| - t.column :reminder_id, :integer - t.column :person_id, :integer - end - end - - def self.down - drop_table "people_reminders" - end -end diff --git a/activerecord/test/migrations/interleaved/pass_2/1_interleaved_people_have_last_names.rb b/activerecord/test/migrations/interleaved/pass_2/1_interleaved_people_have_last_names.rb deleted file mode 100644 index c6c94213a0..0000000000 --- a/activerecord/test/migrations/interleaved/pass_2/1_interleaved_people_have_last_names.rb +++ /dev/null @@ -1,9 +0,0 @@ -class InterleavedPeopleHaveLastNames < ActiveRecord::Migration - def self.up - add_column "people", "last_name", :string - end - - def self.down - remove_column "people", "last_name" - end -end diff --git a/activerecord/test/migrations/interleaved/pass_2/3_interleaved_innocent_jointable.rb b/activerecord/test/migrations/interleaved/pass_2/3_interleaved_innocent_jointable.rb deleted file mode 100644 index bf912fbfc8..0000000000 --- a/activerecord/test/migrations/interleaved/pass_2/3_interleaved_innocent_jointable.rb +++ /dev/null @@ -1,12 +0,0 @@ -class InterleavedInnocentJointable < ActiveRecord::Migration - def self.up - create_table("people_reminders", :id => false) do |t| - t.column :reminder_id, :integer - t.column :person_id, :integer - end - end - - def self.down - drop_table "people_reminders" - end -end diff --git a/activerecord/test/migrations/interleaved/pass_3/1_interleaved_people_have_last_names.rb b/activerecord/test/migrations/interleaved/pass_3/1_interleaved_people_have_last_names.rb deleted file mode 100644 index c6c94213a0..0000000000 --- a/activerecord/test/migrations/interleaved/pass_3/1_interleaved_people_have_last_names.rb +++ /dev/null @@ -1,9 +0,0 @@ -class InterleavedPeopleHaveLastNames < ActiveRecord::Migration - def self.up - add_column "people", "last_name", :string - end - - def self.down - remove_column "people", "last_name" - end -end diff --git a/activerecord/test/migrations/interleaved/pass_3/2_interleaved_i_raise_on_down.rb b/activerecord/test/migrations/interleaved/pass_3/2_interleaved_i_raise_on_down.rb deleted file mode 100644 index 6849995f5e..0000000000 --- a/activerecord/test/migrations/interleaved/pass_3/2_interleaved_i_raise_on_down.rb +++ /dev/null @@ -1,8 +0,0 @@ -class InterleavedIRaiseOnDown < ActiveRecord::Migration - def self.up - end - - def self.down - raise - end -end diff --git a/activerecord/test/migrations/interleaved/pass_3/3_interleaved_innocent_jointable.rb b/activerecord/test/migrations/interleaved/pass_3/3_interleaved_innocent_jointable.rb deleted file mode 100644 index bf912fbfc8..0000000000 --- a/activerecord/test/migrations/interleaved/pass_3/3_interleaved_innocent_jointable.rb +++ /dev/null @@ -1,12 +0,0 @@ -class InterleavedInnocentJointable < ActiveRecord::Migration - def self.up - create_table("people_reminders", :id => false) do |t| - t.column :reminder_id, :integer - t.column :person_id, :integer - end - end - - def self.down - drop_table "people_reminders" - end -end diff --git a/activerecord/test/migrations/rename/1_we_need_things.rb b/activerecord/test/migrations/rename/1_we_need_things.rb new file mode 100644 index 0000000000..cdbe0b1679 --- /dev/null +++ b/activerecord/test/migrations/rename/1_we_need_things.rb @@ -0,0 +1,11 @@ +class WeNeedThings < ActiveRecord::Migration + def self.up + create_table("things") do |t| + t.column :content, :text + end + end + + def self.down + drop_table "things" + end +end
\ No newline at end of file diff --git a/activerecord/test/migrations/rename/2_rename_things.rb b/activerecord/test/migrations/rename/2_rename_things.rb new file mode 100644 index 0000000000..d441b71fc9 --- /dev/null +++ b/activerecord/test/migrations/rename/2_rename_things.rb @@ -0,0 +1,9 @@ +class RenameThings < ActiveRecord::Migration + def self.up + rename_table "things", "awesome_things" + end + + def self.down + rename_table "awesome_things", "things" + end +end
\ No newline at end of file diff --git a/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb new file mode 100644 index 0000000000..e438cf5999 --- /dev/null +++ b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb @@ -0,0 +1,9 @@ +class PeopleHaveLastNames < ActiveRecord::Migration + def self.up + add_column "people", "hobbies", :string + end + + def self.down + remove_column "people", "hobbies" + end +end diff --git a/activerecord/test/migrations/duplicate/1_people_have_last_names.rb b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb index 81af5fef5e..06cb911117 100644 --- a/activerecord/test/migrations/duplicate/1_people_have_last_names.rb +++ b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb @@ -1,4 +1,4 @@ -class PeopleHaveLastNames < ActiveRecord::Migration +class ValidPeopleHaveLastNames < ActiveRecord::Migration def self.up add_column "people", "last_name", :string end @@ -6,4 +6,4 @@ class PeopleHaveLastNames < ActiveRecord::Migration def self.down remove_column "people", "last_name" end -end
\ No newline at end of file +end diff --git a/activerecord/test/migrations/duplicate/2_we_need_reminders.rb b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb index d5e71ce8ef..d5e71ce8ef 100644 --- a/activerecord/test/migrations/duplicate/2_we_need_reminders.rb +++ b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb diff --git a/activerecord/test/migrations/duplicate/3_innocent_jointable.rb b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb index 21c9ca5328..21c9ca5328 100644 --- a/activerecord/test/migrations/duplicate/3_innocent_jointable.rb +++ b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb diff --git a/activerecord/test/models/admin/randomly_named_c1.rb b/activerecord/test/models/admin/randomly_named_c1.rb new file mode 100644 index 0000000000..2f81d5b831 --- /dev/null +++ b/activerecord/test/models/admin/randomly_named_c1.rb @@ -0,0 +1,3 @@ +class Admin::ClassNameThatDoesNotFollowCONVENTIONS < ActiveRecord::Base
+ self.table_name = :randomly_named_table
+end
diff --git a/activerecord/test/models/admin/user.rb b/activerecord/test/models/admin/user.rb index 74bb21551e..d0e628bd50 100644 --- a/activerecord/test/models/admin/user.rb +++ b/activerecord/test/models/admin/user.rb @@ -1,3 +1,5 @@ class Admin::User < ActiveRecord::Base belongs_to :account -end
\ No newline at end of file + store :settings, :accessors => [ :color, :homepage ] + store :preferences, :accessors => [ :remember_login ] +end diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index 23db5650d4..d50e11d6c9 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -49,12 +49,12 @@ class Author < ActiveRecord::Base has_many :sti_post_comments, :through => :sti_posts, :source => :comments has_many :special_nonexistant_posts, :class_name => "SpecialPost", :conditions => "posts.body = 'nonexistant'" - has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => "comments.post_id = 0" + has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => { 'comments.post_id' => 0 } has_many :nonexistant_comments, :through => :posts has_many :hello_posts, :class_name => "Post", :conditions => "posts.body = 'hello'" has_many :hello_post_comments, :through => :hello_posts, :source => :comments - has_many :posts_with_no_comments, :class_name => 'Post', :conditions => 'comments.id is null', :include => :comments + has_many :posts_with_no_comments, :class_name => 'Post', :conditions => { 'comments.id' => nil }, :include => :comments has_many :hello_posts_with_hash_conditions, :class_name => "Post", :conditions => {:body => 'hello'} @@ -128,7 +128,6 @@ class Author < ActiveRecord::Base belongs_to :author_address, :dependent => :destroy belongs_to :author_address_extra, :dependent => :delete, :class_name => "AuthorAddress" - has_many :post_categories, :through => :posts, :source => :categories has_many :category_post_comments, :through => :categories, :source => :post_comments has_many :misc_posts, :class_name => 'Post', diff --git a/activerecord/test/models/bird.rb b/activerecord/test/models/bird.rb index e61d48e6a5..dff099c1fb 100644 --- a/activerecord/test/models/bird.rb +++ b/activerecord/test/models/bird.rb @@ -1,9 +1,12 @@ class Bird < ActiveRecord::Base + belongs_to :pirate validates_presence_of :name + accepts_nested_attributes_for :pirate + attr_accessor :cancel_save_from_callback before_save :cancel_save_callback_method, :if => :cancel_save_from_callback def cancel_save_callback_method false end -end
\ No newline at end of file +end diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb index b9c2e8ec9a..6ff1329d8e 100644 --- a/activerecord/test/models/car.rb +++ b/activerecord/test/models/car.rb @@ -9,7 +9,7 @@ class Car < ActiveRecord::Base has_many :tyres has_many :engines, :dependent => :destroy - has_many :wheels, :as => :wheelable + has_many :wheels, :as => :wheelable, :dependent => :destroy scope :incl_tyres, includes(:tyres) scope :incl_engines, includes(:engines) diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index c1f7a4171a..fbdfaa2c29 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -4,7 +4,7 @@ end class Company < AbstractCompany attr_protected :rating - set_sequence_name :companies_nonstd_seq + self.sequence_name = :companies_nonstd_seq validates_presence_of :name @@ -42,8 +42,10 @@ class Firm < Company :before_remove => :log_before_remove, :after_remove => :log_after_remove has_many :unsorted_clients, :class_name => "Client" + has_many :unsorted_clients_with_symbol, :class_name => :Client has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC" has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id" + has_many :clients_ordered_by_name, :order => "name", :class_name => "Client" has_many :unvalidated_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :validate => false has_many :dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :destroy has_many :exclusively_dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all @@ -87,6 +89,8 @@ class Firm < Company has_many :accounts has_many :unautosaved_accounts, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false + has_many :association_with_references, :class_name => 'Client', :references => :foo + def log @log ||= [] end diff --git a/activerecord/test/models/country.rb b/activerecord/test/models/country.rb index 15e3a1de0b..7db9a4e731 100644 --- a/activerecord/test/models/country.rb +++ b/activerecord/test/models/country.rb @@ -1,6 +1,6 @@ class Country < ActiveRecord::Base - set_primary_key :country_id + self.primary_key = :country_id has_and_belongs_to_many :treaties diff --git a/activerecord/test/models/dashboard.rb b/activerecord/test/models/dashboard.rb index a8a25834b1..1b3b54545f 100644 --- a/activerecord/test/models/dashboard.rb +++ b/activerecord/test/models/dashboard.rb @@ -1,3 +1,3 @@ class Dashboard < ActiveRecord::Base - set_primary_key :dashboard_id -end
\ No newline at end of file + self.primary_key = :dashboard_id +end diff --git a/activerecord/test/models/dog.rb b/activerecord/test/models/dog.rb new file mode 100644 index 0000000000..72b7d33a86 --- /dev/null +++ b/activerecord/test/models/dog.rb @@ -0,0 +1,4 @@ +class Dog < ActiveRecord::Base + belongs_to :breeder, :class_name => "DogLover", :counter_cache => :bred_dogs_count + belongs_to :trainer, :class_name => "DogLover", :counter_cache => :trained_dogs_count +end diff --git a/activerecord/test/models/dog_lover.rb b/activerecord/test/models/dog_lover.rb new file mode 100644 index 0000000000..a33dc575c5 --- /dev/null +++ b/activerecord/test/models/dog_lover.rb @@ -0,0 +1,4 @@ +class DogLover < ActiveRecord::Base + has_many :trained_dogs, :class_name => "Dog", :foreign_key => :trainer_id + has_many :bred_dogs, :class_name => "Dog", :foreign_key => :breeder_id +end diff --git a/activerecord/test/models/joke.rb b/activerecord/test/models/joke.rb index d7f01e59e6..edda4655dc 100644 --- a/activerecord/test/models/joke.rb +++ b/activerecord/test/models/joke.rb @@ -1,7 +1,7 @@ class Joke < ActiveRecord::Base - set_table_name 'funny_jokes' + self.table_name = 'funny_jokes' end class GoodJoke < ActiveRecord::Base - set_table_name 'funny_jokes' + self.table_name = 'funny_jokes' end diff --git a/activerecord/test/models/keyboard.rb b/activerecord/test/models/keyboard.rb index 32a4a7fad0..39347e274e 100644 --- a/activerecord/test/models/keyboard.rb +++ b/activerecord/test/models/keyboard.rb @@ -1,3 +1,3 @@ class Keyboard < ActiveRecord::Base - set_primary_key 'key_number' + self.primary_key = 'key_number' end diff --git a/activerecord/test/models/legacy_thing.rb b/activerecord/test/models/legacy_thing.rb index eaeb642d12..eead181a0e 100644 --- a/activerecord/test/models/legacy_thing.rb +++ b/activerecord/test/models/legacy_thing.rb @@ -1,3 +1,3 @@ class LegacyThing < ActiveRecord::Base - set_locking_column :version + self.locking_column = :version end diff --git a/activerecord/test/models/liquid.rb b/activerecord/test/models/liquid.rb index b96c054f6c..3fcd5e4b69 100644 --- a/activerecord/test/models/liquid.rb +++ b/activerecord/test/models/liquid.rb @@ -1,5 +1,5 @@ class Liquid < ActiveRecord::Base - set_table_name :liquid + self.table_name = :liquid has_many :molecules, :uniq => true end diff --git a/activerecord/test/models/minivan.rb b/activerecord/test/models/minivan.rb index 830cdb5796..4fe79720ad 100644 --- a/activerecord/test/models/minivan.rb +++ b/activerecord/test/models/minivan.rb @@ -1,5 +1,5 @@ class Minivan < ActiveRecord::Base - set_primary_key :minivan_id + self.primary_key = :minivan_id belongs_to :speedometer has_one :dashboard, :through => :speedometer diff --git a/activerecord/test/models/mixed_case_monkey.rb b/activerecord/test/models/mixed_case_monkey.rb index 853f2682b3..763baefd91 100644 --- a/activerecord/test/models/mixed_case_monkey.rb +++ b/activerecord/test/models/mixed_case_monkey.rb @@ -1,3 +1,3 @@ class MixedCaseMonkey < ActiveRecord::Base - set_primary_key 'monkeyID' + self.primary_key = 'monkeyID' end diff --git a/activerecord/test/models/owner.rb b/activerecord/test/models/owner.rb index 5760b991ec..fea55f4535 100644 --- a/activerecord/test/models/owner.rb +++ b/activerecord/test/models/owner.rb @@ -1,5 +1,5 @@ class Owner < ActiveRecord::Base - set_primary_key :owner_id + self.primary_key = :owner_id has_many :pets has_many :toys, :through => :pets end diff --git a/activerecord/test/models/parrot.rb b/activerecord/test/models/parrot.rb index 737ef9131b..c4ee2bd19d 100644 --- a/activerecord/test/models/parrot.rb +++ b/activerecord/test/models/parrot.rb @@ -1,5 +1,6 @@ class Parrot < ActiveRecord::Base - set_inheritance_column :parrot_sti_class + self.inheritance_column = :parrot_sti_class + has_and_belongs_to_many :pirates has_and_belongs_to_many :treasures has_many :loots, :as => :looter diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index 967a3625aa..d2a0c6b40c 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -3,7 +3,8 @@ class Person < ActiveRecord::Base has_one :reader has_many :posts, :through => :readers - has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments, :conditions => 'comments.id is null' + has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments, + :conditions => 'comments.id is null', :references => :comments has_many :references has_many :bad_references @@ -54,7 +55,7 @@ class LoosePerson < ActiveRecord::Base self.table_name = 'people' self.abstract_class = true - attr_protected :comments + attr_protected :comments, :best_friend_id, :best_friend_of_id attr_protected :as => :admin has_one :best_friend, :class_name => 'LoosePerson', :foreign_key => :best_friend_id @@ -81,4 +82,4 @@ class TightPerson < ActiveRecord::Base accepts_nested_attributes_for :best_friend, :best_friend_of, :best_friends end -class TightDescendant < TightPerson; end
\ No newline at end of file +class TightDescendant < TightPerson; end diff --git a/activerecord/test/models/pet.rb b/activerecord/test/models/pet.rb index 113826756a..3cd5bceed5 100644 --- a/activerecord/test/models/pet.rb +++ b/activerecord/test/models/pet.rb @@ -2,7 +2,7 @@ class Pet < ActiveRecord::Base attr_accessor :current_user - set_primary_key :pet_id + self.primary_key = :pet_id belongs_to :owner, :touch => true has_many :toys diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 198a963cbc..1cab78d8c7 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -24,6 +24,10 @@ class Post < ActiveRecord::Base belongs_to :author_with_posts, :class_name => "Author", :foreign_key => :author_id, :include => :posts belongs_to :author_with_address, :class_name => "Author", :foreign_key => :author_id, :include => :author_address + def first_comment + super.body + end + has_one :first_comment, :class_name => 'Comment', :order => 'id ASC' has_one :last_comment, :class_name => 'Comment', :order => 'id desc' scope :with_special_comments, :joins => :comments, :conditions => {:comments => {:type => 'SpecialComment'} } @@ -40,6 +44,10 @@ class Post < ActiveRecord::Base def newest created.last end + + def the_association + proxy_association + end end has_many :author_favorites, :through => :author @@ -181,4 +189,4 @@ end class SpecialPostWithDefaultScope < ActiveRecord::Base self.table_name = 'posts' default_scope where(:id => [1, 5,6]) -end
\ No newline at end of file +end diff --git a/activerecord/test/models/randomly_named_c1.rb b/activerecord/test/models/randomly_named_c1.rb new file mode 100644 index 0000000000..18a86c4989 --- /dev/null +++ b/activerecord/test/models/randomly_named_c1.rb @@ -0,0 +1,3 @@ +class ClassNameThatDoesNotFollowCONVENTIONS < ActiveRecord::Base
+ self.table_name = :randomly_named_table
+end
diff --git a/activerecord/test/models/speedometer.rb b/activerecord/test/models/speedometer.rb index 94743eff8e..0a7d38d8ec 100644 --- a/activerecord/test/models/speedometer.rb +++ b/activerecord/test/models/speedometer.rb @@ -1,4 +1,4 @@ class Speedometer < ActiveRecord::Base - set_primary_key :speedometer_id + self.primary_key = :speedometer_id belongs_to :dashboard -end
\ No newline at end of file +end diff --git a/activerecord/test/models/string_key_object.rb b/activerecord/test/models/string_key_object.rb index f8d4c6e0e4..f084ec1bdc 100644 --- a/activerecord/test/models/string_key_object.rb +++ b/activerecord/test/models/string_key_object.rb @@ -1,3 +1,3 @@ class StringKeyObject < ActiveRecord::Base - set_primary_key :id + self.primary_key = :id end diff --git a/activerecord/test/models/subscriber.rb b/activerecord/test/models/subscriber.rb index 5b78014e6f..76e85a0cd3 100644 --- a/activerecord/test/models/subscriber.rb +++ b/activerecord/test/models/subscriber.rb @@ -1,5 +1,5 @@ class Subscriber < ActiveRecord::Base - set_primary_key 'nick' + self.primary_key = 'nick' has_many :subscriptions has_many :books, :through => :subscriptions end diff --git a/activerecord/test/models/teapot.rb b/activerecord/test/models/teapot.rb new file mode 100644 index 0000000000..b035b18c1b --- /dev/null +++ b/activerecord/test/models/teapot.rb @@ -0,0 +1,35 @@ +class Teapot + # I'm a little teapot, + # Short and stout, + # Here is my handle + # Here is my spout + # When I get all steamed up, + # Hear me shout, + # Tip me over and pour me out! + # + # HELL YEAH TEAPOT SONG + + include ActiveRecord::Model +end + +class OtherTeapot < Teapot +end + +class OMFGIMATEAPOT + def aaahhh + "mmm" + end +end + +class CoolTeapot < OMFGIMATEAPOT + include ActiveRecord::Model + self.table_name = "teapots" +end + +class Ceiling + include ActiveRecord::Model + + class Teapot + include ActiveRecord::Model + end +end diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index fe424e61b2..8bcb9df8a8 100644 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -8,6 +8,8 @@ class Topic < ActiveRecord::Base scope :approved, :conditions => {:approved => true} scope :rejected, :conditions => {:approved => false} + scope :scope_with_lambda, lambda { scoped } + scope :by_lifo, :conditions => {:author_name => 'lifo'} scope :approved_as_hash_condition, :conditions => {:topics => {:approved => true}} @@ -78,6 +80,11 @@ class Topic < ActiveRecord::Base after_initialize :set_email_address + class_attribute :after_initialize_called + after_initialize do + self.class.after_initialize_called = true + end + def approved=(val) @custom_approved = val write_attribute(:approved, val) @@ -106,6 +113,10 @@ class Topic < ActiveRecord::Base def after_create_for_transaction; end end +class ImportantTopic < Topic + serialize :important, Hash +end + module Web class Topic < ActiveRecord::Base has_many :replies, :dependent => :destroy, :foreign_key => "parent_id", :class_name => 'Web::Reply' diff --git a/activerecord/test/models/toy.rb b/activerecord/test/models/toy.rb index 6c45e99671..0377e50011 100644 --- a/activerecord/test/models/toy.rb +++ b/activerecord/test/models/toy.rb @@ -1,5 +1,5 @@ class Toy < ActiveRecord::Base - set_primary_key :toy_id + self.primary_key = :toy_id belongs_to :pet scope :with_pet, joins(:pet) diff --git a/activerecord/test/models/treaty.rb b/activerecord/test/models/treaty.rb index b46537f0d2..41fd1350f3 100644 --- a/activerecord/test/models/treaty.rb +++ b/activerecord/test/models/treaty.rb @@ -1,6 +1,6 @@ class Treaty < ActiveRecord::Base - set_primary_key :treaty_id + self.primary_key = :treaty_id has_and_belongs_to_many :countries diff --git a/activerecord/test/models/warehouse_thing.rb b/activerecord/test/models/warehouse_thing.rb index 6ace1183cc..f20bd1a245 100644 --- a/activerecord/test/models/warehouse_thing.rb +++ b/activerecord/test/models/warehouse_thing.rb @@ -1,5 +1,5 @@ class WarehouseThing < ActiveRecord::Base - set_table_name "warehouse-things" + self.table_name = "warehouse-things" validates_uniqueness_of :value -end
\ No newline at end of file +end diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb index c78d99f4af..ab2c7ccc10 100644 --- a/activerecord/test/schema/mysql2_specific_schema.rb +++ b/activerecord/test/schema/mysql2_specific_schema.rb @@ -21,4 +21,15 @@ BEGIN END SQL -end + ActiveRecord::Base.connection.execute <<-SQL +DROP TABLE IF EXISTS collation_tests; +SQL + + ActiveRecord::Base.connection.execute <<-SQL +CREATE TABLE collation_tests ( + string_cs_column VARCHAR(1) COLLATE utf8_bin, + string_ci_column VARCHAR(1) COLLATE utf8_general_ci +) CHARACTER SET utf8 COLLATE utf8_general_ci +SQL + +end
\ No newline at end of file diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb index 30e1c5a167..a0adfe3752 100644 --- a/activerecord/test/schema/mysql_specific_schema.rb +++ b/activerecord/test/schema/mysql_specific_schema.rb @@ -32,4 +32,15 @@ BEGIN END SQL + ActiveRecord::Base.connection.execute <<-SQL +DROP TABLE IF EXISTS collation_tests; +SQL + + ActiveRecord::Base.connection.execute <<-SQL +CREATE TABLE collation_tests ( + string_cs_column VARCHAR(1) COLLATE utf8_bin, + string_ci_column VARCHAR(1) COLLATE utf8_general_ci +) CHARACTER SET utf8 COLLATE utf8_general_ci +SQL + end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 9d5ad16a3c..da0c4cecdd 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -37,6 +37,8 @@ ActiveRecord::Schema.define do create_table :admin_users, :force => true do |t| t.string :name + t.text :settings, :null => true + t.text :preferences, :null => false, :default => "" t.references :account end @@ -106,6 +108,7 @@ ActiveRecord::Schema.define do t.string :name t.integer :engines_count t.integer :wheels_count + t.column :lock_version, :integer, :null => false, :default => 0 end create_table :categories, :force => true do |t| @@ -211,6 +214,16 @@ ActiveRecord::Schema.define do t.integer :access_level, :default => 1 end + create_table :dog_lovers, :force => true do |t| + t.integer :trained_dogs_count, :default => 0 + t.integer :bred_dogs_count, :default => 0 + end + + create_table :dogs, :force => true do |t| + t.integer :trainer_id + t.integer :breeder_id + end + create_table :edges, :force => true, :id => false do |t| t.column :source_id, :integer, :null => false t.column :sink_id, :integer, :null => false @@ -504,6 +517,11 @@ ActiveRecord::Schema.define do t.string :type end + create_table :randomly_named_table, :force => true do |t| + t.string :some_attribute + t.integer :another_attribute + end + create_table :ratings, :force => true do |t| t.integer :comment_id t.integer :value @@ -595,6 +613,12 @@ ActiveRecord::Schema.define do t.datetime :ending end + create_table :teapots, :force => true do |t| + t.string :name + t.string :type + t.timestamps + end + create_table :topics, :force => true do |t| t.string :title t.string :author_name @@ -606,8 +630,10 @@ ActiveRecord::Schema.define do # Oracle SELECT WHERE clause which causes many unit test failures if current_adapter?(:OracleAdapter) t.string :content, :limit => 4000 + t.string :important, :limit => 4000 else t.text :content + t.text :important end t.boolean :approved, :default => true t.integer :replies_count, :default => 0 @@ -699,8 +725,6 @@ ActiveRecord::Schema.define do create_table :countries_treaties, :force => true, :id => false do |t| t.string :country_id, :null => false t.string :treaty_id, :null => false - t.datetime :created_at - t.datetime :updated_at end create_table :liquid, :force => true do |t| diff --git a/activerecord/test/support/connection.rb b/activerecord/test/support/connection.rb index a39794fa39..60fea46fd3 100644 --- a/activerecord/test/support/connection.rb +++ b/activerecord/test/support/connection.rb @@ -1,4 +1,4 @@ -require 'logger' +require 'active_support/logger' require_dependency 'models/course' module ARTest @@ -12,9 +12,9 @@ module ARTest def self.connect puts "Using #{connection_name} with Identity Map #{ActiveRecord::IdentityMap.enabled? ? 'on' : 'off'}" - ActiveRecord::Base.logger = Logger.new("debug.log") - ActiveRecord::Base.configurations = connection_config - ActiveRecord::Base.establish_connection 'arunit' + ActiveRecord::Model.logger = ActiveSupport::Logger.new("debug.log") + ActiveRecord::Model.configurations = connection_config + ActiveRecord::Model.establish_connection 'arunit' Course.establish_connection 'arunit2' end end |