1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activerecord/CHANGELOG.md

948 lines
28 KiB
Markdown
Raw Normal View History

* Add `touch` option to `has_one` association.
*Abhay Nikam*
Deprecate `where.not` working as NOR and will be changed to NAND in Rails 6.1 `where.not` with polymorphic association is partly fixed incidentally at 213796f (refer #33493, #26207, #17010, #16983, #14161), and I've added test case e9ba12f to avoid lose that fix accidentally in the future. In Rails 5.2, `where.not(polymorphic: object)` works as expected as NAND, but `where.not(polymorphic_type: object.class.polymorphic_name, polymorphic_id: object.id)` still unexpectedly works as NOR. To will make `where.not` working desiredly as NAND in Rails 6.1, this deprecates `where.not` working as NOR. If people want to continue NOR conditions, we'd encourage to them to `where.not` each conditions manually. ```ruby all = [treasures(:diamond), treasures(:sapphire), cars(:honda), treasures(:sapphire)] assert_equal all, PriceEstimate.all.map(&:estimate_of) ``` In Rails 6.0: ```ruby sapphire = treasures(:sapphire) nor = all.reject { |e| e.estimate_of_type == sapphire.class.polymorphic_name }.reject { |e| e.estimate_of_id == sapphire.id } assert_equal [cars(:honda)], nor without_sapphire = PriceEstimate.where.not( estimate_of_type: sapphire.class.polymorphic_name, estimate_of_id: sapphire.id ) assert_equal nor, without_sapphire.map(&:estimate_of) ``` In Rails 6.1: ```ruby sapphire = treasures(:sapphire) nand = all - [sapphire] assert_equal [treasures(:diamond), cars(:honda)], nand without_sapphire = PriceEstimate.where.not( estimate_of_type: sapphire.class.polymorphic_name, estimate_of_id: sapphire.id ) assert_equal nand, without_sapphire.map(&:estimate_of) ``` Resolves #31209.
2019-04-09 10:25:30 -04:00
* Deprecate `where.not` working as NOR and will be changed to NAND in Rails 6.1.
```ruby
all = [treasures(:diamond), treasures(:sapphire), cars(:honda), treasures(:sapphire)]
assert_equal all, PriceEstimate.all.map(&:estimate_of)
```
In Rails 6.0:
```ruby
sapphire = treasures(:sapphire)
nor = all.reject { |e|
e.estimate_of_type == sapphire.class.polymorphic_name
}.reject { |e|
e.estimate_of_id == sapphire.id
}
assert_equal [cars(:honda)], nor
without_sapphire = PriceEstimate.where.not(
estimate_of_type: sapphire.class.polymorphic_name, estimate_of_id: sapphire.id
)
assert_equal nor, without_sapphire.map(&:estimate_of)
```
In Rails 6.1:
```ruby
sapphire = treasures(:sapphire)
nand = all - [sapphire]
assert_equal [treasures(:diamond), cars(:honda)], nand
without_sapphire = PriceEstimate.where.not(
estimate_of_type: sapphire.class.polymorphic_name, estimate_of_id: sapphire.id
)
assert_equal nand, without_sapphire.map(&:estimate_of)
```
*Ryuta Kamizono*
* Fix dirty tracking after rollback.
Fixes #15018, #30167, #33868.
*Ryuta Kamizono*
* Add `ActiveRecord::Relation#cache_version` to support recyclable cache keys via
the versioned entries in `ActiveSupport::Cache`. This also means that
`ActiveRecord::Relation#cache_key` will now return a stable key that does not
include the max timestamp or count any more.
NOTE: This feature is turned off by default, and `cache_key` will still return
cache keys with timestamps until you set `ActiveRecord::Base.collection_cache_versioning = true`.
That's the setting for all new apps on Rails 6.0+
*Lachlan Sylvester*
* Fix dirty tracking for `touch` to track saved changes.
Fixes #33429.
*Ryuta Kamzono*
* `change_column_comment` and `change_table_comment` are invertible only if
`to` and `from` options are specified.
*Yoshiyuki Kinjo*
* Don't call commit/rollback callbacks when a record isn't saved.
Fixes #29747.
*Ryuta Kamizono*
* Fix circular `autosave: true` causes invalid records to be saved.
Prior to the fix, when there was a circular series of `autosave: true`
associations, the callback for a `has_many` association was run while
another instance of the same callback on the same association hadn't
finished running. When control returned to the first instance of the
callback, the instance variable had changed, and subsequent associated
records weren't saved correctly. Specifically, the ID field for the
`belongs_to` corresponding to the `has_many` was `nil`.
Fixes #28080.
*Larry Reid*
2016-03-09 22:41:44 -05:00
* Raise `ArgumentError` for invalid `:limit` and `:precision` like as other options.
Before:
```ruby
add_column :items, :attr1, :binary, size: 10 # => ArgumentError
add_column :items, :attr2, :decimal, scale: 10 # => ArgumentError
add_column :items, :attr3, :integer, limit: 10 # => ActiveRecordError
add_column :items, :attr4, :datetime, precision: 10 # => ActiveRecordError
```
After:
```ruby
add_column :items, :attr1, :binary, size: 10 # => ArgumentError
add_column :items, :attr2, :decimal, scale: 10 # => ArgumentError
add_column :items, :attr3, :integer, limit: 10 # => ArgumentError
add_column :items, :attr4, :datetime, precision: 10 # => ArgumentError
```
*Ryuta Kamizono*
* Association loading isn't to be affected by scoping consistently
whether preloaded / eager loaded or not, with the exception of `unscoped`.
Before:
```ruby
Post.where("1=0").scoping do
Comment.find(1).post # => nil
Comment.preload(:post).find(1).post # => #<Post id: 1, ...>
Comment.eager_load(:post).find(1).post # => #<Post id: 1, ...>
end
```
After:
```ruby
Post.where("1=0").scoping do
Comment.find(1).post # => #<Post id: 1, ...>
Comment.preload(:post).find(1).post # => #<Post id: 1, ...>
Comment.eager_load(:post).find(1).post # => #<Post id: 1, ...>
end
```
Fixes #34638, #35398.
*Ryuta Kamizono*
* Add `rails db:prepare` to migrate or setup a database.
Runs `db:migrate` if the database exists or `db:setup` if it doesn't.
*Roberto Miranda*
* Add `after_save_commit` callback as shortcut for `after_commit :hook, on: [ :create, :update ]`.
*DHH*
* 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.
Fixes #33249.
*Ryan H. Kerr*
* Add `ActiveRecord::Relation#extract_associated` for extracting associated records from a relation.
```
account.memberships.extract_associated(:user)
# => Returns collection of User records
```
*DHH*
* Add `ActiveRecord::Relation#annotate` for adding SQL comments to its queries.
For example:
```
Post.where(id: 123).annotate("this is a comment").to_sql
# SELECT "posts".* FROM "posts" WHERE "posts"."id" = 123 /* this is a comment */
```
This can be useful in instrumentation or other analysis of issued queries.
*Matt Yoho*
* Support Optimizer Hints.
2019-03-25 03:19:58 -04:00
In most databases, a way to control the optimizer is by using optimizer hints,
which can be specified within individual statements.
Example (for MySQL):
Topic.optimizer_hints("MAX_EXECUTION_TIME(50000)", "NO_INDEX_MERGE(topics)")
# SELECT /*+ MAX_EXECUTION_TIME(50000) NO_INDEX_MERGE(topics) */ `topics`.* FROM `topics`
Example (for PostgreSQL with pg_hint_plan):
Topic.optimizer_hints("SeqScan(topics)", "Parallel(topics 8)")
# SELECT /*+ SeqScan(topics) Parallel(topics 8) */ "topics".* FROM "topics"
See also:
* 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*
* Fix query attribute method on user-defined attribute to be aware of typecasted value.
For example, the following code no longer return false as casted non-empty string:
```
class Post < ActiveRecord::Base
attribute :user_defined_text, :text
end
Post.new(user_defined_text: "false").user_defined_text? # => true
```
*Yuji Kamijima*
* Quote empty ranges like other empty enumerables.
*Patrick Rebsch*
* 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`.
Supports skipping or upserting duplicates through the `ON CONFLICT` syntax
for PostgreSQL (9.5+) and SQLite (3.24+) and `ON DUPLICATE KEY UPDATE` syntax
for MySQL.
*Bob Lail*
* Add `rails db:seed:replant` that truncates tables of each database
for current environment and loads the seeds.
*bogdanvlviv*, *DHH*
* Add `ActiveRecord::Base.connection.truncate` for SQLite3 adapter.
*bogdanvlviv*
2019-03-04 08:51:29 -05:00
* Deprecate mismatched collation comparison for uniqueness validator.
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.
*Ryuta Kamizono*
* Add `reselect` method. This is a short-hand for `unscope(:select).select(fields)`.
Fixes #27340.
*Willian Gustavo Veiga*
* Add negative scopes for all enum values.
Example:
class Post < ActiveRecord::Base
enum status: %i[ drafted active trashed ]
end
Post.not_drafted # => where.not(status: :drafted)
Post.not_active # => where.not(status: :active)
Post.not_trashed # => where.not(status: :trashed)
*DHH*
* Fix different `count` calculation when using `size` with manual `select` with DISTINCT.
Fixes #35214.
*Juani Villarejo*
## Rails 6.0.0.beta3 (March 11, 2019) ##
* No changes.
2019-02-25 17:45:04 -05:00
## Rails 6.0.0.beta2 (February 25, 2019) ##
* Fix prepared statements caching to be enabled even when query caching is enabled.
*Ryuta Kamizono*
* Ensure `update_all` series cares about optimistic locking.
*Ryuta Kamizono*
* Don't allow `where` with non numeric string matches to 0 values.
*Ryuta Kamizono*
* Introduce `ActiveRecord::Relation#destroy_by` and `ActiveRecord::Relation#delete_by`.
`destroy_by` allows relation to find all the records matching the condition and perform
`destroy_all` on the matched records.
Example:
Person.destroy_by(name: 'David')
Person.destroy_by(name: 'David', rating: 4)
david = Person.find_by(name: 'David')
david.posts.destroy_by(id: [1, 2, 3])
`delete_by` allows relation to find all the records matching the condition and perform
`delete_all` on the matched records.
Example:
Person.delete_by(name: 'David')
Person.delete_by(name: 'David', rating: 4)
david = Person.find_by(name: 'David')
david.posts.delete_by(id: [1, 2, 3])
*Abhay Nikam*
* Don't allow `where` with invalid value matches to nil values.
Fixes #33624.
*Ryuta Kamizono*
* SQLite3: Implement `add_foreign_key` and `remove_foreign_key`.
*Ryuta Kamizono*
* Deprecate using class level querying methods if the receiver scope
regarded as leaked. Use `klass.unscoped` to avoid the leaking scope.
*Ryuta Kamizono*
Adds basic automatic database switching to Rails The following PR adds behavior to Rails to allow an application to automatically switch it's connection from the primary to the replica. A request will be sent to the replica if: * The request is a read request (`GET` or `HEAD`) * AND It's been 2 seconds since the last write to the database (because we don't want to send a user to a replica if the write hasn't made it to the replica yet) A request will be sent to the primary if: * It's not a GET/HEAD request (ie is a POST, PATCH, etc) * Has been less than 2 seconds since the last write to the database The implementation that decides when to switch reads (the 2 seconds) is "safe" to use in production but not recommended without adequate testing with your infrastructure. At GitHub in addition to the a 5 second delay we have a curcuit breaker that checks the replication delay and will send the query to a replica before the 5 seconds has passed. This is specific to our application and therefore not something Rails should be doing for you. You'll need to test and implement more robust handling of when to switch based on your infrastructure. The auto switcher in Rails is meant to be a basic implementation / API that acts as a guide for how to implement autoswitching. The impementation here is meant to be strict enough that you know how to implement your own resolver and operations classes but flexible enough that we're not telling you how to do it. The middleware is not included automatically and can be installed in your application with the classes you want to use for the resolver and operations passed in. If you don't pass any classes into the middleware the Rails default Resolver and Session classes will be used. The Resolver decides what parameters define when to switch, Operations sets timestamps for the Resolver to read from. For example you may want to use cookies instead of a session so you'd implement a Resolver::Cookies class and pass that into the middleware via configuration options. ``` config.active_record.database_selector = { delay: 2.seconds } config.active_record.database_resolver = MyResolver config.active_record.database_operations = MyResolver::MyCookies ``` Your classes can inherit from the existing classes and reimplment the methods (or implement more methods) that you need to do the switching. You only need to implement methods that you want to change. For example if you wanted to set the session token for the last read from a replica you would reimplement the `read_from_replica` method in your resolver class and implement a method that updates a new timestamp in your operations class.
2019-01-17 13:33:48 -05:00
* Allow applications to automatically switch connections.
Adds a middleware and configuration options that can be used in your
application to automatically switch between the writing and reading
database connections.
`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.
To use the middleware in your application you can use the following
configuration options:
```
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
Adds basic automatic database switching to Rails The following PR adds behavior to Rails to allow an application to automatically switch it's connection from the primary to the replica. A request will be sent to the replica if: * The request is a read request (`GET` or `HEAD`) * AND It's been 2 seconds since the last write to the database (because we don't want to send a user to a replica if the write hasn't made it to the replica yet) A request will be sent to the primary if: * It's not a GET/HEAD request (ie is a POST, PATCH, etc) * Has been less than 2 seconds since the last write to the database The implementation that decides when to switch reads (the 2 seconds) is "safe" to use in production but not recommended without adequate testing with your infrastructure. At GitHub in addition to the a 5 second delay we have a curcuit breaker that checks the replication delay and will send the query to a replica before the 5 seconds has passed. This is specific to our application and therefore not something Rails should be doing for you. You'll need to test and implement more robust handling of when to switch based on your infrastructure. The auto switcher in Rails is meant to be a basic implementation / API that acts as a guide for how to implement autoswitching. The impementation here is meant to be strict enough that you know how to implement your own resolver and operations classes but flexible enough that we're not telling you how to do it. The middleware is not included automatically and can be installed in your application with the classes you want to use for the resolver and operations passed in. If you don't pass any classes into the middleware the Rails default Resolver and Session classes will be used. The Resolver decides what parameters define when to switch, Operations sets timestamps for the Resolver to read from. For example you may want to use cookies instead of a session so you'd implement a Resolver::Cookies class and pass that into the middleware via configuration options. ``` config.active_record.database_selector = { delay: 2.seconds } config.active_record.database_resolver = MyResolver config.active_record.database_operations = MyResolver::MyCookies ``` Your classes can inherit from the existing classes and reimplment the methods (or implement more methods) that you need to do the switching. You only need to implement methods that you want to change. For example if you wanted to set the session token for the last read from a replica you would reimplement the `read_from_replica` method in your resolver class and implement a method that updates a new timestamp in your operations class.
2019-01-17 13:33:48 -05:00
```
To change the database selection strategy, pass a custom class to the
configuration options:
```
config.active_record.database_selector = { delay: 10.seconds }
config.active_record.database_resolver = MyResolver
config.active_record.database_resolver_context = MyResolver::MyCookies
Adds basic automatic database switching to Rails The following PR adds behavior to Rails to allow an application to automatically switch it's connection from the primary to the replica. A request will be sent to the replica if: * The request is a read request (`GET` or `HEAD`) * AND It's been 2 seconds since the last write to the database (because we don't want to send a user to a replica if the write hasn't made it to the replica yet) A request will be sent to the primary if: * It's not a GET/HEAD request (ie is a POST, PATCH, etc) * Has been less than 2 seconds since the last write to the database The implementation that decides when to switch reads (the 2 seconds) is "safe" to use in production but not recommended without adequate testing with your infrastructure. At GitHub in addition to the a 5 second delay we have a curcuit breaker that checks the replication delay and will send the query to a replica before the 5 seconds has passed. This is specific to our application and therefore not something Rails should be doing for you. You'll need to test and implement more robust handling of when to switch based on your infrastructure. The auto switcher in Rails is meant to be a basic implementation / API that acts as a guide for how to implement autoswitching. The impementation here is meant to be strict enough that you know how to implement your own resolver and operations classes but flexible enough that we're not telling you how to do it. The middleware is not included automatically and can be installed in your application with the classes you want to use for the resolver and operations passed in. If you don't pass any classes into the middleware the Rails default Resolver and Session classes will be used. The Resolver decides what parameters define when to switch, Operations sets timestamps for the Resolver to read from. For example you may want to use cookies instead of a session so you'd implement a Resolver::Cookies class and pass that into the middleware via configuration options. ``` config.active_record.database_selector = { delay: 2.seconds } config.active_record.database_resolver = MyResolver config.active_record.database_operations = MyResolver::MyCookies ``` Your classes can inherit from the existing classes and reimplment the methods (or implement more methods) that you need to do the switching. You only need to implement methods that you want to change. For example if you wanted to set the session token for the last read from a replica you would reimplement the `read_from_replica` method in your resolver class and implement a method that updates a new timestamp in your operations class.
2019-01-17 13:33:48 -05:00
```
*Eileen M. Uchitelle*
* MySQL: Support `:size` option to change text and blob size.
*Ryuta Kamizono*
* Make `t.timestamps` with precision by default.
*Ryuta Kamizono*
2019-01-18 15:42:12 -05:00
## Rails 6.0.0.beta1 (January 18, 2019) ##
* Remove deprecated `#set_state` from the transaction object.
*Rafael Mendonça França*
* Remove deprecated `#supports_statement_cache?` from the database adapters.
*Rafael Mendonça França*
* Remove deprecated `#insert_fixtures` from the database adapters.
*Rafael Mendonça França*
* Remove deprecated `ActiveRecord::ConnectionAdapters::SQLite3Adapter#valid_alter_table_type?`.
*Rafael Mendonça França*
* Do not allow passing the column name to `sum` when a block is passed.
*Rafael Mendonça França*
* Do not allow passing the column name to `count` when a block is passed.
*Rafael Mendonça França*
* Remove delegation of missing methods in a relation to arel.
*Rafael Mendonça França*
* Remove delegation of missing methods in a relation to private methods of the class.
*Rafael Mendonça França*
* Deprecate `config.activerecord.sqlite3.represent_boolean_as_integer`.
*Rafael Mendonça França*
* Change `SQLite3Adapter` to always represent boolean values as integers.
*Rafael Mendonça França*
* Remove ability to specify a timestamp name for `#cache_key`.
*Rafael Mendonça França*
* Remove deprecated `ActiveRecord::Migrator.migrations_path=`.
*Rafael Mendonça França*
* Remove deprecated `expand_hash_conditions_for_aggregates`.
*Rafael Mendonça França*
* Set polymorphic type column to NULL on `dependent: :nullify` strategy.
On polymorphic associations both the foreign key and the foreign type columns will be set to NULL.
*Laerti Papa*
* Allow permitted instance of `ActionController::Parameters` as argument of `ActiveRecord::Relation#exists?`.
*Gannon McGibbon*
* Add support for endless ranges introduces in Ruby 2.6.
*Greg Navis*
* Deprecate passing `migrations_paths` to `connection.assume_migrated_upto_version`.
*Ryuta Kamizono*
* MySQL: `ROW_FORMAT=DYNAMIC` create table option by default.
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*
* Fix join table column quoting with SQLite.
*Gannon McGibbon*
* Allow disabling scopes generated by `ActiveRecord.enum`.
*Alfred Dominic*
* Ensure that `delete_all` on collection proxy returns affected count.
*Ryuta Kamizono*
* Reset scope after delete on collection association to clear stale offsets of removed records.
*Gannon McGibbon*
* Add the ability to prevent writes to a database for the duration of a block.
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.
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.
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.
*Eileen M. Uchitelle*
* Allow aliased attributes to be used in `#update_columns` and `#update`.
*Gannon McGibbon*
* Allow spaces in postgres table names.
Fixes issue where "user post" is misinterpreted as "\"user\".\"post\"" when quoting table names with the postgres adapter.
*Gannon McGibbon*
* Cached `columns_hash` fields should be excluded from `ResultSet#column_types`.
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:
```ruby
class DeveloperName < ActiveRecord::Type::String
def deserialize(value)
"Developer: #{value}"
end
end
class AttributedDeveloper < ActiveRecord::Base
self.table_name = "developers"
attribute :name, DeveloperName.new
self.ignored_columns += ["name"]
end
developer = AttributedDeveloper.create
developer.update_column :name, "name"
loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first
puts loaded_developer.name # should be "Developer: name" but it's just "name"
```
*Dmitry Tsepelev*
* Make the implicit order column configurable.
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:
class Project < ActiveRecord::Base
self.implicit_order_column = "created_at"
end
*Tekin Suleyman*
* Bump minimum PostgreSQL version to 9.3.
*Yasuo Honda*
* Values of enum are frozen, raising an error when attempting to modify them.
*Emmanuel Byrd*
* Move `ActiveRecord::StatementInvalid` SQL to error property and include binds as separate error property.
`ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception_class` now requires `binds` to be passed as the last argument.
`ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception` now requires `message`, `sql`, and `binds` to be passed as keyword arguments.
Subclasses of `ActiveRecord::StatementInvalid` must now provide `sql:` and `binds:` arguments to `super`.
Example:
```
class MySubclassedError < ActiveRecord::StatementInvalid
def initialize(message, sql:, binds:)
super(message, sql: sql, binds: binds)
end
end
```
*Gannon McGibbon*
* Add an `:if_not_exists` option to `create_table`.
Example:
create_table :posts, if_not_exists: true do |t|
t.string :title
end
That would execute:
CREATE TABLE IF NOT EXISTS posts (
...
)
If the table already exists, `if_not_exists: false` (the default) raises an
exception whereas `if_not_exists: true` does nothing.
*fatkodima*, *Stefan Kanev*
* Defining an Enum as a Hash with blank key, or as an Array with a blank value, now raises an `ArgumentError`.
*Christophe Maximin*
* Adds support for multiple databases to `rails db:schema:cache:dump` and `rails db:schema:cache:clear`.
*Gannon McGibbon*
* `update_columns` now correctly raises `ActiveModel::MissingAttributeError`
if the attribute does not exist.
*Sean Griffin*
* Add support for hash and URL configs in database hash of `ActiveRecord::Base.connected_to`.
````
User.connected_to(database: { writing: "postgres://foo" }) do
User.create!(name: "Gannon")
end
config = { "adapter" => "sqlite3", "database" => "db/readonly.sqlite3" }
User.connected_to(database: { reading: config }) do
User.count
end
````
*Gannon McGibbon*
* Support default expression for MySQL.
MySQL 8.0.13 and higher supports default value to be a function or expression.
https://dev.mysql.com/doc/refman/8.0/en/create-table.html
*Ryuta Kamizono*
* Support expression indexes for MySQL.
MySQL 8.0.13 and higher supports functional key parts that index
expression values rather than column or column prefix values.
https://dev.mysql.com/doc/refman/8.0/en/create-index.html
*Ryuta Kamizono*
* Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.
Fixes #33056.
*Federico Martinez*
Basic API for connection switching This PR adds the ability to 1) connect to multiple databases in a model, and 2) switch between those connections using a block. To connect a model to a set of databases for writing and reading use the following API. This API supercedes `establish_connection`. The `writing` and `reading` keys represent handler / role names and `animals` and `animals_replica` represents the database key to look up the configuration hash from. ``` class AnimalsBase < ApplicationRecord connects_to database: { writing: :animals, reading: :animals_replica } end ``` Inside the application - outside the model declaration - we can switch connections with a block call to `connected_to`. If we want to connect to a db that isn't default (ie readonly_slow) we can connect like this: Outside the model we may want to connect to a new database (one that is not in the default writing/reading set) - for example a slow replica for making slow queries. To do this we have the `connected_to` method that takes a `database` hash that matches the signature of `connects_to`. The `connected_to` method also takes a block. ``` AcitveRecord::Base.connected_to(database: { slow_readonly: :primary_replica_slow }) do ModelInPrimary.do_something_thats_slow end ``` For models that are already loaded and connections that are already connected, `connected_to` doesn't need to pass in a `database` because you may want to run queries against multiple databases using a specific role/handler. In this case `connected_to` can take a `role` and use that to swap on the connection passed. This simplies queries - and matches how we do it in GitHub. Once you're connected to the database you don't need to re-connect, we assume the connection is in the pool and simply pass the handler we'd like to swap on. ``` ActiveRecord::Base.connected_to(role: :reading) do Dog.read_something_from_dog ModelInPrimary.do_something_from_model_in_primary end ```
2018-09-28 16:52:54 -04:00
* Add basic API for connection switching to support multiple databases.
1) Adds a `connects_to` method for models to connect to multiple databases. Example:
```
class AnimalsModel < ApplicationRecord
self.abstract_class = true
connects_to database: { writing: :animals_primary, reading: :animals_replica }
end
class Dog < AnimalsModel
# connected to both the animals_primary db for writing and the animals_replica for reading
end
```
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.
```
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
```
```
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
```
*Eileen M. Uchitelle*
* Enum raises on invalid definition values
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`.
Fixes #33961
*Alberto Almagro*
* Reloading associations now clears the Query Cache like `Persistence#reload` does.
```
class Post < ActiveRecord::Base
has_one :category
belongs_to :author
has_many :comments
end
# Each of the following will now clear the query cache.
post.reload_category
post.reload_author
post.comments.reload
```
*Christophe Maximin*
* Added `index` option for `change_table` migration helpers.
With this change you can create indexes while adding new
columns into the existing tables.
Example:
change_table(:languages) do |t|
t.string :country_code, index: true
end
*Mehmet Emin İNAÇ*
* Fix `transaction` reverting for migrations.
Before: Commands inside a `transaction` in a reverted migration ran uninverted.
Now: This change fixes that by reverting commands inside `transaction` block.
*fatkodima*, *David Verhasselt*
* Raise an error instead of scanning the filesystem root when `fixture_path` is blank.
*Gannon McGibbon*, *Max Albrecht*
2018-09-24 13:20:03 -04:00
* Allow `ActiveRecord::Base.configurations=` to be set with a symbolized hash.
*Gannon McGibbon*
* Don't update counter cache unless the record is actually saved.
Fixes #31493, #33113, #33117.
*Ryuta Kamizono*
* Deprecate `ActiveRecord::Result#to_hash` in favor of `ActiveRecord::Result#to_a`.
*Gannon McGibbon*, *Kevin Cheng*
* SQLite3 adapter supports expression indexes.
```
create_table :users do |t|
t.string :email
end
add_index :users, 'lower(email)', name: 'index_users_on_email', unique: true
```
*Gray Kemmey*
* Allow subclasses to redefine autosave callbacks for associated records.
Fixes #33305.
*Andrey Subbota*
* Bump minimum MySQL version to 5.5.8.
*Yasuo Honda*
Use utf8mb4 character set by default for MySQL database (#33608) * Use utf8mb4 character set by default `utf8mb4` character set supports supplementary characters including emoji. `utf8` character set with 3-Byte encoding is not enough to support them. There was a downside of 4-Byte length character set with MySQL 5.5 and 5.6: "ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes" for Rails string data type which is mapped to varchar(255) type. MySQL 5.7 supports 3072 byte key prefix length by default. * Remove `DEFAULT COLLATE` from Active Record unit test databases There should be no "one size fits all" collation in MySQL 5.7. Let MySQL server choose the default collation for Active Record unit test databases. Users can choose their best collation for their databases by setting `options[:collation]` based on their requirements. * InnoDB FULLTEXT indexes support since MySQL 5.6 it does not have to use MyISAM storage engine whose maximum key length is 1000 bytes. Using MyISAM storag engine with utf8mb4 character set would cause "Specified key was too long; max key length is 1000 bytes" https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html * References "10.9.1 The utf8mb4 Character Set (4-Byte UTF-8 Unicode Encoding)" https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8mb4.html "10.9.2 The utf8mb3 Character Set (3-Byte UTF-8 Unicode Encoding)" https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8.html "14.8.1.7 Limits on InnoDB Tables" https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html > If innodb_large_prefix is enabled (the default), the index key prefix limit is 3072 bytes > for InnoDB tables that use DYNAMIC or COMPRESSED row format. * CI against MySQL 5.7 Followed this instruction and changed root password to empty string. https://docs.travis-ci.com/user/database-setup/#MySQL-57 * The recommended minimum version of MySQL is 5.7.9 to support utf8mb4 character set and `innodb_default_row_format` MySQL 5.7.9 introduces `innodb_default_row_format` to support 3072 byte length index by default. Users do not have to change MySQL database configuration to support Rails string type. https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_default_row_format https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html > If innodb_large_prefix is enabled (the default), > the index key prefix limit is 3072 bytes for InnoDB tables that use DYNAMIC or COMPRESSED row format. * The recommended minimum version of MariaDB is 10.2.2 MariaDB 10.2.2 is the first version of MariaDB supporting `innodb_default_row_format` Also MariaDB says "MySQL 5.7 is compatible with MariaDB 10.2". - innodb_default_row_format https://mariadb.com/kb/en/library/xtradbinnodb-server-system-variables/#innodb_default_row_format - "MariaDB versus MySQL - Compatibility" https://mariadb.com/kb/en/library/mariadb-vs-mysql-compatibility/ > MySQL 5.7 is compatible with MariaDB 10.2 - "Supported Character Sets and Collations" https://mariadb.com/kb/en/library/supported-character-sets-and-collations/
2018-09-11 16:03:34 -04:00
* Use MySQL utf8mb4 character set by default.
`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.
*Yasuo Honda*
* Fix duplicated record creation when using nested attributes with `create_with`.
*Darwin Wu*
* 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.
```
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] ...>
```
*Zhang Kang*, *Yoshiyuki Kinjo*
* 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*
* `ActiveRecord::Base.configurations` now returns an object.
Refactors Active Record connection management While the three-tier config makes it easier to define databases for multiple database applications, it quickly became clear to offer full support for multiple databases we need to change the way the connections hash was handled. A three-tier config means that when Rails needed to choose a default configuration (in the case a user doesn't ask for a specific configuration) it wasn't clear to Rails which the default was. I [bandaid fixed this so the rake tasks could work](#32271) but that fix wasn't correct because it actually doubled up the configuration hashes. Instead of attemping to manipulate the hashes @tenderlove and I decided that it made more sense if we converted the hashes to objects so we can easily ask those object questions. In a three tier config like this: ``` development: primary: database: "my_primary_db" animals: database; "my_animals_db" ``` We end up with an object like this: ``` @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> ``` The configurations setter takes the database configuration set by your application and turns them into an `ActiveRecord::DatabaseConfigurations` object that has one getter - `@configurations` which is an array of all the database objects. The configurations getter returns this object by default since it acts like a hash in most of the cases we need. For example if you need to access the default `development` database we can simply request it as we did before: ``` ActiveRecord::Base.configurations["development"] ``` This will return primary development database configuration hash: ``` { "database" => "my_primary_db" } ``` Internally all of Active Record has been converted to use the new objects. I've built this to be backwards compatible but allow for accessing the hash if needed for a deprecation period. To get the original hash instead of the object you can either add `to_h` on the configurations call or pass `legacy: true` to `configurations. ``` ActiveRecord::Base.configurations.to_h => { "development => { "database" => "my_primary_db" } } ActiveRecord::Base.configurations(legacy: true) => { "development => { "database" => "my_primary_db" } } ``` The new configurations object allows us to iterate over the Active Record configurations without losing the known environment or specification name for that configuration. You can also select all the configs for an env or env and spec. With this we can always ask any object what environment it belongs to: ``` db_configs = ActiveRecord::Base.configurations.configurations_for("development") => #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> db_config.env_name => "development" db_config.spec_name => "primary" db_config.config => { "adapter"=>"sqlite3", "database"=>"db/development.sqlite3" } ``` The configurations object is more flexible than the configurations hash and will allow us to build on top of the connection management in order to add support for primary/replica connections, sharding, and constructing queries for associations that live in multiple databases.
2018-08-16 15:49:18 -04:00
`ActiveRecord::Base.configurations` used to return a hash, but this
Refactors Active Record connection management While the three-tier config makes it easier to define databases for multiple database applications, it quickly became clear to offer full support for multiple databases we need to change the way the connections hash was handled. A three-tier config means that when Rails needed to choose a default configuration (in the case a user doesn't ask for a specific configuration) it wasn't clear to Rails which the default was. I [bandaid fixed this so the rake tasks could work](#32271) but that fix wasn't correct because it actually doubled up the configuration hashes. Instead of attemping to manipulate the hashes @tenderlove and I decided that it made more sense if we converted the hashes to objects so we can easily ask those object questions. In a three tier config like this: ``` development: primary: database: "my_primary_db" animals: database; "my_animals_db" ``` We end up with an object like this: ``` @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> ``` The configurations setter takes the database configuration set by your application and turns them into an `ActiveRecord::DatabaseConfigurations` object that has one getter - `@configurations` which is an array of all the database objects. The configurations getter returns this object by default since it acts like a hash in most of the cases we need. For example if you need to access the default `development` database we can simply request it as we did before: ``` ActiveRecord::Base.configurations["development"] ``` This will return primary development database configuration hash: ``` { "database" => "my_primary_db" } ``` Internally all of Active Record has been converted to use the new objects. I've built this to be backwards compatible but allow for accessing the hash if needed for a deprecation period. To get the original hash instead of the object you can either add `to_h` on the configurations call or pass `legacy: true` to `configurations. ``` ActiveRecord::Base.configurations.to_h => { "development => { "database" => "my_primary_db" } } ActiveRecord::Base.configurations(legacy: true) => { "development => { "database" => "my_primary_db" } } ``` The new configurations object allows us to iterate over the Active Record configurations without losing the known environment or specification name for that configuration. You can also select all the configs for an env or env and spec. With this we can always ask any object what environment it belongs to: ``` db_configs = ActiveRecord::Base.configurations.configurations_for("development") => #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> db_config.env_name => "development" db_config.spec_name => "primary" db_config.config => { "adapter"=>"sqlite3", "database"=>"db/development.sqlite3" } ``` The configurations object is more flexible than the configurations hash and will allow us to build on top of the connection management in order to add support for primary/replica connections, sharding, and constructing queries for associations that live in multiple databases.
2018-08-16 15:49:18 -04:00
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.
For example, the following `database.yml`:
Refactors Active Record connection management While the three-tier config makes it easier to define databases for multiple database applications, it quickly became clear to offer full support for multiple databases we need to change the way the connections hash was handled. A three-tier config means that when Rails needed to choose a default configuration (in the case a user doesn't ask for a specific configuration) it wasn't clear to Rails which the default was. I [bandaid fixed this so the rake tasks could work](#32271) but that fix wasn't correct because it actually doubled up the configuration hashes. Instead of attemping to manipulate the hashes @tenderlove and I decided that it made more sense if we converted the hashes to objects so we can easily ask those object questions. In a three tier config like this: ``` development: primary: database: "my_primary_db" animals: database; "my_animals_db" ``` We end up with an object like this: ``` @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> ``` The configurations setter takes the database configuration set by your application and turns them into an `ActiveRecord::DatabaseConfigurations` object that has one getter - `@configurations` which is an array of all the database objects. The configurations getter returns this object by default since it acts like a hash in most of the cases we need. For example if you need to access the default `development` database we can simply request it as we did before: ``` ActiveRecord::Base.configurations["development"] ``` This will return primary development database configuration hash: ``` { "database" => "my_primary_db" } ``` Internally all of Active Record has been converted to use the new objects. I've built this to be backwards compatible but allow for accessing the hash if needed for a deprecation period. To get the original hash instead of the object you can either add `to_h` on the configurations call or pass `legacy: true` to `configurations. ``` ActiveRecord::Base.configurations.to_h => { "development => { "database" => "my_primary_db" } } ActiveRecord::Base.configurations(legacy: true) => { "development => { "database" => "my_primary_db" } } ``` The new configurations object allows us to iterate over the Active Record configurations without losing the known environment or specification name for that configuration. You can also select all the configs for an env or env and spec. With this we can always ask any object what environment it belongs to: ``` db_configs = ActiveRecord::Base.configurations.configurations_for("development") => #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> db_config.env_name => "development" db_config.spec_name => "primary" db_config.config => { "adapter"=>"sqlite3", "database"=>"db/development.sqlite3" } ``` The configurations object is more flexible than the configurations hash and will allow us to build on top of the connection management in order to add support for primary/replica connections, sharding, and constructing queries for associations that live in multiple databases.
2018-08-16 15:49:18 -04:00
```
development:
adapter: sqlite3
database: db/development.sqlite3
```
Used to become a hash:
```
{ "development" => { "adapter" => "sqlite3", "database" => "db/development.sqlite3" } }
```
Is now converted into the following object:
```
#<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
#<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>
]
```
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.
Refactors Active Record connection management While the three-tier config makes it easier to define databases for multiple database applications, it quickly became clear to offer full support for multiple databases we need to change the way the connections hash was handled. A three-tier config means that when Rails needed to choose a default configuration (in the case a user doesn't ask for a specific configuration) it wasn't clear to Rails which the default was. I [bandaid fixed this so the rake tasks could work](#32271) but that fix wasn't correct because it actually doubled up the configuration hashes. Instead of attemping to manipulate the hashes @tenderlove and I decided that it made more sense if we converted the hashes to objects so we can easily ask those object questions. In a three tier config like this: ``` development: primary: database: "my_primary_db" animals: database; "my_animals_db" ``` We end up with an object like this: ``` @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> ``` The configurations setter takes the database configuration set by your application and turns them into an `ActiveRecord::DatabaseConfigurations` object that has one getter - `@configurations` which is an array of all the database objects. The configurations getter returns this object by default since it acts like a hash in most of the cases we need. For example if you need to access the default `development` database we can simply request it as we did before: ``` ActiveRecord::Base.configurations["development"] ``` This will return primary development database configuration hash: ``` { "database" => "my_primary_db" } ``` Internally all of Active Record has been converted to use the new objects. I've built this to be backwards compatible but allow for accessing the hash if needed for a deprecation period. To get the original hash instead of the object you can either add `to_h` on the configurations call or pass `legacy: true` to `configurations. ``` ActiveRecord::Base.configurations.to_h => { "development => { "database" => "my_primary_db" } } ActiveRecord::Base.configurations(legacy: true) => { "development => { "database" => "my_primary_db" } } ``` The new configurations object allows us to iterate over the Active Record configurations without losing the known environment or specification name for that configuration. You can also select all the configs for an env or env and spec. With this we can always ask any object what environment it belongs to: ``` db_configs = ActiveRecord::Base.configurations.configurations_for("development") => #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> db_config.env_name => "development" db_config.spec_name => "primary" db_config.config => { "adapter"=>"sqlite3", "database"=>"db/development.sqlite3" } ``` The configurations object is more flexible than the configurations hash and will allow us to build on top of the connection management in order to add support for primary/replica connections, sharding, and constructing queries for associations that live in multiple databases.
2018-08-16 15:49:18 -04:00
```
ActiveRecord::Base.configurations.configs_for(env_name: "development")
ActiveRecord::Base.configurations.configs_for(env_name: "development", spec_name: "primary")
Refactors Active Record connection management While the three-tier config makes it easier to define databases for multiple database applications, it quickly became clear to offer full support for multiple databases we need to change the way the connections hash was handled. A three-tier config means that when Rails needed to choose a default configuration (in the case a user doesn't ask for a specific configuration) it wasn't clear to Rails which the default was. I [bandaid fixed this so the rake tasks could work](#32271) but that fix wasn't correct because it actually doubled up the configuration hashes. Instead of attemping to manipulate the hashes @tenderlove and I decided that it made more sense if we converted the hashes to objects so we can easily ask those object questions. In a three tier config like this: ``` development: primary: database: "my_primary_db" animals: database; "my_animals_db" ``` We end up with an object like this: ``` @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> ``` The configurations setter takes the database configuration set by your application and turns them into an `ActiveRecord::DatabaseConfigurations` object that has one getter - `@configurations` which is an array of all the database objects. The configurations getter returns this object by default since it acts like a hash in most of the cases we need. For example if you need to access the default `development` database we can simply request it as we did before: ``` ActiveRecord::Base.configurations["development"] ``` This will return primary development database configuration hash: ``` { "database" => "my_primary_db" } ``` Internally all of Active Record has been converted to use the new objects. I've built this to be backwards compatible but allow for accessing the hash if needed for a deprecation period. To get the original hash instead of the object you can either add `to_h` on the configurations call or pass `legacy: true` to `configurations. ``` ActiveRecord::Base.configurations.to_h => { "development => { "database" => "my_primary_db" } } ActiveRecord::Base.configurations(legacy: true) => { "development => { "database" => "my_primary_db" } } ``` The new configurations object allows us to iterate over the Active Record configurations without losing the known environment or specification name for that configuration. You can also select all the configs for an env or env and spec. With this we can always ask any object what environment it belongs to: ``` db_configs = ActiveRecord::Base.configurations.configurations_for("development") => #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",@spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>, #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="development",@spec_name="animals", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]> db_config.env_name => "development" db_config.spec_name => "primary" db_config.config => { "adapter"=>"sqlite3", "database"=>"db/development.sqlite3" } ``` The configurations object is more flexible than the configurations hash and will allow us to build on top of the connection management in order to add support for primary/replica connections, sharding, and constructing queries for associations that live in multiple databases.
2018-08-16 15:49:18 -04:00
```
*Eileen M. Uchitelle*, *Aaron Patterson*
* Add database configuration to disable advisory locks.
```
production:
adapter: postgresql
advisory_locks: false
```
*Guo Xiang*
* SQLite3 adapter `alter_table` method restores foreign keys.
*Yasuo Honda*
* Allow `:to_table` option to `invert_remove_foreign_key`.
Example:
remove_foreign_key :accounts, to_table: :owners
*Nikolay Epifanov*, *Rich Chen*
* Add environment & load_config dependency to `bin/rake db:seed` to enable
seed load in environments without Rails and custom DB configuration
*Tobias Bielohlawek*
* Fix default value for mysql time types with specified precision.
*Nikolay Kondratyev*
* Fix `touch` option to behave consistently with `Persistence#touch` method.
*Ryuta Kamizono*
* Migrations raise when duplicate column definition.
Fixes #33024.
*Federico Martinez*
2018-06-10 07:39:10 -04:00
* Bump minimum SQLite version to 3.8
*Yasuo Honda*
* Fix parent record should not get saved with duplicate children records.
Fixes #32940.
*Santosh Wadghule*
* Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur.
*Brian Durand*
* Ensure `Associations::CollectionAssociation#size` and `Associations::CollectionAssociation#empty?`
use loaded association ids if present.
*Graham Turner*
* Add support to preload associations of polymorphic associations when not all the records have the requested associations.
*Dana Sherson*
* Add `touch_all` method to `ActiveRecord::Relation`.
Example:
Person.where(name: "David").touch_all(time: Time.new(2020, 5, 16, 0, 0, 0))
*fatkodima*, *duggiefresh*
* Add `ActiveRecord::Base.base_class?` predicate.
2018-04-02 07:17:24 -04:00
*Bogdan Gusiev*
* Add custom prefix/suffix options to `ActiveRecord::Store.store_accessor`.
*Tan Huynh*, *Yukio Mizuta*
* Rails 6 requires Ruby 2.5.0 or newer.
*Jeremy Daer*, *Kasper Timm Hansen*
* Deprecate `update_attributes`/`!` in favor of `update`/`!`.
*Eddie Lebow*
* 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.
*DHH*
* Add `Relation#pick` as short-hand for single-value plucks.
*DHH*
Please check [5-2-stable](https://github.com/rails/rails/blob/5-2-stable/activerecord/CHANGELOG.md) for previous changes.