diff options
Diffstat (limited to 'activerecord/CHANGELOG.md')
-rw-r--r-- | activerecord/CHANGELOG.md | 2118 |
1 files changed, 459 insertions, 1659 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index d59101d621..d73d9ade41 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,1995 +1,795 @@ -* Delegate `empty?`, `none?` and `one?`. Now they can be invoked as model class methods. +* Assign all attributes before calling `build` to ensure the child record is visible in + `before_add` and `after_add` callbacks for `has_many :through` associations. - Example: + Fixes #33249. - # When no record is found on the table - Topic.empty? # => true - Topic.none? # => true + *Ryan H. Kerr* - # When only one record is found on the table - Topic.one? # => true +* Add `ActiveRecord::Relation#extract_associated` for extracting associated records from a relation. - *Kenta Shirai* + ``` + account.memberships.extract_associated(:user) + # => Returns collection of User records + ``` -* The form builder now properly displays values when passing a proc form - default to the attributes API. + *DHH* - Fixes #24249. +* Add `ActiveRecord::Relation#annotate` for adding SQL comments to its queries. - *Sean Griffin* + For example: -* The schema cache is now cleared after the `db:migrate` task is run. + ``` + Post.where(id: 123).annotate("this is a comment").to_sql + # SELECT "posts".* FROM "posts" WHERE "posts"."id" = 123 /* this is a comment */ + ``` - Closes #24273. + This can be useful in instrumentation or other analysis of issued queries. - *Chris Arcand* + *Matt Yoho* -* MySQL: strict mode respects other SQL modes rather than overwriting them. - Setting `strict: true` adds `STRICT_ALL_TABLES` to `sql_mode`. Setting - `strict: false` removes `STRICT_TRANS_TABLES`, `STRICT_ALL_TABLES`, and - `TRADITIONAL` from `sql_mode`. +* Support Optimizer Hints. - *Ryuta Kamizono* + In most databases, a way to control the optimizer is by using optimizer hints, + which can be specified within individual statements. -* Execute default_scope defined by abstract class in the context of subclass. + Example (for MySQL): - Fixes #23413. - Fixes #10658. - - *Mehmet Emin İNAÇ* + Topic.optimizer_hints("MAX_EXECUTION_TIME(50000)", "NO_INDEX_MERGE(topics)") + # SELECT /*+ MAX_EXECUTION_TIME(50000) NO_INDEX_MERGE(topics) */ `topics`.* FROM `topics` -* Fix an issue when preloading associations with extensions. - Previously every association with extension methods was transformed into an - instance dependent scope. This is no longer the case. + Example (for PostgreSQL with pg_hint_plan): - Fixes #23934. + Topic.optimizer_hints("SeqScan(topics)", "Parallel(topics 8)") + # SELECT /*+ SeqScan(topics) Parallel(topics 8) */ "topics".* FROM "topics" - *Yves Senn* + See also: -* Deprecate `{insert|update|delete}_sql` in `DatabaseStatements`. - Use the `{insert|update|delete}` public methods instead. + * https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html + * https://pghintplan.osdn.jp/pg_hint_plan.html + * https://docs.oracle.com/en/database/oracle/oracle-database/12.2/tgsql/influencing-the-optimizer.html + * https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query?view=sql-server-2017 + * https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.perf.doc/doc/c0070117.html *Ryuta Kamizono* -* Added a configuration option to have active record raise an ArgumentError - if the order or limit is ignored in a batch query, rather than logging a - warning message. - - *Scott Ringwelski* - -* Honour the order of the joining model in a `has_many :through` association when eager loading. - - Example: - - The below will now follow the order of `by_lines` when eager loading `authors`. +* Fix query attribute method on user-defined attribute to be aware of typecasted value. - class Article < ActiveRecord::Base - has_many :by_lines, -> { order(:position) } - has_many :authors, through: :by_lines - end - - Fixes #17864. - - *Yasyf Mohamedali*, *Joel Turkel* - -* Ensure that the Suppressor runs before validations. - - This moves the suppressor up to be run before validations rather than after - validations. There's no reason to validate a record you aren't planning on saving. + For example, the following code no longer return false as casted non-empty string: - *Eileen M. Uchitelle* - -## Rails 5.0.0.beta3 (February 24, 2016) ## - -* Save many-to-many objects based on association primary key. + ``` + class Post < ActiveRecord::Base + attribute :user_defined_text, :text + end - Fixes #20995. + Post.new(user_defined_text: "false").user_defined_text? # => true + ``` - *himesh-r* + *Yuji Kamijima* -* Ensure that mutations of the array returned from `ActiveRecord::Relation#to_a` - do not affect the original relation, by returning a duplicate array each time. +* Quote empty ranges like other empty enumerables. - This brings the behavior in line with `CollectionProxy#to_a`, which was - already more careful. + *Patrick Rebsch* - *Matthew Draper* +* Add `insert_all`/`insert_all!`/`upsert_all` methods to `ActiveRecord::Persistence`, + allowing bulk inserts akin to the bulk updates provided by `update_all` and + bulk deletes by `delete_all`. -* Fixed `where` for polymorphic associations when passed an array containing different types. + Supports skipping or upserting duplicates through the `ON CONFLICT` syntax + for Postgres (9.5+) and Sqlite (3.24+) and `ON DUPLICATE KEY UPDATE` syntax + for MySQL. - Fixes #17011. - - Example: + *Bob Lail* - PriceEstimate.where(estimate_of: [Treasure.find(1), Car.find(2)]) - # => SELECT "price_estimates".* FROM "price_estimates" - WHERE (("price_estimates"."estimate_of_type" = 'Treasure' AND "price_estimates"."estimate_of_id" = 1) - OR ("price_estimates"."estimate_of_type" = 'Car' AND "price_estimates"."estimate_of_id" = 2)) +* Add `rails db:seed:replant` that truncates tables of each database + for current environment and loads the seeds. - *Philippe Huibonhoa* + *bogdanvlviv*, *DHH* -* Fix a bug where using `t.foreign_key` twice with the same `to_table` within - the same table definition would only create one foreign key. +* Add `ActiveRecord::Base.connection.truncate` for SQLite3 adapter. - *George Millo* + *bogdanvlviv* -* Fix a regression on has many association, where calling a child from parent in child's callback - results in same child records getting added repeatedly to target. +* Deprecate mismatched collation comparison for uniqueness validator. - Fixes #13387. + Uniqueness validator will no longer enforce case sensitive comparison in Rails 6.1. + To continue case sensitive comparison on the case insensitive column, + pass `case_sensitive: true` option explicitly to the uniqueness validator. - *Bogdan Gusiev*, *Jon Hinson* - -* Rework `ActiveRecord::Relation#last`. - - 1. Never perform additional SQL on loaded relation - 2. Use SQL reverse order instead of loading relation if relation doesn't have limit - 3. Deprecated relation loading when SQL order can not be automatically reversed - - Topic.order("title").load.last(3) - # before: SELECT ... - # after: No SQL - - Topic.order("title").last - # before: SELECT * FROM `topics` - # after: SELECT * FROM `topics` ORDER BY `topics`.`title` DESC LIMIT 1 - - Topic.order("coalesce(author, title)").last - # before: SELECT * FROM `topics` - # after: Deprecation Warning for irreversible order - - *Bogdan Gusiev* - -* Allow `joins` to be unscoped. - - Fixes #13775. + *Ryuta Kamizono* - *Takashi Kokubun* +* Add `reselect` method. This is a short-hand for `unscope(:select).select(fields)`. -* Add ActiveRecord `#second_to_last` and `#third_to_last` methods. + Fixes #27340. - *Brian Christian* + *Willian Gustavo Veiga* -* Added `numeric` helper into migrations. +* Add negative scopes for all enum values. Example: - create_table(:numeric_types) do |t| - t.numeric :numeric_type, precision: 10, scale: 2 + class Post < ActiveRecord::Base + enum status: %i[ drafted active trashed ] end - *Mehmet Emin İNAÇ* - -* Bumped the minimum supported version of PostgreSQL to >= 9.1. - Both PG 9.0 and 8.4 are past their end of life date: - http://www.postgresql.org/support/versioning/ - - *Remo Mueller* + Post.not_drafted # => where.not(status: :drafted) + Post.not_active # => where.not(status: :active) + Post.not_trashed # => where.not(status: :trashed) -## Rails 5.0.0.beta2 (February 01, 2016) ## + *DHH* -* `ActiveRecord::Relation#reverse_order` throws `ActiveRecord::IrreversibleOrderError` - when the order can not be reversed using current trivial algorithm. - Also raises the same error when `#reverse_order` is called on - relation without any order and table has no primary key: +* Fix different `count` calculation when using `size` with manual `select` with DISTINCT. - Topic.order("concat(author_name, title)").reverse_order - # Before: SELECT `topics`.* FROM `topics` ORDER BY concat(author_name DESC, title) DESC - # After: raises ActiveRecord::IrreversibleOrderError - Edge.all.reverse_order - # Before: SELECT `edges`.* FROM `edges` ORDER BY `edges`.`` DESC - # After: raises ActiveRecord::IrreversibleOrderError - - *Bogdan Gusiev* + Fixes #35214. -* Improve schema_migrations insertion performance by inserting all versions - in one INSERT SQL. + *Juani Villarejo* - *Akira Matsuda*, *Naoto Koshikawa* -* Using `references` or `belongs_to` in migrations will always add index - for the referenced column by default, without adding `index: true` option - to generated migration file. Users can opt out of this by passing - `index: false`. +## Rails 6.0.0.beta3 (March 11, 2019) ## - Fixes #18146. +* No changes. - *Matthew Draper*, *Prathamesh Sonpatki* -* Run `type` attributes through attributes API type-casting before - instantiating the corresponding subclass. This makes it possible to define - custom STI mappings. +## Rails 6.0.0.beta2 (February 25, 2019) ## - Fixes #21986. - - *Yves Senn* - -* Don't try to quote functions or expressions passed to `:default` option if - they are passed as procs. - - This will generate proper query with the passed function or expression for - the default option, instead of trying to quote it in incorrect fashion. - - Example: - - create_table :posts do |t| - t.datetime :published_at, default: -> { 'NOW()' } - end +* Fix prepared statements caching to be enabled even when query caching is enabled. *Ryuta Kamizono* -* Fix regression when loading fixture files with symbol keys. - - Fixes #22584. - - *Yves Senn* - -* Use `version` column as primary key for schema_migrations table because - `schema_migrations` versions are guaranteed to be unique. - - This makes it possible to use `update_attributes` on models that do - not have a primary key. - - *Richard Schneeman* - -* Add short-hand methods for text and blob types in MySQL. - - In Pg and Sqlite3, `:text` and `:binary` have variable unlimited length. - But in MySQL, these have limited length for each types (ref #21591, #21619). - This change adds short-hand methods for each text and blob types. - - Example: - - create_table :foos do |t| - t.tinyblob :tiny_blob - t.mediumblob :medium_blob - t.longblob :long_blob - t.tinytext :tiny_text - t.mediumtext :medium_text - t.longtext :long_text - end +* Ensure `update_all` series cares about optimistic locking. *Ryuta Kamizono* -* Take into account UTC offset when assigning string representation of - timestamp with offset specified to attribute of time type. - - *Andrey Novikov* - -* When calling `first` with a `limit` argument, return directly from the - `loaded?` records if available. - - *Ben Woosley* - -* Deprecate sending the `offset` argument to `find_nth`. Please use the - `offset` method on relation instead. - - *Ben Woosley* - -## Rails 5.0.0.beta1 (December 18, 2015) ## - -* Limit record touching to once per transaction. - - If you have a parent/grand-parent relation like: - - Comment belongs_to :message, touch: true - Message belongs_to :project, touch: true - Project belongs_to :account, touch: true - - When the lowest entry(`Comment`) is saved, now, it won't repeat the touch - call multiple times for the parent records. - - Related #18606. - - *arthurnn* - -* Order the result of `find(ids)` to match the passed array, if the relation - has no explicit order defined. - - Fixes #20338. - - *Miguel Grazziotin*, *Matthew Draper* - -* Omit default limit values in dumped schema. It's tidier, and if the defaults - change in the future, we can address that via Migration API Versioning. - - *Jean Boussier* - -* Support passing the schema name as a prefix to table name in - `ConnectionAdapters::SchemaStatements#indexes`. Previously the prefix would - be considered a full part of the index name, and only the schema in the - current search path would be considered. - - *Grey Baker* - -* Ignore index name in `index_exists?` and `remove_index` when not passed a - name to check for. - - *Grey Baker* - -* Extract support for the legacy `mysql` database adapter from core. It will - live on in a separate gem for now, but most users should just use `mysql2`. - - *Abdelkader Boudih* - -* ApplicationRecord is a new superclass for all app models, analogous to app - controllers subclassing ApplicationController instead of - ActionController::Base. This gives apps a single spot to configure app-wide - model behavior. +* Don't allow `where` with non numeric string matches to 0 values. - Newly generated applications have `app/models/application_record.rb` - present by default. - - *Genadi Samokovarov* - -* Version the API presented to migration classes, so we can change parameter - defaults without breaking existing migrations, or forcing them to be - rewritten through a deprecation cycle. - - New migrations specify the Rails version they were written for: - - class AddStatusToOrders < ActiveRecord::Migration[5.0] - def change - # ... - end - end - - *Matthew Draper*, *Ravil Bayramgalin* - -* Use bind params for `limit` and `offset`. This will generate significantly - fewer prepared statements for common tasks like pagination. To support this - change, passing a string containing a comma to `limit` has been deprecated, - and passing an Arel node to `limit` is no longer supported. - - Fixes #22250. - - *Sean Griffin* - -* Introduce after_{create,update,delete}_commit callbacks. - - Before: - - after_commit :add_to_index_later, on: :create - after_commit :update_in_index_later, on: :update - after_commit :remove_from_index_later, on: :destroy + *Ryuta Kamizono* - After: +* Introduce `ActiveRecord::Relation#destroy_by` and `ActiveRecord::Relation#delete_by`. - after_create_commit :add_to_index_later - after_update_commit :update_in_index_later - after_destroy_commit :remove_from_index_later + `destroy_by` allows relation to find all the records matching the condition and perform + `destroy_all` on the matched records. - Fixes #22515. + Example: - *Genadi Samokovarov* + Person.destroy_by(name: 'David') + Person.destroy_by(name: 'David', rating: 4) -* Respect the column default values for `inheritance_column` when - instantiating records through the base class. + david = Person.find_by(name: 'David') + david.posts.destroy_by(id: [1, 2, 3]) - Fixes #17121. + `delete_by` allows relation to find all the records matching the condition and perform + `delete_all` on the matched records. Example: - # The schema of BaseModel has `t.string :type, default: 'SubType'` - subtype = BaseModel.new - assert_equals SubType, subtype.class + Person.delete_by(name: 'David') + Person.delete_by(name: 'David', rating: 4) - *Kuldeep Aggarwal* + david = Person.find_by(name: 'David') + david.posts.delete_by(id: [1, 2, 3]) -* Fix `rake db:structure:dump` on Postgres when multiple schemas are used. + *Abhay Nikam* - Fixes #22346. +* Don't allow `where` with invalid value matches to nil values. - *Nick Muerdter*, *ckoenig* - -* Add schema dumping support for PostgreSQL geometric data types. + Fixes #33624. *Ryuta Kamizono* -* Except keys of `build_record`'s argument from `create_scope` in `initialize_attributes`. - - Fixes #21893. - - *Yuichiro Kaneko* - -* Deprecate `connection.tables` on the SQLite3 and MySQL adapters. - Also deprecate passing arguments to `#tables`. - And deprecate `table_exists?`. - - The `#tables` method of some adapters (mysql, mysql2, sqlite3) would return - both tables and views while others (postgresql) just return tables. To make - their behavior consistent, `#tables` will return only tables in the future. - - The `#table_exists?` method would check both tables and views. To make - their behavior consistent with `#tables`, `#table_exists?` will check only - tables in the future. - - *Yuichiro Kaneko* - -* Improve support for non Active Record objects on `validates_associated` - - Skipping `marked_for_destruction?` when the associated object does not responds - to it make easier to validate virtual associations built on top of Active Model - objects and/or serialized objects that implement a `valid?` instance method. - - *Kassio Borges*, *Lucas Mazza* - -* Change connection management middleware to return a new response with - a body proxy, rather than mutating the original. - - *Kevin Buchanan* - -* Make `db:migrate:status` to render `1_some.rb` format migrate files. - - These files are in `db/migrate`: - - * 1_valid_people_have_last_names.rb - * 20150819202140_irreversible_migration.rb - * 20150823202140_add_admin_flag_to_users.rb - * 20150823202141_migration_tests.rb - * 2_we_need_reminders.rb - * 3_innocent_jointable.rb - - Before: - - $ bundle exec rake db:migrate:status - ... - - Status Migration ID Migration Name - -------------------------------------------------- - up 001 ********** NO FILE ********** - up 002 ********** NO FILE ********** - up 003 ********** NO FILE ********** - up 20150819202140 Irreversible migration - up 20150823202140 Add admin flag to users - up 20150823202141 Migration tests - - After: - - $ bundle exec rake db:migrate:status - ... - - Status Migration ID Migration Name - -------------------------------------------------- - up 001 Valid people have last names - up 002 We need reminders - up 003 Innocent jointable - up 20150819202140 Irreversible migration - up 20150823202140 Add admin flag to users - up 20150823202141 Migration tests - - *Yuichiro Kaneko* - -* Define `ActiveRecord::Sanitization.sanitize_sql_for_order` and use it inside - `preprocess_order_args`. - - *Yuichiro Kaneko* - -* Allow bigint with default nil for avoiding auto increment primary key. +* SQLite3: Implement `add_foreign_key` and `remove_foreign_key`. *Ryuta Kamizono* -* Remove `DEFAULT_CHARSET` and `DEFAULT_COLLATION` in `MySQLDatabaseTasks`. - - We should omit the collation entirely rather than providing a default. - Then the choice is the responsibility of the server and MySQL distribution. +* Deprecate using class level querying methods if the receiver scope + regarded as leaked. Use `klass.unscoped` to avoid the leaking scope. *Ryuta Kamizono* -* Alias `ActiveRecord::Relation#left_joins` to - `ActiveRecord::Relation#left_outer_joins`. - - *Takashi Kokubun* - -* Use advisory locking to raise a `ConcurrentMigrationError` instead of - attempting to migrate when another migration is currently running. - - *Sam Davies* - -* Added `ActiveRecord::Relation#left_outer_joins`. - - Example: - - User.left_outer_joins(:posts) - # => SELECT "users".* FROM "users" LEFT OUTER JOIN "posts" ON - "posts"."user_id" = "users"."id" - - *Florian Thomas* - -* Support passing an array to `order` for SQL parameter sanitization. - - *Aaron Suggs* - -* Avoid disabling errors on the PostgreSQL connection when enabling the - `standard_conforming_strings` setting. Errors were previously disabled because - the setting wasn't writable in Postgres 8.1 and didn't exist in earlier - versions. Now Rails only supports Postgres 8.2+ we're fine to assume the - setting exists. Disabling errors caused problems when using a connection - pooling tool like PgBouncer because it's not guaranteed to have the same - connection between calls to `execute` and it could leave the connection - with errors disabled. - - Fixes #22101. - - *Harry Marr* - -* Set `scope.reordering_value` to `true` if `:reordering`-values are specified. - - Fixes #21886. - - *Hiroaki Izu* - -* Add support for bidirectional destroy dependencies. +* Allow applications to automatically switch connections. - Fixes #13609. + Adds a middleware and configuration options that can be used in your + application to automatically switch between the writing and reading + database connections. - Example: - - class Content < ActiveRecord::Base - has_one :position, dependent: :destroy - end - - class Position < ActiveRecord::Base - belongs_to :content, dependent: :destroy - end - - *Seb Jacobs* - -* Includes HABTM returns correct size now. It's caused by the join dependency - only instantiates one HABTM object because the join table hasn't a primary key. - - Fixes #16032. - - Examples: - - before: + `GET` and `HEAD` requests will read from the replica unless there was + a write in the last 2 seconds, otherwise they will read from the primary. + Non-get requests will always write to the primary. The middleware accepts + an argument for a Resolver class and a Operations class where you are able + to change how the auto-switcher works to be most beneficial for your + application. - Project.first.salaried_developers.size # => 3 - Project.includes(:salaried_developers).first.salaried_developers.size # => 1 + To use the middleware in your application you can use the following + configuration options: - after: + ``` + config.active_record.database_selector = { delay: 2.seconds } + config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver + config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session + ``` - Project.first.salaried_developers.size # => 3 - Project.includes(:salaried_developers).first.salaried_developers.size # => 3 + To change the database selection strategy, pass a custom class to the + configuration options: - *Bigxiang* + ``` + config.active_record.database_selector = { delay: 10.seconds } + config.active_record.database_resolver = MyResolver + config.active_record.database_resolver_context = MyResolver::MyCookies + ``` -* Add option to index errors in nested attributes - - For models which have nested attributes, errors within those models will - now be indexed if `:index_errors` is specified when defining a - has_many relationship, or if its set in the global config. - - Example: - - class Guitar < ActiveRecord::Base - has_many :tuning_pegs, index_errors: true - accepts_nested_attributes_for :tuning_pegs - end - - class TuningPeg < ActiveRecord::Base - belongs_to :guitar - validates_numericality_of :pitch - end - - # Old style - guitar.errors["tuning_pegs.pitch"] = ["is not a number"] + *Eileen M. Uchitelle* - # New style (if defined globally, or set in has_many_relationship) - guitar.errors["tuning_pegs[1].pitch"] = ["is not a number"] +* MySQL: Support `:size` option to change text and blob size. - *Michael Probber*, *Terence Sun* + *Ryuta Kamizono* -* Exit with non-zero status for failed database rake tasks. +* Make `t.timestamps` with precision by default. - *Jay Hayes* + *Ryuta Kamizono* -* Queries such as `Computer.joins(:monitor).group(:status).count` will now be - interpreted as `Computer.joins(:monitor).group('computers.status').count` - so that when `Computer` and `Monitor` have both `status` columns we don't - have conflicts in projection. - *Rafael Sales* +## Rails 6.0.0.beta1 (January 18, 2019) ## -* Add ability to default to `uuid` as primary key when generating database migrations. +* Remove deprecated `#set_state` from the transaction object. - Example: + *Rafael Mendonça França* - config.generators do |g| - g.orm :active_record, primary_key_type: :uuid - end +* Remove deprecated `#supports_statement_cache?` from the database adapters. - *Jon McCartie* + *Rafael Mendonça França* -* Don't cache arguments in `#find_by` if they are an `ActiveRecord::Relation`. +* Remove deprecated `#insert_fixtures` from the database adapters. - Fixes #20817. + *Rafael Mendonça França* - *Hiroaki Izu* +* Remove deprecated `ActiveRecord::ConnectionAdapters::SQLite3Adapter#valid_alter_table_type?`. -* Qualify column name inserted by `group` in calculation. + *Rafael Mendonça França* - Giving `group` an unqualified column name now works, even if the relation - has `JOIN` with another table which also has a column of the name. +* Do not allow passing the column name to `sum` when a block is passed. - *Soutaro Matsumoto* + *Rafael Mendonça França* -* Don't cache prepared statements containing an IN clause or a SQL literal, as - these queries will change often and are unlikely to have a cache hit. +* Do not allow passing the column name to `count` when a block is passed. - *Sean Griffin* + *Rafael Mendonça França* -* Fix `rewhere` in a `has_many` association. +* Remove delegation of missing methods in a relation to arel. - Fixes #21955. + *Rafael Mendonça França* - *Josh Branchaud*, *Kal* +* Remove delegation of missing methods in a relation to private methods of the class. -* `where` raises ArgumentError on unsupported types. + *Rafael Mendonça França* - Fixes #20473. +* Deprecate `config.activerecord.sqlite3.represent_boolean_as_integer`. - *Jake Worth* + *Rafael Mendonça França* -* Add an immutable string type to help reduce memory usage for apps which do - not need mutation detection on strings. +* Change `SQLite3Adapter` to always represent boolean values as integers. - *Sean Griffin* + *Rafael Mendonça França* -* Give `ActiveRecord::Relation#update` its own deprecation warning when - passed an `ActiveRecord::Base` instance. +* Remove ability to specify a timestamp name for `#cache_key`. - Fixes #21945. + *Rafael Mendonça França* - *Ted Johansson* +* Remove deprecated `ActiveRecord::Migrator.migrations_path=`. -* Make it possible to pass `:to_table` when adding a foreign key through - `add_reference`. + *Rafael Mendonça França* - Fixes #21563. +* Remove deprecated `expand_hash_conditions_for_aggregates`. - *Yves Senn* + *Rafael Mendonça França* -* No longer pass deprecated option `-i` to `pg_dump`. +* Set polymorphic type column to NULL on `dependent: :nullify` strategy. - *Paul Sadauskas* + On polymorphic associations both the foreign key and the foreign type columns will be set to NULL. -* Concurrent `AR::Base#increment!` and `#decrement!` on the same record - are all reflected in the database rather than overwriting each other. + *Laerti Papa* - *Bogdan Gusiev* +* Allow permitted instance of `ActionController::Parameters` as argument of `ActiveRecord::Relation#exists?`. -* Avoid leaking the first relation we call `first` on, per model. + *Gannon McGibbon* - Fixes #21921. +* Add support for endless ranges introduces in Ruby 2.6. - *Matthew Draper*, *Jean Boussier* + *Greg Navis* -* Remove unused `pk_and_sequence_for` in `AbstractMysqlAdapter`. +* Deprecate passing `migrations_paths` to `connection.assume_migrated_upto_version`. *Ryuta Kamizono* -* Allow fixtures files to set the model class in the YAML file itself. - - To load the fixtures file `accounts.yml` as the `User` model, use: - - _fixture: - model_class: User - david: - name: David - - Fixes #9516. - - *Roque Pinel* - -* Don't require a database connection to load a class which uses acceptance - validations. - - *Sean Griffin* - -* Correctly apply `unscope` when preloading through associations. - - *Jimmy Bourassa* - -* Fixed taking precision into count when assigning a value to timestamp attribute. - - Timestamp column can have less precision than ruby timestamp - In result in how big a fraction of a second can be stored in the - database. - - - m = Model.create! - m.created_at.usec == m.reload.created_at.usec # => false - # due to different precision in Time.now and database column - - If the precision is low enough, (mysql default is 0, so it is always low - enough by default) the value changes when model is reloaded from the - database. This patch fixes that issue ensuring that any timestamp - assigned as an attribute is converted to column precision under the - attribute. - - *Bogdan Gusiev* - -* Introduce `connection.data_sources` and `connection.data_source_exists?`. - These methods determine what relations can be used to back Active Record - models (usually tables and views). - - Also deprecate `SchemaCache#tables`, `SchemaCache#table_exists?` and - `SchemaCache#clear_table_cache!` in favor of their new data source - counterparts. - - *Yves Senn*, *Matthew Draper* +* MySQL: `ROW_FORMAT=DYNAMIC` create table option by default. -* Add `ActiveRecord::Base.ignored_columns` to make some columns - invisible from Active Record. - - *Jean Boussier* - -* `ActiveRecord::Tasks::MySQLDatabaseTasks` fails if shellout to - mysql commands (like `mysqldump`) is not successful. - - *Steve Mitchell* - -* Ensure `select` quotes aliased attributes, even when using `from`. - - Fixes #21488. - - *Sean Griffin*, *@johanlunds* - -* MySQL: support `unsigned` numeric data types. - - Example: - - create_table :foos do |t| - t.unsigned_integer :quantity - t.unsigned_bigint :total - t.unsigned_float :percentage - t.unsigned_decimal :price, precision: 10, scale: 2 - end - - The `unsigned: true` option may be used for the primary key: - - create_table :foos, id: :bigint, unsigned: true do |t| - … - end + Since MySQL 5.7.9, the `innodb_default_row_format` option defines the default row + format for InnoDB tables. The default setting is `DYNAMIC`. + The row format is required for indexing on `varchar(255)` with `utf8mb4` columns. *Ryuta Kamizono* -* Add `#views` and `#view_exists?` methods on connection adapters. +* Fix join table column quoting with SQLite. - *Ryuta Kamizono* + *Gannon McGibbon* -* Correctly dump composite primary key. +* Allow disabling scopes generated by `ActiveRecord.enum`. - Example: + *Alfred Dominic* - create_table :barcodes, primary_key: ["region", "code"] do |t| - t.string :region - t.integer :code - end +* Ensure that `delete_all` on collection proxy returns affected count. *Ryuta Kamizono* -* Lookup the attribute name for `restrict_with_error` messages on the - model class that defines the association. - - *kuboon*, *Ronak Jangir* - -* Correct query for PostgreSQL 8.2 compatibility. +* Reset scope after delete on collection association to clear stale offsets of removed records. - *Ben Murphy*, *Matthew Draper* + *Gannon McGibbon* -* `bin/rails db:migrate` uses - `ActiveRecord::Tasks::DatabaseTasks.migrations_paths` instead of - `Migrator.migrations_paths`. +* Add the ability to prevent writes to a database for the duration of a block. - *Tobias Bielohlawek* - -* Support dropping indexes concurrently in PostgreSQL. - - See http://www.postgresql.org/docs/9.4/static/sql-dropindex.html for more - details. + Allows the application to prevent writes to a database. This can be useful when + you're building out multiple databases and want to make sure you're not sending + writes when you want a read. - *Grey Baker* + If `while_preventing_writes` is called and the query is considered a write + query the database will raise an exception regardless of whether the database + user is able to write. -* Deprecate passing conditions to `ActiveRecord::Relation#delete_all` - and `ActiveRecord::Relation#destroy_all`. + This is not meant to be a catch-all for write queries but rather a way to enforce + read-only queries without opening a second connection. One purpose of this is to + catch accidental writes, not all writes. - *Wojciech Wnętrzak* + *Eileen M. Uchitelle* -* Instantiating an AR model with `ActionController::Parameters` now raises - an `ActiveModel::ForbiddenAttributesError` if the parameters include a - `type` field that has not been explicitly permitted. Previously, the - `type` field was simply ignored in the same situation. +* Allow aliased attributes to be used in `#update_columns` and `#update`. - *Prem Sichanugrist* + *Gannon McGibbon* -* PostgreSQL, `create_schema`, `drop_schema` and `rename_table` now quote - schema names. +* Allow spaces in postgres table names. - Fixes #21418. + Fixes issue where "user post" is misinterpreted as "\"user\".\"post\"" when quoting table names with the postgres adapter. - Example: + *Gannon McGibbon* - create_schema("my.schema") - # CREATE SCHEMA "my.schema"; +* Cached `columns_hash` fields should be excluded from `ResultSet#column_types`. - *Yves Senn* + PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test + was passing for SQLite and MySQL, but failed for PostgreSQL: -* PostgreSQL, add `:if_exists` option to `#drop_schema`. This makes it - possible to drop a schema that might exist without raising an exception if - it doesn't. + ```ruby + class DeveloperName < ActiveRecord::Type::String + def deserialize(value) + "Developer: #{value}" + end + end - *Yves Senn* + class AttributedDeveloper < ActiveRecord::Base + self.table_name = "developers" -* Only try to nullify has_one target association if the record is persisted. + attribute :name, DeveloperName.new - Fixes #21223. + self.ignored_columns += ["name"] + end - *Agis Anastasopoulos* + developer = AttributedDeveloper.create + developer.update_column :name, "name" -* Uniqueness validator raises descriptive error when running on a persisted - record without primary key. + loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first + puts loaded_developer.name # should be "Developer: name" but it's just "name" + ``` - Fixes #21304. + *Dmitry Tsepelev* - *Yves Senn* +* Make the implicit order column configurable. -* Add a native JSON data type support in MySQL. + When calling ordered finder methods such as `first` or `last` without an + explicit order clause, ActiveRecord sorts records by primary key. This can + result in unpredictable and surprising behaviour when the primary key is + not an auto-incrementing integer, for example when it's a UUID. This change + makes it possible to override the column used for implicit ordering such + that `first` and `last` will return more predictable results. Example: - create_table :json_data_type do |t| - t.json :settings + class Project < ActiveRecord::Base + self.implicit_order_column = "created_at" end - *Ryuta Kamizono* - -* Descriptive error message when fixtures contain a missing column. - - Fixes #21201. + *Tekin Suleyman* - *Yves Senn* +* Bump minimum PostgreSQL version to 9.3. -* `ActiveRecord::Tasks::PostgreSQLDatabaseTasks` fail if shellout to - postgresql commands (like `pg_dump`) is not successful. + *Yasuo Honda* - *Bryan Paxton*, *Nate Berkopec* +* Values of enum are frozen, raising an error when attempting to modify them. -* Add `ActiveRecord::Relation#in_batches` to work with records and relations - in batches. + *Emmanuel Byrd* - Available options are `of` (batch size), `load`, `start`, and `finish`. +* Move `ActiveRecord::StatementInvalid` SQL to error property and include binds as separate error property. - Examples: - - Person.in_batches.each_record(&:party_all_night!) - Person.in_batches.update_all(awesome: true) - Person.in_batches.delete_all - Person.in_batches.each do |relation| - relation.delete_all - sleep 10 # Throttles the delete queries - end + `ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception_class` now requires `binds` to be passed as the last argument. - Fixes #20933. + `ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception` now requires `message`, `sql`, and `binds` to be passed as keyword arguments. - *Sina Siadat* - -* Added methods for PostgreSQL geometric data types to use in migrations. + Subclasses of `ActiveRecord::StatementInvalid` must now provide `sql:` and `binds:` arguments to `super`. Example: - create_table :foo do |t| - t.line :foo_line - t.lseg :foo_lseg - t.box :foo_box - t.path :foo_path - t.polygon :foo_polygon - t.circle :foo_circle - end - - *Mehmet Emin İNAÇ* - -* Add `cache_key` to ActiveRecord::Relation. - - Example: - - @users = User.where("name like ?", "%Alberto%") - @users.cache_key - # => "/users/query-5942b155a43b139f2471b872ac54251f-3-20150714212107656125000" - - *Alberto Fernández-Capel* + ``` + class MySubclassedError < ActiveRecord::StatementInvalid + def initialize(message, sql:, binds:) + super(message, sql: sql, binds: binds) + end + end + ``` -* Properly allow uniqueness validations on primary keys. + *Gannon McGibbon* - Fixes #20966. - - *Sean Griffin*, *presskey* - -* Don't raise an error if an association failed to destroy when `destroy` was - called on the parent (as opposed to `destroy!`). - - Fixes #20991. - - *Sean Griffin* - -* `ActiveRecord::RecordNotFound` modified to store model name, primary_key and - id of the caller model. It allows the catcher of this exception to make - a better decision to what to do with it. +* Add an `:if_not_exists` option to `create_table`. Example: - class SomeAbstractController < ActionController::Base - rescue_from ActiveRecord::RecordNotFound, with: :redirect_to_404 - - private def redirect_to_404(e) - return redirect_to(posts_url) if e.model == 'Post' - raise - end + create_table :posts, if_not_exists: true do |t| + t.string :title end - *Sameer Rahmani* - -* Deprecate the keys for association `restrict_dependent_destroy` errors in favor - of new key names. - - Previously `has_one` and `has_many` associations were using the - `one` and `many` keys respectively. Both of these keys have special - meaning in I18n (they are considered to be pluralizations) so by - renaming them to `has_one` and `has_many` we make the messages more explicit - and most importantly they don't clash with linguistical systems that need to - validate translation keys (and their pluralizations). - - The `:'restrict_dependent_destroy.one'` key should be replaced with - `:'restrict_dependent_destroy.has_one'`, and `:'restrict_dependent_destroy.many'` - with `:'restrict_dependent_destroy.has_many'`. - - *Roque Pinel*, *Christopher Dell* - -* Fix state being carried over from previous transaction. - - Considering the following example where `name` is a required attribute. - Before we had `new_record?` returning `true` for a persisted record: - - author = Author.create! name: 'foo' - author.name = nil - author.save # => false - author.new_record? # => true - - Fixes #20824. - - *Roque Pinel* - -* Correctly ignore `mark_for_destruction` when `autosave` isn't set to `true` - when validating associations. - - Fixes #20882. - - *Sean Griffin* - -* Fix a bug where counter_cache doesn't always work with polymorphic - relations. - - Fixes #16407. - - *Stefan Kanev*, *Sean Griffin* - -* Ensure that cyclic associations with autosave don't cause duplicate errors - to be added to the parent record. - - Fixes #20874. - - *Sean Griffin* - -* Ensure that `ActionController::Parameters` can still be passed to nested - attributes. - - Fixes #20922. - - *Sean Griffin* - -* Deprecate force association reload by passing a truthy argument to - association method. - - For collection association, you can call `#reload` on association proxy to - force a reload: - - @user.posts.reload # Instead of @user.posts(true) - - For singular association, you can call `#reload` on the parent object to - clear its association cache then call the association method: - - @user.reload.profile # Instead of @user.profile(true) - - Passing a truthy argument to force association to reload will be removed in - Rails 5.1. - - *Prem Sichanugrist* - -* Replaced `ActiveSupport::Concurrency::Latch` with `Concurrent::CountDownLatch` - from the concurrent-ruby gem. - - *Jerry D'Antonio* - -* Fix through associations using scopes having the scope merged multiple - times. - - Fixes #20721. - Fixes #20727. - - *Sean Griffin* - -* `ActiveRecord::Base.dump_schema_after_migration` applies migration tasks - other than `db:migrate`. (eg. `db:rollback`, `db:migrate:dup`, ...) - - Fixes #20743. - - *Yves Senn* - -* Add alternate syntax to make `change_column_default` reversible. - - User can pass in `:from` and `:to` to make `change_column_default` command - become reversible. - - Example: - - change_column_default :posts, :status, from: nil, to: "draft" - change_column_default :users, :authorized, from: true, to: false - - *Prem Sichanugrist* - -* Prevent error when using `force_reload: true` on an unassigned polymorphic - belongs_to association. - - Fixes #20426. - - *James Dabbs* - -* Correctly raise `ActiveRecord::AssociationTypeMismatch` when assigning - a wrong type to a namespaced association. - - Fixes #20545. - - *Diego Carrion* - -* `validates_absence_of` respects `marked_for_destruction?`. - - Fixes #20449. - - *Yves Senn* - -* Include the `Enumerable` module in `ActiveRecord::Relation` - - *Sean Griffin*, *bogdan* - -* Use `Enumerable#sum` in `ActiveRecord::Relation` if a block is given. - - *Sean Griffin* - -* Let `WITH` queries (Common Table Expressions) be explainable. - - *Vladimir Kochnev* - -* Make `remove_index :table, :column` reversible. - - *Yves Senn* - -* Fixed an error which would occur in dirty checking when calling - `update_attributes` from a getter. - - Fixes #20531. - - *Sean Griffin* - -* Make `remove_foreign_key` reversible. Any foreign key options must be - specified, similar to `remove_column`. - - *Aster Ryan* - -* Add `:_prefix` and `:_suffix` options to `enum` definition. + That would execute: - Fixes #17511, #17415. + CREATE TABLE IF NOT EXISTS posts ( + ... + ) - *Igor Kapkov* + If the table already exists, `if_not_exists: false` (the default) raises an + exception whereas `if_not_exists: true` does nothing. -* Correctly handle decimal arrays with defaults in the schema dumper. + *fatkodima*, *Stefan Kanev* - Fixes #20515. +* Defining an Enum as a Hash with blank key, or as an Array with a blank value, now raises an `ArgumentError`. - *Sean Griffin*, *jmondo* + *Christophe Maximin* -* Deprecate the PostgreSQL `:point` type in favor of a new one which will return - `Point` objects instead of an `Array` +* Adds support for multiple databases to `rails db:schema:cache:dump` and `rails db:schema:cache:clear`. - *Sean Griffin* + *Gannon McGibbon* -* Ensure symbols passed to `ActiveRecord::Relation#select` are always treated - as columns. - - Fixes #20360. +* `update_columns` now correctly raises `ActiveModel::MissingAttributeError` + if the attribute does not exist. *Sean Griffin* -* Do not set `sql_mode` if `strict: :default` is specified. - - # config/database.yml - production: - adapter: mysql2 - database: foo_prod - user: foo - strict: :default - - *Ryuta Kamizono* - -* Allow proc defaults to be passed to the attributes API. See documentation - for examples. - - *Sean Griffin*, *Kir Shatrov* - -* SQLite: `:collation` support for string and text columns. - - Example: - - create_table :foo do |t| - t.string :string_nocase, collation: 'NOCASE' - t.text :text_rtrim, collation: 'RTRIM' - end - - add_column :foo, :title, :string, collation: 'RTRIM' - - change_column :foo, :title, :string, collation: 'NOCASE' - - *Akshay Vishnoi* - -* Allow the use of symbols or strings to specify enum values in test - fixtures: - - awdr: - title: "Agile Web Development with Rails" - status: :proposed - - *George Claghorn* +* Add support for hash and URL configs in database hash of `ActiveRecord::Base.connected_to`. -* Clear query cache when `ActiveRecord::Base#reload` is called. + ```` + User.connected_to(database: { writing: "postgres://foo" }) do + User.create!(name: "Gannon") + end - *Shane Hender, Pierre Nespo* + config = { "adapter" => "sqlite3", "database" => "db/readonly.sqlite3" } + User.connected_to(database: { reading: config }) do + User.count + end + ```` -* Include stored procedures and function on the MySQL structure dump. + *Gannon McGibbon* - *Jonathan Worek* +* Support default expression for MySQL. -* Pass `:extend` option for `has_and_belongs_to_many` associations to the - underlying `has_many :through`. + MySQL 8.0.13 and higher supports default value to be a function or expression. - *Jaehyun Shin* - -* Deprecate `Relation#uniq` use `Relation#distinct` instead. - - See #9683. - - *Yves Senn* - -* Allow single table inheritance instantiation to work when storing - demodulized class names. - - *Alex Robbin* - -* Correctly pass MySQL options when using `structure_dump` or - `structure_load`. - - Specifically, it fixes an issue when using SSL authentication. - - *Alex Coomans* - -* Correctly dump `:options` on `create_table` for MySQL. + https://dev.mysql.com/doc/refman/8.0/en/create-table.html *Ryuta Kamizono* -* PostgreSQL: `:collation` support for string and text columns. +* Support expression indexes for MySQL. - Example: + MySQL 8.0.13 and higher supports functional key parts that index + expression values rather than column or column prefix values. - create_table :foos do |t| - t.string :string_en, collation: 'en_US.UTF-8' - t.text :text_ja, collation: 'ja_JP.UTF-8' - end + https://dev.mysql.com/doc/refman/8.0/en/create-index.html *Ryuta Kamizono* -* Remove `ActiveRecord::Serialization::XmlSerializer` from core. +* Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error. - *Zachary Scott* + Fixes #33056. -* Make `unscope` aware of "less than" and "greater than" conditions. + *Federico Martinez* - *TAKAHASHI Kazuaki* +* Add basic API for connection switching to support multiple databases. -* `find_by` and `find_by!` raise `ArgumentError` when called without - arguments. + 1) Adds a `connects_to` method for models to connect to multiple databases. Example: - *Kohei Suzuki* + ``` + class AnimalsModel < ApplicationRecord + self.abstract_class = true -* Revert behavior of `db:schema:load` back to loading the full - environment. This ensures that initializers are run. + connects_to database: { writing: :animals_primary, reading: :animals_replica } + end - Fixes #19545. + class Dog < AnimalsModel + # connected to both the animals_primary db for writing and the animals_replica for reading + end + ``` - *Yves Senn* + 2) Adds a `connected_to` block method for switching connection roles or connecting to + a database that the model didn't connect to. Connecting to the database in this block is + useful when you have another defined connection, for example `slow_replica` that you don't + want to connect to by default but need in the console, or a specific code block. -* Fix missing index when using `timestamps` with the `index` option. + ``` + ActiveRecord::Base.connected_to(role: :reading) do + Dog.first # finds dog from replica connected to AnimalsBase + Book.first # doesn't have a reading connection, will raise an error + end + ``` - The `index` option used with `timestamps` should be passed to both - `column` definitions for `created_at` and `updated_at` rather than just - the first. + ``` + ActiveRecord::Base.connected_to(database: :slow_replica) do + SlowReplicaModel.first # if the db config has a slow_replica configuration this will be used to do the lookup, otherwise this will throw an exception + end + ``` - *Paul Mucur* + *Eileen M. Uchitelle* -* Rename `:class` to `:anonymous_class` in association options. +* Enum raises on invalid definition values - Fixes #19659. + When defining a Hash enum it can be easy to use `[]` instead of `{}`. This + commit checks that only valid definition values are provided, those can + be a Hash, an array of Symbols or an array of Strings. Otherwise it + raises an `ArgumentError`. - *Andrew White* + Fixes #33961 -* Autosave existing records on a has many through association when the parent - is new. + *Alberto Almagro* - Fixes #19782. +* Reloading associations now clears the Query Cache like `Persistence#reload` does. - *Sean Griffin* + ``` + class Post < ActiveRecord::Base + has_one :category + belongs_to :author + has_many :comments + end -* Fixed a bug where uniqueness validations would error on out of range values, - even if an validation should have prevented it from hitting the database. + # Each of the following will now clear the query cache. + post.reload_category + post.reload_author + post.comments.reload + ``` - *Andrey Voronkov* + *Christophe Maximin* -* MySQL: `:charset` and `:collation` support for string and text columns. +* Added `index` option for `change_table` migration helpers. + With this change you can create indexes while adding new + columns into the existing tables. Example: - create_table :foos do |t| - t.string :string_utf8_bin, charset: 'utf8', collation: 'utf8_bin' - t.text :text_ascii, charset: 'ascii' + change_table(:languages) do |t| + t.string :country_code, index: true end - *Ryuta Kamizono* - -* Foreign key related methods in the migration DSL respect - `ActiveRecord::Base.pluralize_table_names = false`. - - Fixes #19643. - *Mehmet Emin İNAÇ* -* Reduce memory usage from loading types on PostgreSQL. - - Fixes #19578. - - *Sean Griffin* - -* Add `config.active_record.warn_on_records_fetched_greater_than` option. - - When set to an integer, a warning will be logged whenever a result set - larger than the specified size is returned by a query. - - Fixes #16463. - - *Jason Nochlin* - -* Ignore `.psqlrc` when loading database structure. - - *Jason Weathered* - -* Fix referencing wrong table aliases while joining tables of has many through - association (only when calling calculation methods). - - Fixes #19276. - - *pinglamb* - -* Correctly persist a serialized attribute that has been returned to - its default value by an in-place modification. - - Fixes #19467. - - *Matthew Draper* - -* Fix generating the schema file when using PostgreSQL `BigInt[]` data type. - Previously the `limit: 8` was not coming through, and this caused it to - become `Int[]` data type after rebuilding from the schema. - - Fixes #19420. - - *Jake Waller* - -* Reuse the `CollectionAssociation#reader` cache when the foreign key is - available prior to save. - - *Ben Woosley* - -* Add `config.active_record.dump_schemas` to fix `db:structure:dump` - when using schema_search_path and PostgreSQL extensions. - - Fixes #17157. - - *Ryan Wallace* - -* Renaming `use_transactional_fixtures` to `use_transactional_tests` for clarity. - - Fixes #18864. - - *Brandon Weiss* - -* Increase pg gem version requirement to `~> 0.18`. Earlier versions of the - pg gem are known to have problems with Ruby 2.2. - - *Matt Brictson* - -* Correctly dump `serial` and `bigserial`. - - *Ryuta Kamizono* - -* Fix default `format` value in `ActiveRecord::Tasks::DatabaseTasks#schema_file`. - - *James Cox* - -* Don't enroll records in the transaction if they don't have commit callbacks. - This was causing a memory leak when creating many records inside a transaction. - - Fixes #15549. - - *Will Bryant*, *Aaron Patterson* - -* Correctly create through records when created on a has many through - association when using `where`. - - Fixes #19073. - - *Sean Griffin* - -* Add `SchemaMigration.create_table` support for any unicode charsets with MySQL. - - *Ryuta Kamizono* - -* PostgreSQL no longer disables user triggers if system triggers can't be - disabled. Disabling user triggers does not fulfill what the method promises. - Rails currently requires superuser privileges for this method. - - If you absolutely rely on this behavior, consider patching - `disable_referential_integrity`. +* Fix `transaction` reverting for migrations. - *Yves Senn* + Before: Commands inside a `transaction` in a reverted migration ran uninverted. + Now: This change fixes that by reverting commands inside `transaction` block. -* Restore aborted transaction state when `disable_referential_integrity` fails - due to missing permissions. + *fatkodima*, *David Verhasselt* - *Toby Ovod-Everett*, *Yves Senn* +* Raise an error instead of scanning the filesystem root when `fixture_path` is blank. -* In PostgreSQL, print a warning message if `disable_referential_integrity` - fails due to missing permissions. + *Gannon McGibbon*, *Max Albrecht* - *Andrey Nering*, *Yves Senn* +* Allow `ActiveRecord::Base.configurations=` to be set with a symbolized hash. -* Allow a `:limit` option for MySQL bigint primary key support. + *Gannon McGibbon* - Example: - - create_table :foos, id: :primary_key, limit: 8 do |t| - end +* Don't update counter cache unless the record is actually saved. - # or - - create_table :foos, id: false do |t| - t.primary_key :id, limit: 8 - end + Fixes #31493, #33113, #33117. *Ryuta Kamizono* -* `belongs_to` will now trigger a validation error by default if the association is not present. - You can turn this off on a per-association basis with `optional: true`. - (Note this new default only applies to new Rails apps that will be generated with - `config.active_record.belongs_to_required_by_default = true` in initializer.) +* Deprecate `ActiveRecord::Result#to_hash` in favor of `ActiveRecord::Result#to_a`. - *Josef Šimánek* + *Gannon McGibbon*, *Kevin Cheng* -* Fixed `ActiveRecord::Relation#becomes!` and `changed_attributes` issues for type - columns. +* SQLite3 adapter supports expression indexes. - Fixes #17139. + ``` + create_table :users do |t| + t.string :email + end - *Miklos Fazekas* + add_index :users, 'lower(email)', name: 'index_users_on_email', unique: true + ``` -* Format the time string according to the precision of the time column. + *Gray Kemmey* - *Ryuta Kamizono* - -* Allow a `:precision` option for time type columns. - - *Ryuta Kamizono* - -* Add `ActiveRecord::Base.suppress` to prevent the receiver from being saved - during the given block. - - For example, here's a pattern of creating notifications when new comments - are posted. (The notification may in turn trigger an email, a push - notification, or just appear in the UI somewhere): - - class Comment < ActiveRecord::Base - belongs_to :commentable, polymorphic: true - after_create -> { Notification.create! comment: self, - recipients: commentable.recipients } - end - - That's what you want the bulk of the time. A new comment creates a new - Notification. There may be edge cases where you don't want that, like - when copying a commentable and its comments, in which case write a - concern with something like this: - - module Copyable - def copy_to(destination) - Notification.suppress do - # Copy logic that creates new comments that we do not want triggering - # notifications. - end - end - end +* Allow subclasses to redefine autosave callbacks for associated records. - *Michael Ryan* + Fixes #33305. -* `:time` option added for `#touch`. + *Andrey Subbota* - Fixes #18905. +* Bump minimum MySQL version to 5.5.8. - *Hyonjee Joo* + *Yasuo Honda* -* Deprecate passing of `start` value to `find_in_batches` and `find_each` - in favour of `begin_at` value. +* Use MySQL utf8mb4 character set by default. - *Vipul A M* + `utf8mb4` character set with 4-Byte encoding supports supplementary characters including emoji. + The previous default 3-Byte encoding character set `utf8` is not enough to support them. -* Add `foreign_key_exists?` method. + *Yasuo Honda* - *Tõnis Simo* +* Fix duplicated record creation when using nested attributes with `create_with`. -* Use SQL COUNT and LIMIT 1 queries for `none?` and `one?` methods - if no block or limit is given, instead of loading the entire - collection into memory. This applies to relations (e.g. `User.all`) - as well as associations (e.g. `account.users`) - - # Before: - - users.none? - # SELECT "users".* FROM "users" - - users.one? - # SELECT "users".* FROM "users" - - # After: - - users.none? - # SELECT 1 AS one FROM "users" LIMIT 1 - - users.one? - # SELECT COUNT(*) FROM "users" - - *Eugene Gilburg* - -* Have `enum` perform type casting consistently with the rest of Active - Record, such as `where`. - - *Sean Griffin* - -* `scoping` no longer pollutes the current scope of sibling classes when using - STI. - - Fixes #18806. - - Example: - - StiOne.none.scoping do - StiTwo.all - end - - - *Sean Griffin* + *Darwin Wu* -* `remove_reference` with `foreign_key: true` removes the foreign key before - removing the column. This fixes a bug where it was not possible to remove - the column on MySQL. +* Configuration item `config.filter_parameters` could also filter out + sensitive values of database columns when call `#inspect`. + We also added `ActiveRecord::Base::filter_attributes`/`=` in order to + specify sensitive attributes to specific model. - Fixes #18664. + ``` + Rails.application.config.filter_parameters += [:credit_card_number, /phone/] + Account.last.inspect # => #<Account id: 123, name: "DHH", credit_card_number: [FILTERED], telephone_number: [FILTERED] ...> + SecureAccount.filter_attributes += [:name] + SecureAccount.last.inspect # => #<SecureAccount id: 42, name: [FILTERED], credit_card_number: [FILTERED] ...> + ``` - *Yves Senn* + *Zhang Kang*, *Yoshiyuki Kinjo* -* `find_in_batches` now accepts an `:finish` parameter that complements the `:start` - parameter to specify where to stop batch processing. - - *Vipul A M* - -* Fix a rounding problem for PostgreSQL timestamp columns. - - If a timestamp column has a precision specified, it needs to - format according to that. - - *Ryuta Kamizono* - -* Respect the database default charset for `schema_migrations` table. - - The charset of `version` column in `schema_migrations` table depends - on the database default charset and collation rather than the encoding - of the connection. +* Deprecate `column_name_length`, `table_name_length`, `columns_per_table`, + `indexes_per_table`, `columns_per_multicolumn_index`, `sql_query_length`, + and `joins_per_query` methods in `DatabaseLimits`. *Ryuta Kamizono* -* Raise `ArgumentError` when passing `nil` or `false` to `Relation#merge`. - - These are not valid values to merge in a relation, so it should warn users - early. - - *Rafael Mendonça França* - -* Use `SCHEMA` instead of `DB_STRUCTURE` for specifying a structure file. - - This makes the `db:structure` tasks consistent with `test:load_structure`. - - *Dieter Komendera* - -* Respect custom primary keys for associations when calling `Relation#where` - - Fixes #18813. - - *Sean Griffin* - -* Fix several edge cases which could result in a counter cache updating - twice or not updating at all for `has_many` and `has_many :through`. - - Fixes #10865. - - *Sean Griffin* - -* Foreign keys added by migrations were given random, generated names. This - meant a different `structure.sql` would be generated every time a developer - ran migrations on their machine. - - The generated part of foreign key names is now a hash of the table name and - column name, which is consistent every time you run the migration. - - *Chris Sinjakli* - -* Fix n+1 query problem when eager loading nil associations (fixes #18312) - - *Sammy Larbi* - -* Change the default error message from `can't be blank` to `must exist` for - the presence validator of the `:required` option on `belongs_to`/`has_one` - associations. - - *Henrik Nygren* - -* Fixed `ActiveRecord::Relation#group` method when an argument is an SQL - reserved keyword: - - Example: - - SplitTest.group(:key).count - Property.group(:value).count - - *Bogdan Gusiev* - -* Added the `#or` method on `ActiveRecord::Relation`, allowing use of the OR - operator to combine WHERE or HAVING clauses. - - Example: - - Post.where('id = 1').or(Post.where('id = 2')) - # => SELECT * FROM posts WHERE (id = 1) OR (id = 2) +* `ActiveRecord::Base.configurations` now returns an object. - *Sean Griffin*, *Matthew Draper*, *Gael Muller*, *Olivier El Mekki* + `ActiveRecord::Base.configurations` used to return a hash, but this + is an inflexible data model. In order to improve multiple-database + handling in Rails, we've changed this to return an object. Some methods + are provided to make the object behave hash-like in order to ease the + transition process. Since most applications don't manipulate the hash + we've decided to add backwards-compatible functionality that will throw + a deprecation warning if used, however calling `ActiveRecord::Base.configurations` + will use the new version internally and externally. -* Don't define autosave association callbacks twice from - `accepts_nested_attributes_for`. + For example, the following `database.yml`: - Fixes #18704. + ``` + development: + adapter: sqlite3 + database: db/development.sqlite3 + ``` - *Sean Griffin* - -* Integer types will no longer raise a `RangeError` when assigning an - attribute, but will instead raise when going to the database. - - Fixes several vague issues which were never reported directly. See the - commit message from the commit which added this line for some examples. - - *Sean Griffin* + Used to become a hash: -* Values which would error while being sent to the database (such as an - ASCII-8BIT string with invalid UTF-8 bytes on SQLite3), no longer error on - assignment. They will still error when sent to the database, but you are - given the ability to re-assign it to a valid value. + ``` + { "development" => { "adapter" => "sqlite3", "database" => "db/development.sqlite3" } } + ``` - Fixes #18580. + Is now converted into the following object: - *Sean Griffin* + ``` + #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ + #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development", + @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> + ] + ``` -* Don't remove join dependencies in `Relation#exists?` + Iterating over the database configurations has also changed. Instead of + calling hash methods on the `configurations` hash directly, a new method `configs_for` has + been provided that allows you to select the correct configuration. `env_name` and + `spec_name` arguments are optional. For example, these return an array of + database config objects for the requested environment and a single database config object + will be returned for the requested environment and specification name respectively. - Fixes #18632. + ``` + ActiveRecord::Base.configurations.configs_for(env_name: "development") + ActiveRecord::Base.configurations.configs_for(env_name: "development", spec_name: "primary") + ``` - *Sean Griffin* + *Eileen M. Uchitelle*, *Aaron Patterson* -* Invalid values assigned to a JSON column are assumed to be `nil`. +* Add database configuration to disable advisory locks. - Fixes #18629. + ``` + production: + adapter: postgresql + advisory_locks: false + ``` - *Sean Griffin* + *Guo Xiang* -* Add `ActiveRecord::Base#accessed_fields`, which can be used to quickly - discover which fields were read from a model when you are looking to only - select the data you need from the database. +* SQLite3 adapter `alter_table` method restores foreign keys. - *Sean Griffin* + *Yasuo Honda* -* Introduce the `:if_exists` option for `drop_table`. +* Allow `:to_table` option to `invert_remove_foreign_key`. Example: - drop_table(:posts, if_exists: true) - - That would execute: - - DROP TABLE IF EXISTS posts - - If the table doesn't exist, `if_exists: false` (the default) raises an - exception whereas `if_exists: true` does nothing. - - *Cody Cutrer*, *Stefan Kanev*, *Ryuta Kamizono* - -* Don't run SQL if attribute value is not changed for update_attribute method. - - *Prathamesh Sonpatki* - -* `time` columns can now get affected by `time_zone_aware_attributes`. If you have - set `config.time_zone` to a value other than `'UTC'`, they will be treated - as in that time zone by default in Rails 5.1. If this is not the desired - behavior, you can set - - ActiveRecord::Base.time_zone_aware_types = [:datetime] - - A deprecation warning will be emitted if you have a `:time` column, and have - not explicitly opted out. - - Fixes #3145. - - *Sean Griffin* - -* Tests now run after_commit callbacks. You no longer have to declare - `uses_transaction ‘test name’` to test the results of an after_commit. - - after_commit callbacks run after committing a transaction whose parent - is not `joinable?`: un-nested transactions, transactions within test cases, - and transactions in `console --sandbox`. - - *arthurnn*, *Ravil Bayramgalin*, *Matthew Draper* - -* `nil` as a value for a binary column in a query no longer logs as - "<NULL binary data>", and instead logs as just "nil". - - *Sean Griffin* - -* `attribute_will_change!` will no longer cause non-persistable attributes to - be sent to the database. - - Fixes #18407. - - *Sean Griffin* - -* Remove support for the `protected_attributes` gem. - - *Carlos Antonio da Silva*, *Roberto Miranda* - -* Fix accessing of fixtures having non-string labels like Fixnum. - - *Prathamesh Sonpatki* - -* Remove deprecated support to preload instance-dependent associations. - - *Yves Senn* - -* Remove deprecated support for PostgreSQL ranges with exclusive lower bounds. - - *Yves Senn* - -* Remove deprecation when modifying a relation with cached Arel. - This raises an `ImmutableRelation` error instead. - - *Yves Senn* - -* Added `ActiveRecord::SecureToken` in order to encapsulate generation of - unique tokens for attributes in a model using `SecureRandom`. - - *Roberto Miranda* - -* Change the behavior of boolean columns to be closer to Ruby's semantics. - - Before this change we had a small set of "truthy", and all others are "falsy". - - Now, we have a small set of "falsy" values and all others are "truthy" matching - Ruby's semantics. - - *Rafael Mendonça França* - -* Deprecate `ActiveRecord::Base.errors_in_transactional_callbacks=`. - - *Rafael Mendonça França* - -* Change transaction callbacks to not swallow errors. - - Before this change any errors raised inside a transaction callback - were getting rescued and printed in the logs. - - Now these errors are not rescued anymore and just bubble up, as the other callbacks. - - *Rafael Mendonça França* - -* Remove deprecated `sanitize_sql_hash_for_conditions`. - - *Rafael Mendonça França* - -* Remove deprecated `Reflection#source_macro`. - - *Rafael Mendonça França* - -* Remove deprecated `symbolized_base_class` and `symbolized_sti_name`. - - *Rafael Mendonça França* - -* Remove deprecated `ActiveRecord::Base.disable_implicit_join_references=`. - - *Rafael Mendonça França* - -* Remove deprecated access to connection specification using a string accessor. - - Now all strings will be handled as a URL. - - *Rafael Mendonça França* - -* Change the default `null` value for `timestamps` to `false`. - - *Rafael Mendonça França* - -* Return an array of pools from `connection_pools`. + remove_foreign_key :accounts, to_table: :owners - *Rafael Mendonça França* - -* Return a null column from `column_for_attribute` when no column exists. - - *Rafael Mendonça França* - -* Remove deprecated `serialized_attributes`. - - *Rafael Mendonça França* - -* Remove deprecated automatic counter caches on `has_many :through`. - - *Rafael Mendonça França* + *Nikolay Epifanov*, *Rich Chen* -* Change the way in which callback chains can be halted. +* Add environment & load_config dependency to `bin/rake db:seed` to enable + seed load in environments without Rails and custom DB configuration - The preferred method to halt a callback chain from now on is to explicitly - `throw(:abort)`. - In the past, returning `false` in an Active Record `before_` callback had the - side effect of halting the callback chain. - This is not recommended anymore and, depending on the value of the - `ActiveSupport.halt_callback_chains_on_return_false` option, will - either not work at all or display a deprecation warning. - - *claudiob* - -* Clear query cache on rollback. - - *Florian Weingarten* - -* Fix setting of foreign_key for through associations when building a new record. - - Fixes #12698. - - *Ivan Antropov* - -* Improve dumping of the primary key. If it is not a default primary key, - correctly dump the type and options. - - Fixes #14169, #16599. - - *Ryuta Kamizono* - -* Format the datetime string according to the precision of the datetime field. - - Incompatible to rounding behavior between MySQL 5.6 and earlier. - - In 5.5, when you insert `2014-08-17 12:30:00.999999` the fractional part - is ignored. In 5.6, it's rounded to `2014-08-17 12:30:01`: + *Tobias Bielohlawek* - http://bugs.mysql.com/bug.php?id=68760 +* Fix default value for mysql time types with specified precision. - *Ryuta Kamizono* + *Nikolay Kondratyev* -* Allow a precision option for MySQL datetimes. +* Fix `touch` option to behave consistently with `Persistence#touch` method. *Ryuta Kamizono* -* Fixed automatic `inverse_of` for models nested in a module. +* Migrations raise when duplicate column definition. - *Andrew McCloud* + Fixes #33024. -* Change `ActiveRecord::Relation#update` behavior so that it can - be called without passing ids of the records to be updated. + *Federico Martinez* - This change allows updating multiple records returned by - `ActiveRecord::Relation` with callbacks and validations. +* Bump minimum SQLite version to 3.8 - # Before - # ArgumentError: wrong number of arguments (1 for 2) - Comment.where(group: 'expert').update(body: "Group of Rails Experts") + *Yasuo Honda* - # After - # Comments with group expert updated with body "Group of Rails Experts" - Comment.where(group: 'expert').update(body: "Group of Rails Experts") +* Fix parent record should not get saved with duplicate children records. - *Prathamesh Sonpatki* + Fixes #32940. -* Fix `reaping_frequency` option when the value is a string. + *Santosh Wadghule* - This usually happens when it is configured using `DATABASE_URL`. +* Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur. - *korbin* + *Brian Durand* -* Fix error message when trying to create an associated record and the foreign - key is missing. +* Ensure `Associations::CollectionAssociation#size` and `Associations::CollectionAssociation#empty?` + use loaded association ids if present. - Before this fix the following exception was being raised: - - NoMethodError: undefined method `val' for #<Arel::Nodes::BindParam:0x007fc64d19c218> - - Now the message is: - - ActiveRecord::UnknownAttributeError: unknown attribute 'foreign_key' for Model. - - *Rafael Mendonça França* + *Graham Turner* -* Fix change detection problem for PostgreSQL bytea type and - `ArgumentError: string contains null byte` exception with pg-0.18. +* Add support to preload associations of polymorphic associations when not all the records have the requested associations. - Fixes #17680. + *Dana Sherson* - *Lars Kanis* - -* When a table has a composite primary key, the `primary_key` method for - SQLite3 and PostgreSQL adapters was only returning the first field of the key. - Ensures that it will return nil instead, as Active Record doesn't support - composite primary keys. - - Fixes #18070. - - *arthurnn* - -* `validates_size_of` / `validates_length_of` do not count records - which are `marked_for_destruction?`. - - Fixes #7247. - - *Yves Senn* - -* Ensure `first!` and friends work on loaded associations. - - Fixes #18237. - - *Sean Griffin* - -* `eager_load` preserves readonly flag for associations. - - Fixes #15853. - - *Takashi Kokubun* - -* Provide `:touch` option to `save()` to accommodate saving without updating - timestamps. - - Fixes #18202. - - *Dan Olson* - -* Provide a more helpful error message when an unsupported class is passed to - `serialize`. - - Fixes #18224. - - *Sean Griffin* - -* Add bigint primary key support for MySQL. +* Add `touch_all` method to `ActiveRecord::Relation`. Example: - create_table :foos, id: :bigint do |t| - end - - *Ryuta Kamizono* - -* Support for any type of primary key. - - Fixes #14194. - - *Ryuta Kamizono* - -* Dump the default `nil` for PostgreSQL UUID primary key. - - *Ryuta Kamizono* - -* Add a `:foreign_key` option to `references` and associated migration - methods. The model and migration generators now use this option, rather than - the `add_foreign_key` form. - - *Sean Griffin* - -* Don't raise when writing an attribute with an out-of-range datetime passed - by the user. - - *Grey Baker* - -* Replace deprecated `ActiveRecord::Tasks::DatabaseTasks#load_schema` with - `ActiveRecord::Tasks::DatabaseTasks#load_schema_for`. - - *Yves Senn* + Person.where(name: "David").touch_all(time: Time.new(2020, 5, 16, 0, 0, 0)) -* Fix bug with `ActiveRecord::Type::Numeric` that caused negative values to - be marked as having changed when set to the same negative value. + *fatkodima*, *duggiefresh* - Fixes #18161. +* Add `ActiveRecord::Base.base_class?` predicate. - *Daniel Fox* - -* Introduce `force: :cascade` option for `create_table`. Using this option - will recreate tables even if they have dependent objects (like foreign keys). - `db/schema.rb` now uses `force: :cascade`. This makes it possible to - reload the schema when foreign keys are in place. - - *Matthew Draper*, *Yves Senn* - -* `db:schema:load` and `db:structure:load` no longer purge the database - before loading the schema. This is left for the user to do. - `db:test:prepare` will still purge the database. - - Fixes #17945. - - *Yves Senn* - -* Fix undesirable RangeError by `Type::Integer`. Add `Type::UnsignedInteger`. - - *Ryuta Kamizono* + *Bogdan Gusiev* -* Add `foreign_type` option to `has_one` and `has_many` association macros. +* Add custom prefix/suffix options to `ActiveRecord::Store.store_accessor`. - This option enables to define the column name of associated object's type for polymorphic associations. + *Tan Huynh*, *Yukio Mizuta* - *Ulisses Almeida*, *Kassio Borges* +* Rails 6 requires Ruby 2.5.0 or newer. -* Remove deprecated behavior allowing nested arrays to be passed as query - values. + *Jeremy Daer*, *Kasper Timm Hansen* - *Melanie Gilman* +* Deprecate `update_attributes`/`!` in favor of `update`/`!`. -* Deprecate passing a class as a value in a query. Users should pass strings - instead. + *Eddie Lebow* - *Melanie Gilman* +* Add `ActiveRecord::Base.create_or_find_by`/`!` to deal with the SELECT/INSERT race condition in + `ActiveRecord::Base.find_or_create_by`/`!` by leaning on unique constraints in the database. -* `add_timestamps` and `remove_timestamps` now properly reversible with - options. + *DHH* - *Noam Gagliardi-Rabinovich* +* Add `Relation#pick` as short-hand for single-value plucks. -* `ActiveRecord::ConnectionAdapters::ColumnDumper#column_spec` and - `ActiveRecord::ConnectionAdapters::ColumnDumper#prepare_column_options` no - longer have a `types` argument. They should access - `connection#native_database_types` directly. + *DHH* - *Yves Senn* -Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md) for previous changes. +Please check [5-2-stable](https://github.com/rails/rails/blob/5-2-stable/activerecord/CHANGELOG.md) for previous changes. |