activerecord 6.0.3.3 → 6.1.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (244) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +849 -698
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +2 -2
  5. data/lib/active_record.rb +7 -14
  6. data/lib/active_record/aggregations.rb +5 -5
  7. data/lib/active_record/association_relation.rb +22 -14
  8. data/lib/active_record/associations.rb +118 -11
  9. data/lib/active_record/associations/alias_tracker.rb +19 -15
  10. data/lib/active_record/associations/association.rb +44 -28
  11. data/lib/active_record/associations/association_scope.rb +19 -15
  12. data/lib/active_record/associations/belongs_to_association.rb +22 -8
  13. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +8 -3
  14. data/lib/active_record/associations/builder/association.rb +9 -3
  15. data/lib/active_record/associations/builder/belongs_to.rb +10 -7
  16. data/lib/active_record/associations/builder/collection_association.rb +5 -4
  17. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +0 -1
  18. data/lib/active_record/associations/builder/has_many.rb +6 -2
  19. data/lib/active_record/associations/builder/has_one.rb +11 -14
  20. data/lib/active_record/associations/builder/singular_association.rb +1 -1
  21. data/lib/active_record/associations/collection_association.rb +19 -6
  22. data/lib/active_record/associations/collection_proxy.rb +13 -5
  23. data/lib/active_record/associations/foreign_association.rb +13 -0
  24. data/lib/active_record/associations/has_many_association.rb +24 -2
  25. data/lib/active_record/associations/has_many_through_association.rb +10 -4
  26. data/lib/active_record/associations/has_one_association.rb +15 -1
  27. data/lib/active_record/associations/join_dependency.rb +72 -50
  28. data/lib/active_record/associations/join_dependency/join_association.rb +39 -16
  29. data/lib/active_record/associations/join_dependency/join_part.rb +3 -3
  30. data/lib/active_record/associations/preloader.rb +11 -5
  31. data/lib/active_record/associations/preloader/association.rb +51 -25
  32. data/lib/active_record/associations/preloader/through_association.rb +2 -2
  33. data/lib/active_record/associations/singular_association.rb +1 -1
  34. data/lib/active_record/associations/through_association.rb +1 -1
  35. data/lib/active_record/attribute_assignment.rb +10 -8
  36. data/lib/active_record/attribute_methods.rb +64 -54
  37. data/lib/active_record/attribute_methods/before_type_cast.rb +13 -9
  38. data/lib/active_record/attribute_methods/dirty.rb +1 -11
  39. data/lib/active_record/attribute_methods/primary_key.rb +6 -2
  40. data/lib/active_record/attribute_methods/query.rb +3 -6
  41. data/lib/active_record/attribute_methods/read.rb +8 -11
  42. data/lib/active_record/attribute_methods/serialization.rb +11 -5
  43. data/lib/active_record/attribute_methods/time_zone_conversion.rb +12 -13
  44. data/lib/active_record/attribute_methods/write.rb +12 -20
  45. data/lib/active_record/attributes.rb +33 -8
  46. data/lib/active_record/autosave_association.rb +57 -40
  47. data/lib/active_record/base.rb +2 -14
  48. data/lib/active_record/callbacks.rb +152 -22
  49. data/lib/active_record/coders/yaml_column.rb +1 -1
  50. data/lib/active_record/connection_adapters.rb +50 -0
  51. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +191 -134
  52. data/lib/active_record/connection_adapters/abstract/database_limits.rb +2 -44
  53. data/lib/active_record/connection_adapters/abstract/database_statements.rb +65 -22
  54. data/lib/active_record/connection_adapters/abstract/query_cache.rb +2 -7
  55. data/lib/active_record/connection_adapters/abstract/quoting.rb +34 -34
  56. data/lib/active_record/connection_adapters/abstract/savepoints.rb +3 -3
  57. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +153 -116
  58. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +112 -27
  59. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +3 -3
  60. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +228 -83
  61. data/lib/active_record/connection_adapters/abstract/transaction.rb +80 -32
  62. data/lib/active_record/connection_adapters/abstract_adapter.rb +54 -71
  63. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +129 -88
  64. data/lib/active_record/connection_adapters/column.rb +15 -1
  65. data/lib/active_record/connection_adapters/deduplicable.rb +29 -0
  66. data/lib/active_record/connection_adapters/legacy_pool_manager.rb +31 -0
  67. data/lib/active_record/connection_adapters/mysql/database_statements.rb +23 -25
  68. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +1 -1
  69. data/lib/active_record/connection_adapters/mysql/quoting.rb +1 -1
  70. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +32 -6
  71. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +8 -0
  72. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +1 -1
  73. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +11 -7
  74. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +10 -1
  75. data/lib/active_record/connection_adapters/mysql2_adapter.rb +31 -12
  76. data/lib/active_record/connection_adapters/pool_config.rb +63 -0
  77. data/lib/active_record/connection_adapters/pool_manager.rb +43 -0
  78. data/lib/active_record/connection_adapters/postgresql/column.rb +24 -1
  79. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +13 -54
  80. data/lib/active_record/connection_adapters/postgresql/oid.rb +2 -0
  81. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +3 -5
  82. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +2 -2
  83. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +10 -2
  84. data/lib/active_record/connection_adapters/postgresql/oid/interval.rb +49 -0
  85. data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +2 -2
  86. data/lib/active_record/connection_adapters/postgresql/oid/macaddr.rb +25 -0
  87. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +2 -2
  88. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +24 -5
  89. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +11 -1
  90. data/lib/active_record/connection_adapters/postgresql/quoting.rb +4 -4
  91. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +1 -1
  92. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +5 -1
  93. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +61 -29
  94. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +8 -0
  95. data/lib/active_record/connection_adapters/postgresql_adapter.rb +72 -55
  96. data/lib/active_record/connection_adapters/schema_cache.rb +98 -15
  97. data/lib/active_record/connection_adapters/sql_type_metadata.rb +10 -0
  98. data/lib/active_record/connection_adapters/sqlite3/database_statements.rb +31 -6
  99. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +1 -1
  100. data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +5 -1
  101. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +37 -4
  102. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +49 -50
  103. data/lib/active_record/connection_handling.rb +210 -71
  104. data/lib/active_record/core.rb +229 -63
  105. data/lib/active_record/database_configurations.rb +124 -85
  106. data/lib/active_record/database_configurations/connection_url_resolver.rb +98 -0
  107. data/lib/active_record/database_configurations/database_config.rb +52 -9
  108. data/lib/active_record/database_configurations/hash_config.rb +54 -8
  109. data/lib/active_record/database_configurations/url_config.rb +15 -40
  110. data/lib/active_record/delegated_type.rb +209 -0
  111. data/lib/active_record/destroy_association_async_job.rb +36 -0
  112. data/lib/active_record/enum.rb +75 -37
  113. data/lib/active_record/errors.rb +47 -12
  114. data/lib/active_record/explain.rb +9 -4
  115. data/lib/active_record/explain_subscriber.rb +1 -1
  116. data/lib/active_record/fixture_set/file.rb +10 -17
  117. data/lib/active_record/fixture_set/model_metadata.rb +1 -2
  118. data/lib/active_record/fixture_set/render_context.rb +1 -1
  119. data/lib/active_record/fixture_set/table_row.rb +2 -2
  120. data/lib/active_record/fixtures.rb +58 -9
  121. data/lib/active_record/gem_version.rb +3 -3
  122. data/lib/active_record/inheritance.rb +40 -18
  123. data/lib/active_record/insert_all.rb +35 -6
  124. data/lib/active_record/integration.rb +3 -5
  125. data/lib/active_record/internal_metadata.rb +16 -7
  126. data/lib/active_record/legacy_yaml_adapter.rb +7 -3
  127. data/lib/active_record/locking/optimistic.rb +22 -16
  128. data/lib/active_record/locking/pessimistic.rb +6 -2
  129. data/lib/active_record/log_subscriber.rb +26 -8
  130. data/lib/active_record/middleware/database_selector.rb +4 -1
  131. data/lib/active_record/middleware/database_selector/resolver.rb +5 -0
  132. data/lib/active_record/middleware/database_selector/resolver/session.rb +3 -0
  133. data/lib/active_record/migration.rb +113 -83
  134. data/lib/active_record/migration/command_recorder.rb +47 -27
  135. data/lib/active_record/migration/compatibility.rb +68 -17
  136. data/lib/active_record/model_schema.rb +117 -13
  137. data/lib/active_record/nested_attributes.rb +2 -3
  138. data/lib/active_record/no_touching.rb +1 -1
  139. data/lib/active_record/persistence.rb +50 -45
  140. data/lib/active_record/query_cache.rb +15 -5
  141. data/lib/active_record/querying.rb +11 -6
  142. data/lib/active_record/railtie.rb +64 -44
  143. data/lib/active_record/railties/databases.rake +276 -99
  144. data/lib/active_record/readonly_attributes.rb +4 -0
  145. data/lib/active_record/reflection.rb +71 -57
  146. data/lib/active_record/relation.rb +96 -67
  147. data/lib/active_record/relation/batches.rb +38 -31
  148. data/lib/active_record/relation/batches/batch_enumerator.rb +25 -9
  149. data/lib/active_record/relation/calculations.rb +101 -44
  150. data/lib/active_record/relation/delegation.rb +2 -1
  151. data/lib/active_record/relation/finder_methods.rb +45 -15
  152. data/lib/active_record/relation/from_clause.rb +1 -1
  153. data/lib/active_record/relation/merger.rb +27 -25
  154. data/lib/active_record/relation/predicate_builder.rb +59 -38
  155. data/lib/active_record/relation/predicate_builder/array_handler.rb +8 -9
  156. data/lib/active_record/relation/predicate_builder/association_query_value.rb +4 -5
  157. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +8 -6
  158. data/lib/active_record/relation/predicate_builder/relation_handler.rb +1 -1
  159. data/lib/active_record/relation/query_methods.rb +333 -195
  160. data/lib/active_record/relation/record_fetch_warning.rb +3 -3
  161. data/lib/active_record/relation/spawn_methods.rb +8 -7
  162. data/lib/active_record/relation/where_clause.rb +104 -57
  163. data/lib/active_record/result.rb +41 -33
  164. data/lib/active_record/runtime_registry.rb +2 -2
  165. data/lib/active_record/sanitization.rb +6 -17
  166. data/lib/active_record/schema_dumper.rb +34 -4
  167. data/lib/active_record/schema_migration.rb +2 -8
  168. data/lib/active_record/scoping/named.rb +6 -17
  169. data/lib/active_record/secure_token.rb +16 -8
  170. data/lib/active_record/serialization.rb +5 -3
  171. data/lib/active_record/signed_id.rb +116 -0
  172. data/lib/active_record/statement_cache.rb +20 -4
  173. data/lib/active_record/store.rb +2 -2
  174. data/lib/active_record/suppressor.rb +2 -2
  175. data/lib/active_record/table_metadata.rb +42 -51
  176. data/lib/active_record/tasks/database_tasks.rb +140 -113
  177. data/lib/active_record/tasks/mysql_database_tasks.rb +34 -35
  178. data/lib/active_record/tasks/postgresql_database_tasks.rb +24 -26
  179. data/lib/active_record/tasks/sqlite_database_tasks.rb +13 -9
  180. data/lib/active_record/test_databases.rb +5 -4
  181. data/lib/active_record/test_fixtures.rb +37 -16
  182. data/lib/active_record/timestamp.rb +4 -6
  183. data/lib/active_record/touch_later.rb +21 -21
  184. data/lib/active_record/transactions.rb +19 -66
  185. data/lib/active_record/type.rb +8 -1
  186. data/lib/active_record/type/serialized.rb +6 -2
  187. data/lib/active_record/type/time.rb +10 -0
  188. data/lib/active_record/type_caster/connection.rb +0 -1
  189. data/lib/active_record/type_caster/map.rb +8 -5
  190. data/lib/active_record/validations.rb +1 -0
  191. data/lib/active_record/validations/numericality.rb +35 -0
  192. data/lib/active_record/validations/uniqueness.rb +24 -4
  193. data/lib/arel.rb +5 -13
  194. data/lib/arel/attributes/attribute.rb +4 -0
  195. data/lib/arel/collectors/bind.rb +5 -0
  196. data/lib/arel/collectors/composite.rb +8 -0
  197. data/lib/arel/collectors/sql_string.rb +7 -0
  198. data/lib/arel/collectors/substitute_binds.rb +7 -0
  199. data/lib/arel/nodes.rb +3 -1
  200. data/lib/arel/nodes/binary.rb +82 -8
  201. data/lib/arel/nodes/bind_param.rb +8 -0
  202. data/lib/arel/nodes/casted.rb +21 -9
  203. data/lib/arel/nodes/equality.rb +6 -9
  204. data/lib/arel/nodes/grouping.rb +3 -0
  205. data/lib/arel/nodes/homogeneous_in.rb +72 -0
  206. data/lib/arel/nodes/in.rb +8 -1
  207. data/lib/arel/nodes/infix_operation.rb +13 -1
  208. data/lib/arel/nodes/join_source.rb +1 -1
  209. data/lib/arel/nodes/node.rb +7 -6
  210. data/lib/arel/nodes/ordering.rb +27 -0
  211. data/lib/arel/nodes/sql_literal.rb +3 -0
  212. data/lib/arel/nodes/table_alias.rb +7 -3
  213. data/lib/arel/nodes/unary.rb +0 -1
  214. data/lib/arel/predications.rb +12 -18
  215. data/lib/arel/select_manager.rb +1 -2
  216. data/lib/arel/table.rb +13 -5
  217. data/lib/arel/visitors.rb +0 -7
  218. data/lib/arel/visitors/dot.rb +14 -2
  219. data/lib/arel/visitors/mysql.rb +11 -1
  220. data/lib/arel/visitors/postgresql.rb +15 -4
  221. data/lib/arel/visitors/to_sql.rb +89 -78
  222. data/lib/rails/generators/active_record/migration.rb +6 -1
  223. data/lib/rails/generators/active_record/migration/migration_generator.rb +1 -0
  224. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +2 -0
  225. data/lib/rails/generators/active_record/migration/templates/migration.rb.tt +3 -3
  226. data/lib/rails/generators/active_record/model/model_generator.rb +39 -2
  227. data/lib/rails/generators/active_record/model/templates/abstract_base_class.rb.tt +7 -0
  228. metadata +28 -29
  229. data/lib/active_record/advisory_lock_base.rb +0 -18
  230. data/lib/active_record/attribute_decorators.rb +0 -88
  231. data/lib/active_record/connection_adapters/connection_specification.rb +0 -296
  232. data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +0 -29
  233. data/lib/active_record/define_callbacks.rb +0 -22
  234. data/lib/active_record/railties/collection_cache_association_loading.rb +0 -34
  235. data/lib/active_record/relation/predicate_builder/base_handler.rb +0 -18
  236. data/lib/active_record/relation/where_clause_factory.rb +0 -33
  237. data/lib/arel/attributes.rb +0 -22
  238. data/lib/arel/visitors/depth_first.rb +0 -203
  239. data/lib/arel/visitors/ibm_db.rb +0 -34
  240. data/lib/arel/visitors/informix.rb +0 -62
  241. data/lib/arel/visitors/mssql.rb +0 -156
  242. data/lib/arel/visitors/oracle.rb +0 -158
  243. data/lib/arel/visitors/oracle12.rb +0 -65
  244. data/lib/arel/visitors/where_sql.rb +0 -22
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 43d89875f8d056e835693f2de4407d7dd29663f082c0980e867630982a379b06
4
- data.tar.gz: daf30755f9d5ea1a4475a4505a2281aa93f03334647adfada498eec3ffdfcfa5
3
+ metadata.gz: 56f128436e13685f9715b6dbe295150f61a11e7af686fc5d758044f080fe1879
4
+ data.tar.gz: b80991c1de4020e4e770f64464683e6e3cd88f38dbc93e8909c270ade9f32d20
5
5
  SHA512:
6
- metadata.gz: 795fba3abadc92e73cf780fc801bc43a8e6c7368d1cfc6be89e87be171c51fa648fdf8d06c38143f51983de1c61a4c3f3cb723058369584111aa8f7d48e5246e
7
- data.tar.gz: 680c6072a512dc581ce675fbea15bc7f585c9c650ec96fd45e95b57c0ea89db0e499076886e04eafe8563c955199c9d2078a6072dc55386d600457521e4f4e1a
6
+ metadata.gz: 10f8bd5fccf212ad4807ae6c08a8264333af73373606dce2eb2338e2f6edcfa7469351f5a905836e4be6764548e580d0c205564c8aa2493cbb1476f02ed555a4
7
+ data.tar.gz: 2ff2988d43a99595a0a14d796afeca8aa53b54a8f7e516721a026a053cdc7bb0c23fcf934d180a165023b58c5e9335d42bb1c0e0b9daf1b6df078c1e969fc8c1
@@ -1,1212 +1,1363 @@
1
- ## Rails 6.0.3.3 (September 09, 2020) ##
1
+ ## Rails 6.1.1 (January 07, 2021) ##
2
2
 
3
- * No changes.
3
+ * Fix fixtures loading when strict loading is enabled for the association.
4
4
 
5
+ *Alex Ghiculescu*
5
6
 
6
- ## Rails 6.0.3.2 (June 17, 2020) ##
7
+ * Fix `where` with custom primary key for belongs_to association.
7
8
 
8
- * No changes.
9
+ *Ryuta Kamizono*
9
10
 
11
+ * Fix `where` with aliased associations.
10
12
 
11
- ## Rails 6.0.3.1 (May 18, 2020) ##
13
+ *Ryuta Kamizono*
12
14
 
13
- * No changes.
15
+ * Fix `composed_of` with symbol mapping.
14
16
 
17
+ *Ryuta Kamizono*
15
18
 
16
- ## Rails 6.0.3 (May 06, 2020) ##
19
+ * Don't skip money's type cast for pluck and calculations.
17
20
 
18
- * Recommend applications don't use the `database` kwarg in `connected_to`
21
+ *Ryuta Kamizono*
19
22
 
20
- The database kwarg in `connected_to` was meant to be used for one-off scripts but is often used in requests. This is really dangerous because it re-establishes a connection every time. It's deprecated in 6.1 and will be removed in 6.2 without replacement. This change soft deprecates it in 6.0 by removing documentation.
23
+ * Fix `where` on polymorphic association with non Active Record object.
21
24
 
22
- *Eileen M. Uchitelle*
25
+ *Ryuta Kamizono*
23
26
 
24
- * Fix support for PostgreSQL 11+ partitioned indexes.
27
+ * Make sure `db:prepare` works even the schema file doesn't exist.
25
28
 
26
- *Sebastián Palma*
29
+ *Rafael Mendonça França*
27
30
 
28
- * Add support for beginless ranges, introduced in Ruby 2.7.
31
+ * Fix complicated `has_many :through` with nested where condition.
29
32
 
30
- *Josh Goodall*
33
+ *Ryuta Kamizono*
31
34
 
32
- * Fix insert_all with enum values
35
+ * Handle STI models for `has_many dependent: :destroy_async`.
33
36
 
34
- Fixes #38716.
37
+ *Muhammad Usman*
35
38
 
36
- *Joel Blum*
39
+ * Restore possibility of passing `false` to :polymorphic option of `belongs_to`.
37
40
 
38
- * Regexp-escape table name for MS SQL
41
+ Previously, passing `false` would trigger the option validation logic
42
+ to throw an error saying :polymorphic would not be a valid option.
39
43
 
40
- Add `Regexp.escape` to one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods like `pluck` and `select` fail in certain cases when used with the MS SQL Server adapter.
44
+ *glaszig*
41
45
 
42
- *Larry Reid*
46
+ * Allow adding nonnamed expression indexes to be revertible.
43
47
 
44
- * Store advisory locks on their own named connection.
48
+ Fixes #40732.
45
49
 
46
- Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.
50
+ Previously, the following code would raise an error, when executed while rolling back,
51
+ and the index name should be specified explicitly. Now, the index name is inferred
52
+ automatically.
47
53
 
48
- In order to fix this we are storing the advisory lock on a new connection with the connection specification name `AdisoryLockBase`. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.
54
+ ```ruby
55
+ add_index(:items, "to_tsvector('english', description)")
56
+ ```
49
57
 
50
- *Eileen M. Uchitelle*, *John Crepezzi*
58
+ *fatkodima*
51
59
 
52
- * Ensure `:reading` connections always raise if a write is attempted.
53
60
 
54
- Now Rails will raise an `ActiveRecord::ReadOnlyError` if any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than `:reading`.
61
+ ## Rails 6.1.0 (December 09, 2020) ##
55
62
 
56
- *Eileen M. Uchitelle*
63
+ * Only warn about negative enums if a positive form that would cause conflicts exists.
57
64
 
58
- * Enforce fresh ETag header after a collection's contents change by adding
59
- ActiveRecord::Relation#cache_key_with_version. This method will be used by
60
- ActionController::ConditionalGet to ensure that when collection cache versioning
61
- is enabled, requests using ConditionalGet don't return the same ETag header
62
- after a collection is modified. Fixes #38078.
65
+ Fixes #39065.
63
66
 
64
- *Aaron Lipman*
67
+ *Alex Ghiculescu*
65
68
 
66
- * A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgresSQL `options`.
69
+ * Change `attribute_for_inspect` to take `filter_attributes` in consideration.
67
70
 
68
- *Joshua Flanagan*
71
+ *Rafael Mendonça França*
69
72
 
70
- * Retain explicit selections on the base model after applying `includes` and `joins`.
73
+ * Fix odd behavior of inverse_of with multiple belongs_to to same class.
71
74
 
72
- Resolves #34889.
75
+ Fixes #35204.
73
76
 
74
- *Patrick Rebsch*
77
+ *Tomoyuki Kai*
75
78
 
79
+ * Build predicate conditions with objects that delegate `#id` and primary key:
76
80
 
77
- ## Rails 6.0.2.2 (March 19, 2020) ##
81
+ ```ruby
82
+ class AdminAuthor
83
+ delegate_missing_to :@author
78
84
 
79
- * No changes.
85
+ def initialize(author)
86
+ @author = author
87
+ end
88
+ end
80
89
 
90
+ Post.where(author: AdminAuthor.new(author))
91
+ ```
81
92
 
82
- ## Rails 6.0.2.1 (December 18, 2019) ##
93
+ *Sean Doyle*
83
94
 
84
- * No changes.
95
+ * Add `connected_to_many` API.
85
96
 
97
+ This API allows applications to connect to multiple databases at once without switching all of them or implementing a deeply nested stack.
86
98
 
87
- ## Rails 6.0.2 (December 13, 2019) ##
99
+ Before:
88
100
 
89
- * Share the same connection pool for primary and replica databases in the
90
- transactional tests for the same database.
101
+ AnimalsRecord.connected_to(role: :reading) do
102
+ MealsRecord.connected_to(role: :reading) do
103
+ Dog.first # read from animals replica
104
+ Dinner.first # read from meals replica
105
+ Person.first # read from primary writer
106
+ end
107
+ end
91
108
 
92
- *Edouard Chin*
109
+ After:
93
110
 
94
- * Fix the preloader when one record is fetched using `after_initialize`
95
- but not the entire collection.
111
+ ActiveRecord::Base.connected_to_many([AnimalsRecord, MealsRecord], role: :reading) do
112
+ Dog.first # read from animals replica
113
+ Dinner.first # read from meals replica
114
+ Person.first # read from primary writer
115
+ end
96
116
 
97
- *Bradley Price*
117
+ *Eileen M. Uchitelle*, *John Crepezzi*
98
118
 
99
- * Fix collection callbacks not terminating when `:abort` is thrown.
119
+ * Add option to raise or log for `ActiveRecord::StrictLoadingViolationError`.
100
120
 
101
- *Edouard Chin*, *Ryuta Kamizono*
121
+ Some applications may not want to raise an error in production if using `strict_loading`. This would allow an application to set strict loading to log for the production environment while still raising in development and test environments.
102
122
 
103
- * Correctly deprecate `where.not` working as NOR for relations.
123
+ Set `config.active_record.action_on_strict_loading_violation` to `:log` errors instead of raising.
104
124
 
105
- 12a9664 deprecated where.not working as NOR, however
106
- doing a relation query like `where.not(relation: { ... })`
107
- wouldn't be properly deprecated and `where.not` would work as
108
- NAND instead.
125
+ *Eileen M. Uchitelle*
109
126
 
110
- *Edouard Chin*
127
+ * Allow the inverse of a `has_one` association that was previously autosaved to be loaded.
111
128
 
112
- * Fix `db:migrate` task with multiple databases to restore the connection
113
- to the previous database.
129
+ Fixes #34255.
114
130
 
115
- The migrate task iterates and establish a connection over each db
116
- resulting in the last one to be used by subsequent rake tasks.
117
- We should reestablish a connection to the connection that was
118
- established before the migrate tasks was run
131
+ *Steven Weber*
119
132
 
120
- *Edouard Chin*
133
+ * Optimise the length of index names for polymorphic references by using the reference name rather than the type and id column names.
121
134
 
122
- * Fix multi-threaded issue for `AcceptanceValidator`.
135
+ Because the default behaviour when adding an index with multiple columns is to use all column names in the index name, this could frequently lead to overly long index names for polymorphic references which would fail the migration if it exceeded the database limit.
123
136
 
124
- *Ryuta Kamizono*
137
+ This change reduces the chance of that happening by using the reference name, e.g. `index_my_table_on_my_reference`.
125
138
 
139
+ Fixes #38655.
126
140
 
127
- ## Rails 6.0.1 (November 5, 2019) ##
141
+ *Luke Redpath*
128
142
 
129
- * Common Table Expressions are allowed on read-only connections.
143
+ * MySQL: Uniqueness validator now respects default database collation,
144
+ no longer enforce case sensitive comparison by default.
130
145
 
131
- *Chris Morris*
146
+ *Ryuta Kamizono*
132
147
 
133
- * New record instantiation respects `unscope`.
148
+ * Remove deprecated methods from `ActiveRecord::ConnectionAdapters::DatabaseLimits`.
134
149
 
135
- *Ryuta Kamizono*
150
+ `column_name_length`
151
+ `table_name_length`
152
+ `columns_per_table`
153
+ `indexes_per_table`
154
+ `columns_per_multicolumn_index`
155
+ `sql_query_length`
156
+ `joins_per_query`
136
157
 
137
- * Fixed a case where `find_in_batches` could halt too early.
158
+ *Rafael Mendonça França*
138
159
 
139
- *Takayuki Nakata*
160
+ * Remove deprecated `ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_multi_insert?`.
140
161
 
141
- * Autosaved associations always perform validations when a custom validation
142
- context is used.
162
+ *Rafael Mendonça França*
143
163
 
144
- *Tekin Suleyman*
164
+ * Remove deprecated `ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_foreign_keys_in_create?`.
145
165
 
146
- * `sql.active_record` notifications now include the `:connection` in
147
- their payloads.
166
+ *Rafael Mendonça França*
148
167
 
149
- *Eugene Kenny*
168
+ * Remove deprecated `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#supports_ranges?`.
150
169
 
151
- * A rollback encountered in an `after_commit` callback does not reset
152
- previously-committed record state.
170
+ *Rafael Mendonça França*
153
171
 
154
- *Ryuta Kamizono*
172
+ * Remove deprecated `ActiveRecord::Base#update_attributes` and `ActiveRecord::Base#update_attributes!`.
155
173
 
156
- * Fixed that join order was lost when eager-loading.
174
+ *Rafael Mendonça França*
157
175
 
158
- *Ryuta Kamizono*
176
+ * Remove deprecated `migrations_path` argument in `ActiveRecord::ConnectionAdapter::SchemaStatements#assume_migrated_upto_version`.
159
177
 
160
- * `DESCRIBE` queries are allowed on read-only connections.
178
+ *Rafael Mendonça França*
161
179
 
162
- *Dylan Thacker-Smith*
180
+ * Remove deprecated `config.active_record.sqlite3.represent_boolean_as_integer`.
163
181
 
164
- * Fixed that records that had been `inspect`ed could not be marshaled.
182
+ *Rafael Mendonça França*
165
183
 
166
- *Eugene Kenny*
184
+ * `relation.create` does no longer leak scope to class level querying methods
185
+ in initialization block and callbacks.
167
186
 
168
- * The connection pool reaper thread is respawned in forked processes. This
169
- fixes that idle connections in forked processes wouldn't be reaped.
187
+ Before:
170
188
 
171
- *John Hawthorn*
189
+ User.where(name: "John").create do |john|
190
+ User.find_by(name: "David") # => nil
191
+ end
172
192
 
173
- * The memoized result of `ActiveRecord::Relation#take` is properly cleared
174
- when `ActiveRecord::Relation#reset` or `ActiveRecord::Relation#reload`
175
- is called.
193
+ After:
176
194
 
177
- *Anmol Arora*
195
+ User.where(name: "John").create do |john|
196
+ User.find_by(name: "David") # => #<User name: "David", ...>
197
+ end
178
198
 
179
- * Fixed the performance regression for `primary_keys` introduced MySQL 8.0.
199
+ *Ryuta Kamizono*
180
200
 
181
- *Hiroyuki Ishii*
201
+ * Named scope chain does no longer leak scope to class level querying methods.
182
202
 
183
- * `insert`, `insert_all`, `upsert`, and `upsert_all` now clear the query cache.
203
+ class User < ActiveRecord::Base
204
+ scope :david, -> { User.where(name: "David") }
205
+ end
184
206
 
185
- *Eugene Kenny*
207
+ Before:
186
208
 
187
- * Call `while_preventing_writes` directly from `connected_to`.
209
+ User.where(name: "John").david
210
+ # SELECT * FROM users WHERE name = 'John' AND name = 'David'
188
211
 
189
- In some cases application authors want to use the database switching middleware and make explicit calls with `connected_to`. It's possible for an app to turn off writes and not turn them back on by the time we call `connected_to(role: :writing)`.
212
+ After:
190
213
 
191
- This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.
214
+ User.where(name: "John").david
215
+ # SELECT * FROM users WHERE name = 'David'
192
216
 
193
- *Eileen M. Uchitelle*
217
+ *Ryuta Kamizono*
194
218
 
195
- * Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.
219
+ * Remove deprecated methods from `ActiveRecord::DatabaseConfigurations`.
196
220
 
197
- *Kir Shatrov*
221
+ `fetch`
222
+ `each`
223
+ `first`
224
+ `values`
225
+ `[]=`
198
226
 
227
+ *Rafael Mendonça França*
199
228
 
200
- ## Rails 6.0.0 (August 16, 2019) ##
229
+ * `where.not` now generates NAND predicates instead of NOR.
201
230
 
202
- * Preserve user supplied joins order as much as possible.
231
+ Before:
203
232
 
204
- Fixes #36761, #34328, #24281, #12953.
233
+ User.where.not(name: "Jon", role: "admin")
234
+ # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
205
235
 
206
- *Ryuta Kamizono*
236
+ After:
207
237
 
208
- * Make the DATABASE_URL env variable only affect the primary connection. Add new env variables for multiple databases.
238
+ User.where.not(name: "Jon", role: "admin")
239
+ # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin')
209
240
 
210
- *John Crepezzi*, *Eileen Uchitelle*
241
+ *Rafael Mendonça França*
211
242
 
212
- * Add a warning for enum elements with 'not_' prefix.
243
+ * Remove deprecated `ActiveRecord::Result#to_hash` method.
213
244
 
214
- class Foo
215
- enum status: [:sent, :not_sent]
216
- end
245
+ *Rafael Mendonça França*
217
246
 
218
- *Edu Depetris*
247
+ * Deprecate `ActiveRecord::Base.allow_unsafe_raw_sql`.
219
248
 
220
- * Make currency symbols optional for money column type in PostgreSQL
249
+ *Rafael Mendonça França*
221
250
 
222
- *Joel Schneider*
251
+ * Remove deprecated support for using unsafe raw SQL in `ActiveRecord::Relation` methods.
223
252
 
253
+ *Rafael Mendonça França*
224
254
 
225
- ## Rails 6.0.0.rc2 (July 22, 2019) ##
255
+ * Allow users to silence the "Rails couldn't infer whether you are using multiple databases..."
256
+ message using `config.active_record.suppress_multiple_database_warning`.
226
257
 
227
- * Add database_exists? method to connection adapters to check if a database exists.
258
+ *Omri Gabay*
228
259
 
229
- *Guilherme Mansur*
260
+ * Connections can be granularly switched for abstract classes when `connected_to` is called.
230
261
 
231
- * PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
262
+ This change allows `connected_to` to switch a `role` and/or `shard` for a single abstract class instead of all classes globally. Applications that want to use the new feature need to set `config.active_record.legacy_connection_handling` to `false` in their application configuration.
232
263
 
233
- Fixes #36022.
264
+ Example usage:
234
265
 
235
- *Ryuta Kamizono*
266
+ Given an application we have a `User` model that inherits from `ApplicationRecord` and a `Dog` model that inherits from `AnimalsRecord`. `AnimalsRecord` and `ApplicationRecord` have writing and reading connections as well as shard `default`, `one`, and `two`.
236
267
 
237
- * Make ActiveRecord `ConnectionPool.connections` method thread-safe.
268
+ ```ruby
269
+ ActiveRecord::Base.connected_to(role: :reading) do
270
+ User.first # reads from default replica
271
+ Dog.first # reads from default replica
238
272
 
239
- Fixes #36465.
273
+ AnimalsRecord.connected_to(role: :writing, shard: :one) do
274
+ User.first # reads from default replica
275
+ Dog.first # reads from shard one primary
276
+ end
240
277
 
241
- *Jeff Doering*
278
+ User.first # reads from default replica
279
+ Dog.first # reads from default replica
242
280
 
243
- * Fix sqlite3 collation parsing when using decimal columns.
281
+ ApplicationRecord.connected_to(role: :writing, shard: :two) do
282
+ User.first # reads from shard two primary
283
+ Dog.first # reads from default replica
284
+ end
285
+ end
286
+ ```
244
287
 
245
- *Martin R. Schuster*
288
+ *Eileen M. Uchitelle*, *John Crepezzi*
246
289
 
247
- * Fix invalid schema when primary key column has a comment.
290
+ * Allow double-dash comment syntax when querying read-only databases
248
291
 
249
- Fixes #29966.
292
+ *James Adam*
250
293
 
251
- *Guilherme Goettems Schneider*
294
+ * Add `values_at` method.
252
295
 
253
- * Fix table comment also being applied to the primary key column.
296
+ Returns an array containing the values associated with the given methods.
254
297
 
255
- *Guilherme Goettems Schneider*
298
+ ```ruby
299
+ topic = Topic.first
300
+ topic.values_at(:title, :author_name)
301
+ # => ["Budget", "Jason"]
302
+ ```
256
303
 
257
- * Fix merging left_joins to maintain its own `join_type` context.
304
+ Similar to `Hash#values_at` but on an Active Record instance.
258
305
 
259
- Fixes #36103.
306
+ *Guillaume Briday*
260
307
 
261
- *Ryuta Kamizono*
308
+ * Fix `read_attribute_before_type_cast` to consider attribute aliases.
262
309
 
310
+ *Marcelo Lauxen*
263
311
 
264
- ## Rails 6.0.0.rc1 (April 24, 2019) ##
312
+ * Support passing record to uniqueness validator `:conditions` callable:
265
313
 
266
- * Add `touch` option to `has_one` association.
314
+ ```ruby
315
+ class Article < ApplicationRecord
316
+ validates_uniqueness_of :title, conditions: ->(article) {
317
+ published_at = article.published_at
318
+ where(published_at: published_at.beginning_of_year..published_at.end_of_year)
319
+ }
320
+ end
321
+ ```
267
322
 
268
- *Abhay Nikam*
323
+ *Eliot Sykes*
269
324
 
270
- * Deprecate `where.not` working as NOR and will be changed to NAND in Rails 6.1.
325
+ * `BatchEnumerator#update_all` and `BatchEnumerator#delete_all` now return the
326
+ total number of rows affected, just like their non-batched counterparts.
271
327
 
272
328
  ```ruby
273
- all = [treasures(:diamond), treasures(:sapphire), cars(:honda), treasures(:sapphire)]
274
- assert_equal all, PriceEstimate.all.map(&:estimate_of)
329
+ Person.in_batches.update_all("first_name = 'Eugene'") # => 42
330
+ Person.in_batches.delete_all # => 42
275
331
  ```
276
332
 
277
- In Rails 6.0:
333
+ Fixes #40287.
278
334
 
279
- ```ruby
280
- sapphire = treasures(:sapphire)
281
-
282
- nor = all.reject { |e|
283
- e.estimate_of_type == sapphire.class.polymorphic_name
284
- }.reject { |e|
285
- e.estimate_of_id == sapphire.id
286
- }
287
- assert_equal [cars(:honda)], nor
288
-
289
- without_sapphire = PriceEstimate.where.not(
290
- estimate_of_type: sapphire.class.polymorphic_name, estimate_of_id: sapphire.id
291
- )
292
- assert_equal nor, without_sapphire.map(&:estimate_of)
293
- ```
335
+ *Eugene Kenny*
294
336
 
295
- In Rails 6.1:
337
+ * Add support for PostgreSQL `interval` data type with conversion to
338
+ `ActiveSupport::Duration` when loading records from database and
339
+ serialization to ISO 8601 formatted duration string on save.
340
+ Add support to define a column in migrations and get it in a schema dump.
341
+ Optional column precision is supported.
296
342
 
297
- ```ruby
298
- sapphire = treasures(:sapphire)
343
+ To use this in 6.1, you need to place the next string to your model file:
299
344
 
300
- nand = all - [sapphire]
301
- assert_equal [treasures(:diamond), cars(:honda)], nand
345
+ attribute :duration, :interval
302
346
 
303
- without_sapphire = PriceEstimate.where.not(
304
- estimate_of_type: sapphire.class.polymorphic_name, estimate_of_id: sapphire.id
305
- )
306
- assert_equal nand, without_sapphire.map(&:estimate_of)
307
- ```
347
+ To keep old behavior until 6.2 is released:
308
348
 
309
- *Ryuta Kamizono*
349
+ attribute :duration, :string
310
350
 
311
- * Fix dirty tracking after rollback.
351
+ Example:
312
352
 
313
- Fixes #15018, #30167, #33868.
353
+ create_table :events do |t|
354
+ t.string :name
355
+ t.interval :duration
356
+ end
314
357
 
315
- *Ryuta Kamizono*
358
+ class Event < ApplicationRecord
359
+ attribute :duration, :interval
360
+ end
316
361
 
317
- * Add `ActiveRecord::Relation#cache_version` to support recyclable cache keys via
318
- the versioned entries in `ActiveSupport::Cache`. This also means that
319
- `ActiveRecord::Relation#cache_key` will now return a stable key that does not
320
- include the max timestamp or count any more.
362
+ Event.create!(name: 'Rock Fest', duration: 2.days)
363
+ Event.last.duration # => 2 days
364
+ Event.last.duration.iso8601 # => "P2D"
365
+ Event.new(duration: 'P1DT12H3S').duration # => 1 day, 12 hours, and 3 seconds
366
+ Event.new(duration: '1 day') # Unknown value will be ignored and NULL will be written to database
321
367
 
322
- NOTE: This feature is turned off by default, and `cache_key` will still return
323
- cache keys with timestamps until you set `ActiveRecord::Base.collection_cache_versioning = true`.
324
- That's the setting for all new apps on Rails 6.0+
368
+ *Andrey Novikov*
325
369
 
326
- *Lachlan Sylvester*
370
+ * Allow associations supporting the `dependent:` key to take `dependent: :destroy_async`.
327
371
 
328
- * Fix dirty tracking for `touch` to track saved changes.
372
+ ```ruby
373
+ class Account < ActiveRecord::Base
374
+ belongs_to :supplier, dependent: :destroy_async
375
+ end
376
+ ```
329
377
 
330
- Fixes #33429.
378
+ `:destroy_async` will enqueue a job to destroy associated records in the background.
331
379
 
332
- *Ryuta Kamzono*
380
+ *DHH*, *George Claghorn*, *Cory Gwin*, *Rafael Mendonça França*, *Adrianna Chang*
333
381
 
334
- * `change_column_comment` and `change_table_comment` are invertible only if
335
- `to` and `from` options are specified.
382
+ * Add `SKIP_TEST_DATABASE` environment variable to disable modifying the test database when `rails db:create` and `rails db:drop` are called.
336
383
 
337
- *Yoshiyuki Kinjo*
384
+ *Jason Schweier*
338
385
 
339
- * Don't call commit/rollback callbacks when a record isn't saved.
386
+ * `connects_to` can only be called on `ActiveRecord::Base` or abstract classes.
340
387
 
341
- Fixes #29747.
388
+ Ensure that `connects_to` can only be called from `ActiveRecord::Base` or abstract classes. This protects the application from opening duplicate or too many connections.
342
389
 
343
- *Ryuta Kamizono*
390
+ *Eileen M. Uchitelle*, *John Crepezzi*
344
391
 
345
- * Fix circular `autosave: true` causes invalid records to be saved.
392
+ * All connection adapters `execute` now raises `ActiveRecord::ConnectionNotEstablished` rather than
393
+ `ActiveRecord::StatementInvalid` when they encounter a connection error.
346
394
 
347
- Prior to the fix, when there was a circular series of `autosave: true`
348
- associations, the callback for a `has_many` association was run while
349
- another instance of the same callback on the same association hadn't
350
- finished running. When control returned to the first instance of the
351
- callback, the instance variable had changed, and subsequent associated
352
- records weren't saved correctly. Specifically, the ID field for the
353
- `belongs_to` corresponding to the `has_many` was `nil`.
395
+ *Jean Boussier*
354
396
 
355
- Fixes #28080.
397
+ * `Mysql2Adapter#quote_string` now raises `ActiveRecord::ConnectionNotEstablished` rather than
398
+ `ActiveRecord::StatementInvalid` when it can't connect to the MySQL server.
356
399
 
357
- *Larry Reid*
400
+ *Jean Boussier*
358
401
 
359
- * Raise `ArgumentError` for invalid `:limit` and `:precision` like as other options.
402
+ * Add support for check constraints that are `NOT VALID` via `validate: false` (PostgreSQL-only).
360
403
 
361
- Before:
404
+ *Alex Robbin*
362
405
 
363
- ```ruby
364
- add_column :items, :attr1, :binary, size: 10 # => ArgumentError
365
- add_column :items, :attr2, :decimal, scale: 10 # => ArgumentError
366
- add_column :items, :attr3, :integer, limit: 10 # => ActiveRecordError
367
- add_column :items, :attr4, :datetime, precision: 10 # => ActiveRecordError
368
- ```
406
+ * Ensure the default configuration is considered primary or first for an environment
369
407
 
370
- After:
408
+ If a multiple database application provides a configuration named primary, that will be treated as default. In applications that do not have a primary entry, the default database configuration will be the first configuration for an environment.
409
+
410
+ *Eileen M. Uchitelle*
411
+
412
+ * Allow `where` references association names as joined table name aliases.
371
413
 
372
414
  ```ruby
373
- add_column :items, :attr1, :binary, size: 10 # => ArgumentError
374
- add_column :items, :attr2, :decimal, scale: 10 # => ArgumentError
375
- add_column :items, :attr3, :integer, limit: 10 # => ArgumentError
376
- add_column :items, :attr4, :datetime, precision: 10 # => ArgumentError
415
+ class Comment < ActiveRecord::Base
416
+ enum label: [:default, :child]
417
+ has_many :children, class_name: "Comment", foreign_key: :parent_id
418
+ end
419
+
420
+ # ... FROM comments LEFT OUTER JOIN comments children ON ... WHERE children.label = 1
421
+ Comment.includes(:children).where("children.label": "child")
377
422
  ```
378
423
 
379
424
  *Ryuta Kamizono*
380
425
 
381
- * Association loading isn't to be affected by scoping consistently
382
- whether preloaded / eager loaded or not, with the exception of `unscoped`.
426
+ * Support storing demodulized class name for polymorphic type.
383
427
 
384
- Before:
428
+ Before Rails 6.1, storing demodulized class name is supported only for STI type
429
+ by `store_full_sti_class` class attribute.
430
+
431
+ Now `store_full_class_name` class attribute can handle both STI and polymorphic types.
432
+
433
+ *Ryuta Kamizono*
434
+
435
+ * Deprecate `rails db:structure:{load, dump}` tasks and extend
436
+ `rails db:schema:{load, dump}` tasks to work with either `:ruby` or `:sql` format,
437
+ depending on `config.active_record.schema_format` configuration value.
438
+
439
+ *fatkodima*
440
+
441
+ * Respect the `select` values for eager loading.
385
442
 
386
443
  ```ruby
387
- Post.where("1=0").scoping do
388
- Comment.find(1).post # => nil
389
- Comment.preload(:post).find(1).post # => #<Post id: 1, ...>
390
- Comment.eager_load(:post).find(1).post # => #<Post id: 1, ...>
391
- end
444
+ post = Post.select("UPPER(title) AS title").first
445
+ post.title # => "WELCOME TO THE WEBLOG"
446
+ post.body # => ActiveModel::MissingAttributeError
447
+
448
+ # Rails 6.0 (ignore the `select` values)
449
+ post = Post.select("UPPER(title) AS title").eager_load(:comments).first
450
+ post.title # => "Welcome to the weblog"
451
+ post.body # => "Such a lovely day"
452
+
453
+ # Rails 6.1 (respect the `select` values)
454
+ post = Post.select("UPPER(title) AS title").eager_load(:comments).first
455
+ post.title # => "WELCOME TO THE WEBLOG"
456
+ post.body # => ActiveModel::MissingAttributeError
392
457
  ```
393
458
 
394
- After:
459
+ *Ryuta Kamizono*
460
+
461
+ * Allow attribute's default to be configured but keeping its own type.
395
462
 
396
463
  ```ruby
397
- Post.where("1=0").scoping do
398
- Comment.find(1).post # => #<Post id: 1, ...>
399
- Comment.preload(:post).find(1).post # => #<Post id: 1, ...>
400
- Comment.eager_load(:post).find(1).post # => #<Post id: 1, ...>
464
+ class Post < ActiveRecord::Base
465
+ attribute :written_at, default: -> { Time.now.utc }
401
466
  end
402
- ```
403
467
 
404
- Fixes #34638, #35398.
468
+ # Rails 6.0
469
+ Post.type_for_attribute(:written_at) # => #<Type::Value ... precision: nil, ...>
470
+
471
+ # Rails 6.1
472
+ Post.type_for_attribute(:written_at) # => #<Type::DateTime ... precision: 6, ...>
473
+ ```
405
474
 
406
475
  *Ryuta Kamizono*
407
476
 
408
- * Add `rails db:prepare` to migrate or setup a database.
477
+ * Allow default to be configured for Enum.
409
478
 
410
- Runs `db:migrate` if the database exists or `db:setup` if it doesn't.
479
+ ```ruby
480
+ class Book < ActiveRecord::Base
481
+ enum status: [:proposed, :written, :published], _default: :published
482
+ end
411
483
 
412
- *Roberto Miranda*
484
+ Book.new.status # => "published"
485
+ ```
413
486
 
414
- * Add `after_save_commit` callback as shortcut for `after_commit :hook, on: [ :create, :update ]`.
487
+ *Ryuta Kamizono*
415
488
 
416
- *DHH*
489
+ * Deprecate YAML loading from legacy format older than Rails 5.0.
417
490
 
418
- * Assign all attributes before calling `build` to ensure the child record is visible in
419
- `before_add` and `after_add` callbacks for `has_many :through` associations.
491
+ *Ryuta Kamizono*
420
492
 
421
- Fixes #33249.
493
+ * Added the setting `ActiveRecord::Base.immutable_strings_by_default`, which
494
+ allows you to specify that all string columns should be frozen unless
495
+ otherwise specified. This will reduce memory pressure for applications which
496
+ do not generally mutate string properties of Active Record objects.
422
497
 
423
- *Ryan H. Kerr*
498
+ *Sean Griffin*, *Ryuta Kamizono*
424
499
 
425
- * Add `ActiveRecord::Relation#extract_associated` for extracting associated records from a relation.
500
+ * Deprecate `map!` and `collect!` on `ActiveRecord::Result`.
426
501
 
427
- ```
428
- account.memberships.extract_associated(:user)
429
- # => Returns collection of User records
430
- ```
502
+ *Ryuta Kamizono*
431
503
 
432
- *DHH*
504
+ * Support `relation.and` for intersection as Set theory.
433
505
 
434
- * Add `ActiveRecord::Relation#annotate` for adding SQL comments to its queries.
506
+ ```ruby
507
+ david_and_mary = Author.where(id: [david, mary])
508
+ mary_and_bob = Author.where(id: [mary, bob])
435
509
 
436
- For example:
510
+ david_and_mary.merge(mary_and_bob) # => [mary, bob]
437
511
 
512
+ david_and_mary.and(mary_and_bob) # => [mary]
513
+ david_and_mary.or(mary_and_bob) # => [david, mary, bob]
438
514
  ```
439
- Post.where(id: 123).annotate("this is a comment").to_sql
440
- # SELECT "posts".* FROM "posts" WHERE "posts"."id" = 123 /* this is a comment */
441
- ```
442
-
443
- This can be useful in instrumentation or other analysis of issued queries.
444
515
 
445
- *Matt Yoho*
516
+ *Ryuta Kamizono*
446
517
 
447
- * Support Optimizer Hints.
518
+ * Merging conditions on the same column no longer maintain both conditions,
519
+ and will be consistently replaced by the latter condition in Rails 6.2.
520
+ To migrate to Rails 6.2's behavior, use `relation.merge(other, rewhere: true)`.
448
521
 
449
- In most databases, a way to control the optimizer is by using optimizer hints,
450
- which can be specified within individual statements.
522
+ ```ruby
523
+ # Rails 6.1 (IN clause is replaced by merger side equality condition)
524
+ Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
451
525
 
452
- Example (for MySQL):
526
+ # Rails 6.1 (both conflict conditions exists, deprecated)
527
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
453
528
 
454
- Topic.optimizer_hints("MAX_EXECUTION_TIME(50000)", "NO_INDEX_MERGE(topics)")
455
- # SELECT /*+ MAX_EXECUTION_TIME(50000) NO_INDEX_MERGE(topics) */ `topics`.* FROM `topics`
529
+ # Rails 6.1 with rewhere to migrate to Rails 6.2's behavior
530
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
456
531
 
457
- Example (for PostgreSQL with pg_hint_plan):
532
+ # Rails 6.2 (same behavior with IN clause, mergee side condition is consistently replaced)
533
+ Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
534
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
535
+ ```
458
536
 
459
- Topic.optimizer_hints("SeqScan(topics)", "Parallel(topics 8)")
460
- # SELECT /*+ SeqScan(topics) Parallel(topics 8) */ "topics".* FROM "topics"
537
+ *Ryuta Kamizono*
461
538
 
462
- See also:
539
+ * Do not mark Postgresql MAC address and UUID attributes as changed when the assigned value only varies by case.
463
540
 
464
- * https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html
465
- * https://pghintplan.osdn.jp/pg_hint_plan.html
466
- * https://docs.oracle.com/en/database/oracle/oracle-database/12.2/tgsql/influencing-the-optimizer.html
467
- * https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query?view=sql-server-2017
468
- * https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.perf.doc/doc/c0070117.html
541
+ *Peter Fry*
469
542
 
470
- *Ryuta Kamizono*
543
+ * Resolve issue with insert_all unique_by option when used with expression index.
471
544
 
472
- * Fix query attribute method on user-defined attribute to be aware of typecasted value.
545
+ When the `:unique_by` option of `ActiveRecord::Persistence.insert_all` and
546
+ `ActiveRecord::Persistence.upsert_all` was used with the name of an expression index, an error
547
+ was raised. Adding a guard around the formatting behavior for the `:unique_by` corrects this.
473
548
 
474
- For example, the following code no longer return false as casted non-empty string:
549
+ Usage:
475
550
 
476
- ```
477
- class Post < ActiveRecord::Base
478
- attribute :user_defined_text, :text
551
+ ```ruby
552
+ create_table :books, id: :integer, force: true do |t|
553
+ t.column :name, :string
554
+ t.index "lower(name)", unique: true
479
555
  end
480
556
 
481
- Post.new(user_defined_text: "false").user_defined_text? # => true
557
+ Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_name
482
558
  ```
483
559
 
484
- *Yuji Kamijima*
560
+ Fixes #39516.
485
561
 
486
- * Quote empty ranges like other empty enumerables.
562
+ *Austen Madden*
487
563
 
488
- *Patrick Rebsch*
564
+ * Add basic support for CHECK constraints to database migrations.
489
565
 
490
- * Add `insert_all`/`insert_all!`/`upsert_all` methods to `ActiveRecord::Persistence`,
491
- allowing bulk inserts akin to the bulk updates provided by `update_all` and
492
- bulk deletes by `delete_all`.
566
+ Usage:
493
567
 
494
- Supports skipping or upserting duplicates through the `ON CONFLICT` syntax
495
- for PostgreSQL (9.5+) and SQLite (3.24+) and `ON DUPLICATE KEY UPDATE` syntax
496
- for MySQL.
568
+ ```ruby
569
+ add_check_constraint :products, "price > 0", name: "price_check"
570
+ remove_check_constraint :products, name: "price_check"
571
+ ```
497
572
 
498
- *Bob Lail*
573
+ *fatkodima*
499
574
 
500
- * Add `rails db:seed:replant` that truncates tables of each database
501
- for current environment and loads the seeds.
575
+ * Add `ActiveRecord::Base.strict_loading_by_default` and `ActiveRecord::Base.strict_loading_by_default=`
576
+ to enable/disable strict_loading mode by default for a model. The configuration's value is
577
+ inheritable by subclasses, but they can override that value and it will not impact parent class.
502
578
 
503
- *bogdanvlviv*, *DHH*
579
+ Usage:
504
580
 
505
- * Add `ActiveRecord::Base.connection.truncate` for SQLite3 adapter.
581
+ ```ruby
582
+ class Developer < ApplicationRecord
583
+ self.strict_loading_by_default = true
506
584
 
507
- *bogdanvlviv*
585
+ has_many :projects
586
+ end
587
+
588
+ dev = Developer.first
589
+ dev.projects.first
590
+ # => ActiveRecord::StrictLoadingViolationError Exception: Developer is marked as strict_loading and Project cannot be lazily loaded.
591
+ ```
508
592
 
509
- * Deprecate mismatched collation comparison for uniqueness validator.
593
+ *bogdanvlviv*
510
594
 
511
- Uniqueness validator will no longer enforce case sensitive comparison in Rails 6.1.
512
- To continue case sensitive comparison on the case insensitive column,
513
- pass `case_sensitive: true` option explicitly to the uniqueness validator.
595
+ * Deprecate passing an Active Record object to `quote`/`type_cast` directly.
514
596
 
515
597
  *Ryuta Kamizono*
516
598
 
517
- * Add `reselect` method. This is a short-hand for `unscope(:select).select(fields)`.
599
+ * Default engine `ENGINE=InnoDB` is no longer dumped to make schema more agnostic.
518
600
 
519
- Fixes #27340.
601
+ Before:
520
602
 
521
- *Willian Gustavo Veiga*
603
+ ```ruby
604
+ create_table "accounts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
605
+ end
606
+ ```
522
607
 
523
- * Add negative scopes for all enum values.
608
+ After:
524
609
 
525
- Example:
610
+ ```ruby
611
+ create_table "accounts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
612
+ end
613
+ ```
526
614
 
527
- class Post < ActiveRecord::Base
528
- enum status: %i[ drafted active trashed ]
529
- end
615
+ *Ryuta Kamizono*
530
616
 
531
- Post.not_drafted # => where.not(status: :drafted)
532
- Post.not_active # => where.not(status: :active)
533
- Post.not_trashed # => where.not(status: :trashed)
617
+ * Added delegated type as an alternative to single-table inheritance for representing class hierarchies.
618
+ See ActiveRecord::DelegatedType for the full description.
534
619
 
535
620
  *DHH*
536
621
 
537
- * Fix different `count` calculation when using `size` with manual `select` with DISTINCT.
622
+ * Deprecate aggregations with group by duplicated fields.
538
623
 
539
- Fixes #35214.
624
+ To migrate to Rails 6.2's behavior, use `uniq!(:group)` to deduplicate group fields.
540
625
 
541
- *Juani Villarejo*
626
+ ```ruby
627
+ accounts = Account.group(:firm_id)
628
+
629
+ # duplicated group fields, deprecated.
630
+ accounts.merge(accounts.where.not(credit_limit: nil)).sum(:credit_limit)
631
+ # => {
632
+ # [1, 1] => 50,
633
+ # [2, 2] => 60
634
+ # }
635
+
636
+ # use `uniq!(:group)` to deduplicate group fields.
637
+ accounts.merge(accounts.where.not(credit_limit: nil)).uniq!(:group).sum(:credit_limit)
638
+ # => {
639
+ # 1 => 50,
640
+ # 2 => 60
641
+ # }
642
+ ```
542
643
 
644
+ *Ryuta Kamizono*
543
645
 
544
- ## Rails 6.0.0.beta3 (March 11, 2019) ##
646
+ * Deprecate duplicated query annotations.
545
647
 
546
- * No changes.
648
+ To migrate to Rails 6.2's behavior, use `uniq!(:annotate)` to deduplicate query annotations.
547
649
 
650
+ ```ruby
651
+ accounts = Account.where(id: [1, 2]).annotate("david and mary")
548
652
 
549
- ## Rails 6.0.0.beta2 (February 25, 2019) ##
653
+ # duplicated annotations, deprecated.
654
+ accounts.merge(accounts.rewhere(id: 3))
655
+ # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */ /* david and mary */
550
656
 
551
- * Fix prepared statements caching to be enabled even when query caching is enabled.
657
+ # use `uniq!(:annotate)` to deduplicate annotations.
658
+ accounts.merge(accounts.rewhere(id: 3)).uniq!(:annotate)
659
+ # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */
660
+ ```
552
661
 
553
662
  *Ryuta Kamizono*
554
663
 
555
- * Ensure `update_all` series cares about optimistic locking.
664
+ * Resolve conflict between counter cache and optimistic locking.
556
665
 
557
- *Ryuta Kamizono*
666
+ Bump an Active Record instance's lock version after updating its counter
667
+ cache. This avoids raising an unnecessary `ActiveRecord::StaleObjectError`
668
+ upon subsequent transactions by maintaining parity with the corresponding
669
+ database record's `lock_version` column.
558
670
 
559
- * Don't allow `where` with non numeric string matches to 0 values.
671
+ Fixes #16449.
560
672
 
561
- *Ryuta Kamizono*
673
+ *Aaron Lipman*
562
674
 
563
- * Introduce `ActiveRecord::Relation#destroy_by` and `ActiveRecord::Relation#delete_by`.
675
+ * Support merging option `:rewhere` to allow mergee side condition to be replaced exactly.
564
676
 
565
- `destroy_by` allows relation to find all the records matching the condition and perform
566
- `destroy_all` on the matched records.
677
+ ```ruby
678
+ david_and_mary = Author.where(id: david.id..mary.id)
567
679
 
568
- Example:
680
+ # both conflict conditions exists
681
+ david_and_mary.merge(Author.where(id: bob)) # => []
569
682
 
570
- Person.destroy_by(name: 'David')
571
- Person.destroy_by(name: 'David', rating: 4)
683
+ # mergee side condition is replaced by rewhere
684
+ david_and_mary.merge(Author.rewhere(id: bob)) # => [bob]
572
685
 
573
- david = Person.find_by(name: 'David')
574
- david.posts.destroy_by(id: [1, 2, 3])
686
+ # mergee side condition is replaced by rewhere option
687
+ david_and_mary.merge(Author.where(id: bob), rewhere: true) # => [bob]
688
+ ```
575
689
 
576
- `delete_by` allows relation to find all the records matching the condition and perform
577
- `delete_all` on the matched records.
690
+ *Ryuta Kamizono*
578
691
 
579
- Example:
692
+ * Add support for finding records based on signed ids, which are tamper-proof, verified ids that can be
693
+ set to expire and scoped with a purpose. This is particularly useful for things like password reset
694
+ or email verification, where you want the bearer of the signed id to be able to interact with the
695
+ underlying record, but usually only within a certain time period.
580
696
 
581
- Person.delete_by(name: 'David')
582
- Person.delete_by(name: 'David', rating: 4)
697
+ ```ruby
698
+ signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset
583
699
 
584
- david = Person.find_by(name: 'David')
585
- david.posts.delete_by(id: [1, 2, 3])
700
+ User.find_signed signed_id # => nil, since the purpose does not match
586
701
 
587
- *Abhay Nikam*
702
+ travel 16.minutes
703
+ User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired
588
704
 
589
- * Don't allow `where` with invalid value matches to nil values.
705
+ travel_back
706
+ User.find_signed signed_id, purpose: :password_reset # => User.first
590
707
 
591
- Fixes #33624.
708
+ User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
709
+ ```
592
710
 
593
- *Ryuta Kamizono*
711
+ *DHH*
594
712
 
595
- * SQLite3: Implement `add_foreign_key` and `remove_foreign_key`.
713
+ * Support `ALGORITHM = INSTANT` DDL option for index operations on MySQL.
596
714
 
597
715
  *Ryuta Kamizono*
598
716
 
599
- * Deprecate using class level querying methods if the receiver scope
600
- regarded as leaked. Use `klass.unscoped` to avoid the leaking scope.
717
+ * Fix index creation to preserve index comment in bulk change table on MySQL.
601
718
 
602
719
  *Ryuta Kamizono*
603
720
 
604
- * Allow applications to automatically switch connections.
721
+ * Allow `unscope` to be aware of table name qualified values.
605
722
 
606
- Adds a middleware and configuration options that can be used in your
607
- application to automatically switch between the writing and reading
608
- database connections.
723
+ It is possible to unscope only the column in the specified table.
609
724
 
610
- `GET` and `HEAD` requests will read from the replica unless there was
611
- a write in the last 2 seconds, otherwise they will read from the primary.
612
- Non-get requests will always write to the primary. The middleware accepts
613
- an argument for a Resolver class and an Operations class where you are able
614
- to change how the auto-switcher works to be most beneficial for your
615
- application.
725
+ ```ruby
726
+ posts = Post.joins(:comments).group(:"posts.hidden")
727
+ posts = posts.where("posts.hidden": false, "comments.hidden": false)
616
728
 
617
- To use the middleware in your application you can use the following
618
- configuration options:
729
+ posts.count
730
+ # => { false => 10 }
619
731
 
620
- ```
621
- config.active_record.database_selector = { delay: 2.seconds }
622
- config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
623
- config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
732
+ # unscope both hidden columns
733
+ posts.unscope(where: :hidden).count
734
+ # => { false => 11, true => 1 }
735
+
736
+ # unscope only comments.hidden column
737
+ posts.unscope(where: :"comments.hidden").count
738
+ # => { false => 11 }
624
739
  ```
625
740
 
626
- To change the database selection strategy, pass a custom class to the
627
- configuration options:
741
+ *Ryuta Kamizono*, *Slava Korolev*
628
742
 
743
+ * Fix `rewhere` to truly overwrite collided where clause by new where clause.
744
+
745
+ ```ruby
746
+ steve = Person.find_by(name: "Steve")
747
+ david = Author.find_by(name: "David")
748
+
749
+ relation = Essay.where(writer: steve)
750
+
751
+ # Before
752
+ relation.rewhere(writer: david).to_a # => []
753
+
754
+ # After
755
+ relation.rewhere(writer: david).to_a # => [david]
629
756
  ```
630
- config.active_record.database_selector = { delay: 10.seconds }
631
- config.active_record.database_resolver = MyResolver
632
- config.active_record.database_resolver_context = MyResolver::MyCookies
757
+
758
+ *Ryuta Kamizono*
759
+
760
+ * Inspect time attributes with subsec and time zone offset.
761
+
762
+ ```ruby
763
+ p Knot.create
764
+ => #<Knot id: 1, created_at: "2016-05-05 01:29:47.116928000 +0000">
633
765
  ```
634
766
 
635
- *Eileen M. Uchitelle*
767
+ *akinomaeni*, *Jonathan Hefner*
636
768
 
637
- * MySQL: Support `:size` option to change text and blob size.
769
+ * Deprecate passing a column to `type_cast`.
638
770
 
639
771
  *Ryuta Kamizono*
640
772
 
641
- * Make `t.timestamps` with precision by default.
773
+ * Deprecate `in_clause_length` and `allowed_index_name_length` in `DatabaseLimits`.
642
774
 
643
775
  *Ryuta Kamizono*
644
776
 
777
+ * Support bulk insert/upsert on relation to preserve scope values.
645
778
 
646
- ## Rails 6.0.0.beta1 (January 18, 2019) ##
779
+ *Josef Šimánek*, *Ryuta Kamizono*
647
780
 
648
- * Remove deprecated `#set_state` from the transaction object.
781
+ * Preserve column comment value on changing column name on MySQL.
649
782
 
650
- *Rafael Mendonça França*
783
+ *Islam Taha*
651
784
 
652
- * Remove deprecated `#supports_statement_cache?` from the database adapters.
785
+ * Add support for `if_exists` option for removing an index.
653
786
 
654
- *Rafael Mendonça França*
787
+ The `remove_index` method can take an `if_exists` option. If this is set to true an error won't be raised if the index doesn't exist.
655
788
 
656
- * Remove deprecated `#insert_fixtures` from the database adapters.
789
+ *Eileen M. Uchitelle*
657
790
 
658
- *Rafael Mendonça França*
791
+ * Remove ibm_db, informix, mssql, oracle, and oracle12 Arel visitors which are not used in the code base.
659
792
 
660
- * Remove deprecated `ActiveRecord::ConnectionAdapters::SQLite3Adapter#valid_alter_table_type?`.
793
+ *Ryuta Kamizono*
661
794
 
662
- *Rafael Mendonça França*
795
+ * Prevent `build_association` from `touching` a parent record if the record isn't persisted for `has_one` associations.
663
796
 
664
- * Do not allow passing the column name to `sum` when a block is passed.
797
+ Fixes #38219.
665
798
 
666
- *Rafael Mendonça França*
799
+ *Josh Brody*
667
800
 
668
- * Do not allow passing the column name to `count` when a block is passed.
801
+ * Add support for `if_not_exists` option for adding index.
669
802
 
670
- *Rafael Mendonça França*
803
+ The `add_index` method respects `if_not_exists` option. If it is set to true
804
+ index won't be added.
671
805
 
672
- * Remove delegation of missing methods in a relation to arel.
806
+ Usage:
673
807
 
674
- *Rafael Mendonça França*
808
+ ```ruby
809
+ add_index :users, :account_id, if_not_exists: true
810
+ ```
675
811
 
676
- * Remove delegation of missing methods in a relation to private methods of the class.
812
+ The `if_not_exists` option passed to `create_table` also gets propagated to indexes
813
+ created within that migration so that if table and its indexes exist then there is no
814
+ attempt to create them again.
677
815
 
678
- *Rafael Mendonça França*
816
+ *Prathamesh Sonpatki*
679
817
 
680
- * Deprecate `config.active_record.sqlite3.represent_boolean_as_integer`.
818
+ * Add `ActiveRecord::Base#previously_new_record?` to show if a record was new before the last save.
681
819
 
682
- *Rafael Mendonça França*
820
+ *Tom Ward*
683
821
 
684
- * Change `SQLite3Adapter` to always represent boolean values as integers.
822
+ * Support descending order for `find_each`, `find_in_batches`, and `in_batches`.
685
823
 
686
- *Rafael Mendonça França*
824
+ Batch processing methods allow you to work with the records in batches, greatly reducing memory consumption, but records are always batched from oldest id to newest.
687
825
 
688
- * Remove ability to specify a timestamp name for `#cache_key`.
826
+ This change allows reversing the order, batching from newest to oldest. This is useful when you need to process newer batches of records first.
689
827
 
690
- *Rafael Mendonça França*
828
+ Pass `order: :desc` to yield batches in descending order. The default remains `order: :asc`.
691
829
 
692
- * Remove deprecated `ActiveRecord::Migrator.migrations_path=`.
830
+ ```ruby
831
+ Person.find_each(order: :desc) do |person|
832
+ person.party_all_night!
833
+ end
834
+ ```
693
835
 
694
- *Rafael Mendonça França*
836
+ *Alexey Vasiliev*
695
837
 
696
- * Remove deprecated `expand_hash_conditions_for_aggregates`.
838
+ * Fix `insert_all` with enum values.
697
839
 
698
- *Rafael Mendonça França*
840
+ Fixes #38716.
699
841
 
700
- * Set polymorphic type column to NULL on `dependent: :nullify` strategy.
842
+ *Joel Blum*
701
843
 
702
- On polymorphic associations both the foreign key and the foreign type columns will be set to NULL.
844
+ * Add support for `db:rollback:name` for multiple database applications.
703
845
 
704
- *Laerti Papa*
846
+ Multiple database applications will now raise if `db:rollback` is call and recommend using the `db:rollback:[NAME]` to rollback migrations.
705
847
 
706
- * Allow permitted instance of `ActionController::Parameters` as argument of `ActiveRecord::Relation#exists?`.
848
+ *Eileen M. Uchitelle*
707
849
 
708
- *Gannon McGibbon*
850
+ * `Relation#pick` now uses already loaded results instead of making another query.
709
851
 
710
- * Add support for endless ranges introduces in Ruby 2.6.
852
+ *Eugene Kenny*
711
853
 
712
- *Greg Navis*
854
+ * Deprecate using `return`, `break` or `throw` to exit a transaction block after writes.
713
855
 
714
- * Deprecate passing `migrations_paths` to `connection.assume_migrated_upto_version`.
856
+ *Dylan Thacker-Smith*
715
857
 
716
- *Ryuta Kamizono*
858
+ * Dump the schema or structure of a database when calling `db:migrate:name`.
717
859
 
718
- * MySQL: `ROW_FORMAT=DYNAMIC` create table option by default.
860
+ In previous versions of Rails, `rails db:migrate` would dump the schema of the database. In Rails 6, that holds true (`rails db:migrate` dumps all databases' schemas), but `rails db:migrate:name` does not share that behavior.
719
861
 
720
- Since MySQL 5.7.9, the `innodb_default_row_format` option defines the default row
721
- format for InnoDB tables. The default setting is `DYNAMIC`.
722
- The row format is required for indexing on `varchar(255)` with `utf8mb4` columns.
862
+ Going forward, calls to `rails db:migrate:name` will dump the schema (or structure) of the database being migrated.
723
863
 
724
- *Ryuta Kamizono*
864
+ *Kyle Thompson*
725
865
 
726
- * Fix join table column quoting with SQLite.
866
+ * Reset the `ActiveRecord::Base` connection after `rails db:migrate:name`.
727
867
 
728
- *Gannon McGibbon*
868
+ When `rails db:migrate` has finished, it ensures the `ActiveRecord::Base` connection is reset to its original configuration. Going forward, `rails db:migrate:name` will have the same behavior.
729
869
 
730
- * Allow disabling scopes generated by `ActiveRecord.enum`.
870
+ *Kyle Thompson*
731
871
 
732
- *Alfred Dominic*
872
+ * Disallow calling `connected_to` on subclasses of `ActiveRecord::Base`.
733
873
 
734
- * Ensure that `delete_all` on collection proxy returns affected count.
874
+ Behavior has not changed here but the previous API could be misleading to people who thought it would switch connections for only that class. `connected_to` switches the context from which we are getting connections, not the connections themselves.
735
875
 
736
- *Ryuta Kamizono*
876
+ *Eileen M. Uchitelle*, *John Crepezzi*
737
877
 
738
- * Reset scope after delete on collection association to clear stale offsets of removed records.
878
+ * Add support for horizontal sharding to `connects_to` and `connected_to`.
739
879
 
740
- *Gannon McGibbon*
880
+ Applications can now connect to multiple shards and switch between their shards in an application. Note that the shard swapping is still a manual process as this change does not include an API for automatic shard swapping.
741
881
 
742
- * Add the ability to prevent writes to a database for the duration of a block.
882
+ Usage:
743
883
 
744
- Allows the application to prevent writes to a database. This can be useful when
745
- you're building out multiple databases and want to make sure you're not sending
746
- writes when you want a read.
884
+ Given the following configuration:
747
885
 
748
- If `while_preventing_writes` is called and the query is considered a write
749
- query the database will raise an exception regardless of whether the database
750
- user is able to write.
886
+ ```yaml
887
+ # config/database.yml
888
+ production:
889
+ primary:
890
+ database: my_database
891
+ primary_shard_one:
892
+ database: my_database_shard_one
893
+ ```
751
894
 
752
- This is not meant to be a catch-all for write queries but rather a way to enforce
753
- read-only queries without opening a second connection. One purpose of this is to
754
- catch accidental writes, not all writes.
895
+ Connect to multiple shards:
755
896
 
756
- *Eileen M. Uchitelle*
897
+ ```ruby
898
+ class ApplicationRecord < ActiveRecord::Base
899
+ self.abstract_class = true
757
900
 
758
- * Allow aliased attributes to be used in `#update_columns` and `#update`.
901
+ connects_to shards: {
902
+ default: { writing: :primary },
903
+ shard_one: { writing: :primary_shard_one }
904
+ }
905
+ ```
759
906
 
760
- *Gannon McGibbon*
907
+ Swap between shards in your controller / model code:
761
908
 
762
- * Allow spaces in postgres table names.
909
+ ```ruby
910
+ ActiveRecord::Base.connected_to(shard: :shard_one) do
911
+ # Read from shard one
912
+ end
913
+ ```
763
914
 
764
- Fixes issue where "user post" is misinterpreted as "\"user\".\"post\"" when quoting table names with the postgres adapter.
915
+ The horizontal sharding API also supports read replicas. See guides for more details.
765
916
 
766
- *Gannon McGibbon*
917
+ *Eileen M. Uchitelle*, *John Crepezzi*
918
+
919
+ * Deprecate `spec_name` in favor of `name` on database configurations.
767
920
 
768
- * Cached `columns_hash` fields should be excluded from `ResultSet#column_types`.
921
+ The accessors for `spec_name` on `configs_for` and `DatabaseConfig` are deprecated. Please use `name` instead.
769
922
 
770
- PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test
771
- was passing for SQLite and MySQL, but failed for PostgreSQL:
923
+ Deprecated behavior:
772
924
 
773
925
  ```ruby
774
- class DeveloperName < ActiveRecord::Type::String
775
- def deserialize(value)
776
- "Developer: #{value}"
777
- end
778
- end
926
+ db_config = ActiveRecord::Base.configs_for(env_name: "development", spec_name: "primary")
927
+ db_config.spec_name
928
+ ```
779
929
 
780
- class AttributedDeveloper < ActiveRecord::Base
781
- self.table_name = "developers"
930
+ New behavior:
782
931
 
783
- attribute :name, DeveloperName.new
932
+ ```ruby
933
+ db_config = ActiveRecord::Base.configs_for(env_name: "development", name: "primary")
934
+ db_config.name
935
+ ```
784
936
 
785
- self.ignored_columns += ["name"]
786
- end
937
+ *Eileen M. Uchitelle*
938
+
939
+ * Add additional database-specific rake tasks for multi-database users.
787
940
 
788
- developer = AttributedDeveloper.create
789
- developer.update_column :name, "name"
941
+ Previously, `rails db:create`, `rails db:drop`, and `rails db:migrate` were the only rails tasks that could operate on a single
942
+ database. For example:
790
943
 
791
- loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first
792
- puts loaded_developer.name # should be "Developer: name" but it's just "name"
944
+ ```
945
+ rails db:create
946
+ rails db:create:primary
947
+ rails db:create:animals
948
+ rails db:drop
949
+ rails db:drop:primary
950
+ rails db:drop:animals
951
+ rails db:migrate
952
+ rails db:migrate:primary
953
+ rails db:migrate:animals
793
954
  ```
794
955
 
795
- *Dmitry Tsepelev*
956
+ With these changes, `rails db:schema:dump`, `rails db:schema:load`, `rails db:structure:dump`, `rails db:structure:load` and
957
+ `rails db:test:prepare` can additionally operate on a single database. For example:
796
958
 
797
- * Make the implicit order column configurable.
959
+ ```
960
+ rails db:schema:dump
961
+ rails db:schema:dump:primary
962
+ rails db:schema:dump:animals
963
+ rails db:schema:load
964
+ rails db:schema:load:primary
965
+ rails db:schema:load:animals
966
+ rails db:structure:dump
967
+ rails db:structure:dump:primary
968
+ rails db:structure:dump:animals
969
+ rails db:structure:load
970
+ rails db:structure:load:primary
971
+ rails db:structure:load:animals
972
+ rails db:test:prepare
973
+ rails db:test:prepare:primary
974
+ rails db:test:prepare:animals
975
+ ```
798
976
 
799
- When calling ordered finder methods such as `first` or `last` without an
800
- explicit order clause, ActiveRecord sorts records by primary key. This can
801
- result in unpredictable and surprising behaviour when the primary key is
802
- not an auto-incrementing integer, for example when it's a UUID. This change
803
- makes it possible to override the column used for implicit ordering such
804
- that `first` and `last` will return more predictable results.
977
+ *Kyle Thompson*
805
978
 
806
- Example:
979
+ * Add support for `strict_loading` mode on association declarations.
807
980
 
808
- class Project < ActiveRecord::Base
809
- self.implicit_order_column = "created_at"
810
- end
981
+ Raise an error if attempting to load a record from an association that has been marked as `strict_loading` unless it was explicitly eager loaded.
811
982
 
812
- *Tekin Suleyman*
983
+ Usage:
813
984
 
814
- * Bump minimum PostgreSQL version to 9.3.
985
+ ```ruby
986
+ class Developer < ApplicationRecord
987
+ has_many :projects, strict_loading: true
988
+ end
815
989
 
816
- *Yasuo Honda*
990
+ dev = Developer.first
991
+ dev.projects.first
992
+ # => ActiveRecord::StrictLoadingViolationError: The projects association is marked as strict_loading and cannot be lazily loaded.
993
+ ```
817
994
 
818
- * Values of enum are frozen, raising an error when attempting to modify them.
995
+ *Kevin Deisz*
819
996
 
820
- *Emmanuel Byrd*
997
+ * Add support for `strict_loading` mode to prevent lazy loading of records.
821
998
 
822
- * Move `ActiveRecord::StatementInvalid` SQL to error property and include binds as separate error property.
999
+ Raise an error if a parent record is marked as `strict_loading` and attempts to lazily load its associations. This is useful for finding places you may want to preload an association and avoid additional queries.
823
1000
 
824
- `ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception_class` now requires `binds` to be passed as the last argument.
1001
+ Usage:
825
1002
 
826
- `ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception` now requires `message`, `sql`, and `binds` to be passed as keyword arguments.
1003
+ ```ruby
1004
+ dev = Developer.strict_loading.first
1005
+ dev.audit_logs.to_a
1006
+ # => ActiveRecord::StrictLoadingViolationError: Developer is marked as strict_loading and AuditLog cannot be lazily loaded.
1007
+ ```
827
1008
 
828
- Subclasses of `ActiveRecord::StatementInvalid` must now provide `sql:` and `binds:` arguments to `super`.
1009
+ *Eileen M. Uchitelle*, *Aaron Patterson*
829
1010
 
830
- Example:
1011
+ * Add support for PostgreSQL 11+ partitioned indexes when using `upsert_all`.
831
1012
 
832
- ```
833
- class MySubclassedError < ActiveRecord::StatementInvalid
834
- def initialize(message, sql:, binds:)
835
- super(message, sql: sql, binds: binds)
1013
+ *Sebastián Palma*
1014
+
1015
+ * Adds support for `if_not_exists` to `add_column` and `if_exists` to `remove_column`.
1016
+
1017
+ Applications can set their migrations to ignore exceptions raised when adding a column that already exists or when removing a column that does not exist.
1018
+
1019
+ Example Usage:
1020
+
1021
+ ```ruby
1022
+ class AddColumnTitle < ActiveRecord::Migration[6.1]
1023
+ def change
1024
+ add_column :posts, :title, :string, if_not_exists: true
836
1025
  end
837
1026
  end
838
1027
  ```
839
1028
 
840
- *Gannon McGibbon*
1029
+ ```ruby
1030
+ class RemoveColumnTitle < ActiveRecord::Migration[6.1]
1031
+ def change
1032
+ remove_column :posts, :title, if_exists: true
1033
+ end
1034
+ end
1035
+ ```
841
1036
 
842
- * Add an `:if_not_exists` option to `create_table`.
1037
+ *Eileen M. Uchitelle*
843
1038
 
844
- Example:
1039
+ * Regexp-escape table name for MS SQL Server.
845
1040
 
846
- create_table :posts, if_not_exists: true do |t|
847
- t.string :title
848
- end
1041
+ Add `Regexp.escape` to one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods like `pluck` and `select` fail in certain cases when used with the MS SQL Server adapter.
849
1042
 
850
- That would execute:
1043
+ *Larry Reid*
851
1044
 
852
- CREATE TABLE IF NOT EXISTS posts (
853
- ...
854
- )
1045
+ * Store advisory locks on their own named connection.
855
1046
 
856
- If the table already exists, `if_not_exists: false` (the default) raises an
857
- exception whereas `if_not_exists: true` does nothing.
1047
+ Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.
858
1048
 
859
- *fatkodima*, *Stefan Kanev*
1049
+ In order to fix this we are storing the advisory lock on a new connection with the connection specification name `AdvisoryLockBase`. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.
860
1050
 
861
- * Defining an Enum as a Hash with blank key, or as an Array with a blank value, now raises an `ArgumentError`.
1051
+ *Eileen M. Uchitelle*, *John Crepezzi*
862
1052
 
863
- *Christophe Maximin*
1053
+ * Allow schema cache path to be defined in the database configuration file.
864
1054
 
865
- * Adds support for multiple databases to `rails db:schema:cache:dump` and `rails db:schema:cache:clear`.
1055
+ For example:
866
1056
 
867
- *Gannon McGibbon*
1057
+ ```yaml
1058
+ development:
1059
+ adapter: postgresql
1060
+ database: blog_development
1061
+ pool: 5
1062
+ schema_cache_path: tmp/schema/main.yml
1063
+ ```
868
1064
 
869
- * `update_columns` now correctly raises `ActiveModel::MissingAttributeError`
870
- if the attribute does not exist.
1065
+ *Katrina Owen*
871
1066
 
872
- *Sean Griffin*
1067
+ * Deprecate `#remove_connection` in favor of `#remove_connection_pool` when called on the handler.
873
1068
 
874
- * Add support for hash and URL configs in database hash of `ActiveRecord::Base.connected_to`.
1069
+ `#remove_connection` is deprecated in order to support returning a `DatabaseConfig` object instead of a `Hash`. Use `#remove_connection_pool`, `#remove_connection` will be removed in 6.2.
875
1070
 
876
- ````
877
- User.connected_to(database: { writing: "postgres://foo" }) do
878
- User.create!(name: "Gannon")
879
- end
1071
+ *Eileen M. Uchitelle*, *John Crepezzi*
880
1072
 
881
- config = { "adapter" => "sqlite3", "database" => "db/readonly.sqlite3" }
882
- User.connected_to(database: { reading: config }) do
883
- User.count
884
- end
885
- ````
1073
+ * Deprecate `#default_hash` and it's alias `#[]` on database configurations.
886
1074
 
887
- *Gannon McGibbon*
1075
+ Applications should use `configs_for`. `#default_hash` and `#[]` will be removed in 6.2.
888
1076
 
889
- * Support default expression for MySQL.
1077
+ *Eileen M. Uchitelle*, *John Crepezzi*
890
1078
 
891
- MySQL 8.0.13 and higher supports default value to be a function or expression.
1079
+ * Add scale support to `ActiveRecord::Validations::NumericalityValidator`.
892
1080
 
893
- https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1081
+ *Gannon McGibbon*
894
1082
 
895
- *Ryuta Kamizono*
1083
+ * Find orphans by looking for missing relations through chaining `where.missing`:
896
1084
 
897
- * Support expression indexes for MySQL.
1085
+ Before:
898
1086
 
899
- MySQL 8.0.13 and higher supports functional key parts that index
900
- expression values rather than column or column prefix values.
1087
+ ```ruby
1088
+ Post.left_joins(:author).where(authors: { id: nil })
1089
+ ```
901
1090
 
902
- https://dev.mysql.com/doc/refman/8.0/en/create-index.html
1091
+ After:
903
1092
 
904
- *Ryuta Kamizono*
1093
+ ```ruby
1094
+ Post.where.missing(:author)
1095
+ ```
905
1096
 
906
- * Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.
1097
+ *Tom Rossi*
907
1098
 
908
- Fixes #33056.
1099
+ * Ensure `:reading` connections always raise if a write is attempted.
909
1100
 
910
- *Federico Martinez*
1101
+ Now Rails will raise an `ActiveRecord::ReadOnlyError` if any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than `:reading`.
911
1102
 
912
- * Add basic API for connection switching to support multiple databases.
1103
+ *Eileen M. Uchitelle*
913
1104
 
914
- 1) Adds a `connects_to` method for models to connect to multiple databases. Example:
1105
+ * Deprecate `"primary"` as the `connection_specification_name` for `ActiveRecord::Base`.
915
1106
 
916
- ```
917
- class AnimalsModel < ApplicationRecord
918
- self.abstract_class = true
1107
+ `"primary"` has been deprecated as the `connection_specification_name` for `ActiveRecord::Base` in favor of using `"ActiveRecord::Base"`. This change affects calls to `ActiveRecord::Base.connection_handler.retrieve_connection` and `ActiveRecord::Base.connection_handler.remove_connection`. If you're calling these methods with `"primary"`, please switch to `"ActiveRecord::Base"`.
919
1108
 
920
- connects_to database: { writing: :animals_primary, reading: :animals_replica }
921
- end
1109
+ *Eileen M. Uchitelle*, *John Crepezzi*
922
1110
 
923
- class Dog < AnimalsModel
924
- # connected to both the animals_primary db for writing and the animals_replica for reading
925
- end
926
- ```
1111
+ * Add `ActiveRecord::Validations::NumericalityValidator` with
1112
+ support for casting floats using a database columns' precision value.
927
1113
 
928
- 2) Adds a `connected_to` block method for switching connection roles or connecting to
929
- a database that the model didn't connect to. Connecting to the database in this block is
930
- useful when you have another defined connection, for example `slow_replica` that you don't
931
- want to connect to by default but need in the console, or a specific code block.
1114
+ *Gannon McGibbon*
932
1115
 
933
- ```
934
- ActiveRecord::Base.connected_to(role: :reading) do
935
- Dog.first # finds dog from replica connected to AnimalsBase
936
- Book.first # doesn't have a reading connection, will raise an error
937
- end
938
- ```
1116
+ * Enforce fresh ETag header after a collection's contents change by adding
1117
+ ActiveRecord::Relation#cache_key_with_version. This method will be used by
1118
+ ActionController::ConditionalGet to ensure that when collection cache versioning
1119
+ is enabled, requests using ConditionalGet don't return the same ETag header
1120
+ after a collection is modified.
939
1121
 
940
- ```
941
- ActiveRecord::Base.connected_to(database: :slow_replica) do
942
- 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
943
- end
944
- ```
1122
+ Fixes #38078.
945
1123
 
946
- *Eileen M. Uchitelle*
1124
+ *Aaron Lipman*
947
1125
 
948
- * Enum raises on invalid definition values
1126
+ * Skip test database when running `db:create` or `db:drop` in development
1127
+ with `DATABASE_URL` set.
949
1128
 
950
- When defining a Hash enum it can be easy to use `[]` instead of `{}`. This
951
- commit checks that only valid definition values are provided, those can
952
- be a Hash, an array of Symbols or an array of Strings. Otherwise it
953
- raises an `ArgumentError`.
1129
+ *Brian Buchalter*
954
1130
 
955
- Fixes #33961
1131
+ * Don't allow mutations on the database configurations hash.
956
1132
 
957
- *Alberto Almagro*
1133
+ Freeze the configurations hash to disallow directly changing it. If applications need to change the hash, for example to create databases for parallelization, they should use the `DatabaseConfig` object directly.
958
1134
 
959
- * Reloading associations now clears the Query Cache like `Persistence#reload` does.
1135
+ Before:
960
1136
 
1137
+ ```ruby
1138
+ @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
1139
+ @db_config.configuration_hash.merge!(idle_timeout: "0.02")
961
1140
  ```
962
- class Post < ActiveRecord::Base
963
- has_one :category
964
- belongs_to :author
965
- has_many :comments
966
- end
967
1141
 
968
- # Each of the following will now clear the query cache.
969
- post.reload_category
970
- post.reload_author
971
- post.comments.reload
1142
+ After:
1143
+
1144
+ ```ruby
1145
+ @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
1146
+ config = @db_config.configuration_hash.merge(idle_timeout: "0.02")
1147
+ db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(@db_config.env_name, @db_config.spec_name, config)
972
1148
  ```
973
1149
 
974
- *Christophe Maximin*
1150
+ *Eileen M. Uchitelle*, *John Crepezzi*
975
1151
 
976
- * Added `index` option for `change_table` migration helpers.
977
- With this change you can create indexes while adding new
978
- columns into the existing tables.
1152
+ * Remove `:connection_id` from the `sql.active_record` notification.
979
1153
 
980
- Example:
1154
+ *Aaron Patterson*, *Rafael Mendonça França*
981
1155
 
982
- change_table(:languages) do |t|
983
- t.string :country_code, index: true
984
- end
1156
+ * The `:name` key will no longer be returned as part of `DatabaseConfig#configuration_hash`. Please use `DatabaseConfig#owner_name` instead.
985
1157
 
986
- *Mehmet Emin İNAÇ*
1158
+ *Eileen M. Uchitelle*, *John Crepezzi*
987
1159
 
988
- * Fix `transaction` reverting for migrations.
1160
+ * ActiveRecord's `belongs_to_required_by_default` flag can now be set per model.
989
1161
 
990
- Before: Commands inside a `transaction` in a reverted migration ran uninverted.
991
- Now: This change fixes that by reverting commands inside `transaction` block.
1162
+ You can now opt-out/opt-in specific models from having their associations required
1163
+ by default.
992
1164
 
993
- *fatkodima*, *David Verhasselt*
1165
+ This change is meant to ease the process of migrating all your models to have
1166
+ their association required.
994
1167
 
995
- * Raise an error instead of scanning the filesystem root when `fixture_path` is blank.
1168
+ *Edouard Chin*
996
1169
 
997
- *Gannon McGibbon*, *Max Albrecht*
1170
+ * The `connection_config` method has been deprecated, please use `connection_db_config` instead which will return a `DatabaseConfigurations::DatabaseConfig` instead of a `Hash`.
998
1171
 
999
- * Allow `ActiveRecord::Base.configurations=` to be set with a symbolized hash.
1172
+ *Eileen M. Uchitelle*, *John Crepezzi*
1000
1173
 
1001
- *Gannon McGibbon*
1174
+ * Retain explicit selections on the base model after applying `includes` and `joins`.
1002
1175
 
1003
- * Don't update counter cache unless the record is actually saved.
1176
+ Resolves #34889.
1004
1177
 
1005
- Fixes #31493, #33113, #33117.
1178
+ *Patrick Rebsch*
1006
1179
 
1007
- *Ryuta Kamizono*
1180
+ * The `database` kwarg is deprecated without replacement because it can't be used for sharding and creates an issue if it's used during a request. Applications that need to create new connections should use `connects_to` instead.
1008
1181
 
1009
- * Deprecate `ActiveRecord::Result#to_hash` in favor of `ActiveRecord::Result#to_a`.
1182
+ *Eileen M. Uchitelle*, *John Crepezzi*
1010
1183
 
1011
- *Gannon McGibbon*, *Kevin Cheng*
1184
+ * Allow attributes to be fetched from Arel node groupings.
1012
1185
 
1013
- * SQLite3 adapter supports expression indexes.
1186
+ *Jeff Emminger*, *Gannon McGibbon*
1014
1187
 
1015
- ```
1016
- create_table :users do |t|
1017
- t.string :email
1018
- end
1188
+ * A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgreSQL `options`.
1019
1189
 
1020
- add_index :users, 'lower(email)', name: 'index_users_on_email', unique: true
1021
- ```
1190
+ *Joshua Flanagan*
1022
1191
 
1023
- *Gray Kemmey*
1192
+ * Calling methods like `establish_connection` with a `Hash` which is invalid (eg: no `adapter`) will now raise an error the same way as connections defined in `config/database.yml`.
1024
1193
 
1025
- * Allow subclasses to redefine autosave callbacks for associated records.
1194
+ *John Crepezzi*
1026
1195
 
1027
- Fixes #33305.
1196
+ * Specifying `implicit_order_column` now subsorts the records by primary key if available to ensure deterministic results.
1028
1197
 
1029
- *Andrey Subbota*
1198
+ *Paweł Urbanek*
1030
1199
 
1031
- * Bump minimum MySQL version to 5.5.8.
1200
+ * `where(attr => [])` now loads an empty result without making a query.
1032
1201
 
1033
- *Yasuo Honda*
1202
+ *John Hawthorn*
1034
1203
 
1035
- * Use MySQL utf8mb4 character set by default.
1204
+ * Fixed the performance regression for `primary_keys` introduced MySQL 8.0.
1036
1205
 
1037
- `utf8mb4` character set with 4-Byte encoding supports supplementary characters including emoji.
1038
- The previous default 3-Byte encoding character set `utf8` is not enough to support them.
1206
+ *Hiroyuki Ishii*
1039
1207
 
1040
- *Yasuo Honda*
1208
+ * Add support for `belongs_to` to `has_many` inversing.
1041
1209
 
1042
- * Fix duplicated record creation when using nested attributes with `create_with`.
1210
+ *Gannon McGibbon*
1043
1211
 
1044
- *Darwin Wu*
1212
+ * Allow length configuration for `has_secure_token` method. The minimum length
1213
+ is set at 24 characters.
1045
1214
 
1046
- * Configuration item `config.filter_parameters` could also filter out
1047
- sensitive values of database columns when calling `#inspect`.
1048
- We also added `ActiveRecord::Base::filter_attributes`/`=` in order to
1049
- specify sensitive attributes to specific model.
1215
+ Before:
1050
1216
 
1217
+ ```ruby
1218
+ has_secure_token :auth_token
1051
1219
  ```
1052
- Rails.application.config.filter_parameters += [:credit_card_number, /phone/]
1053
- Account.last.inspect # => #<Account id: 123, name: "DHH", credit_card_number: [FILTERED], telephone_number: [FILTERED] ...>
1054
- SecureAccount.filter_attributes += [:name]
1055
- SecureAccount.last.inspect # => #<SecureAccount id: 42, name: [FILTERED], credit_card_number: [FILTERED] ...>
1220
+
1221
+ After:
1222
+
1223
+ ```ruby
1224
+ has_secure_token :default_token # 24 characters
1225
+ has_secure_token :auth_token, length: 36 # 36 characters
1226
+ has_secure_token :invalid_token, length: 12 # => ActiveRecord::SecureToken::MinimumLengthError
1056
1227
  ```
1057
1228
 
1058
- *Zhang Kang*, *Yoshiyuki Kinjo*
1229
+ *Bernardo de Araujo*
1059
1230
 
1060
- * Deprecate `column_name_length`, `table_name_length`, `columns_per_table`,
1061
- `indexes_per_table`, `columns_per_multicolumn_index`, `sql_query_length`,
1062
- and `joins_per_query` methods in `DatabaseLimits`.
1231
+ * Deprecate `DatabaseConfigurations#to_h`. These connection hashes are still available via `ActiveRecord::Base.configurations.configs_for`.
1063
1232
 
1064
- *Ryuta Kamizono*
1233
+ *Eileen Uchitelle*, *John Crepezzi*
1065
1234
 
1066
- * `ActiveRecord::Base.configurations` now returns an object.
1235
+ * Add `DatabaseConfig#configuration_hash` to return database configuration hashes with symbol keys, and use all symbol-key configuration hashes internally. Deprecate `DatabaseConfig#config` which returns a String-keyed `Hash` with the same values.
1067
1236
 
1068
- `ActiveRecord::Base.configurations` used to return a hash, but this
1069
- is an inflexible data model. In order to improve multiple-database
1070
- handling in Rails, we've changed this to return an object. Some methods
1071
- are provided to make the object behave hash-like in order to ease the
1072
- transition process. Since most applications don't manipulate the hash
1073
- we've decided to add backwards-compatible functionality that will throw
1074
- a deprecation warning if used, however calling `ActiveRecord::Base.configurations`
1075
- will use the new version internally and externally.
1237
+ *John Crepezzi*, *Eileen Uchitelle*
1076
1238
 
1077
- For example, the following `database.yml`:
1239
+ * Allow column names to be passed to `remove_index` positionally along with other options.
1078
1240
 
1079
- ```
1080
- development:
1081
- adapter: sqlite3
1082
- database: db/development.sqlite3
1083
- ```
1241
+ Passing other options can be necessary to make `remove_index` correctly reversible.
1084
1242
 
1085
- Used to become a hash:
1243
+ Before:
1086
1244
 
1087
- ```
1088
- { "development" => { "adapter" => "sqlite3", "database" => "db/development.sqlite3" } }
1089
- ```
1245
+ add_index :reports, :report_id # => works
1246
+ add_index :reports, :report_id, unique: true # => works
1247
+ remove_index :reports, :report_id # => works
1248
+ remove_index :reports, :report_id, unique: true # => ArgumentError
1090
1249
 
1091
- Is now converted into the following object:
1250
+ After:
1092
1251
 
1093
- ```
1094
- #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
1095
- #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
1096
- @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>
1097
- ]
1098
- ```
1252
+ remove_index :reports, :report_id, unique: true # => works
1099
1253
 
1100
- Iterating over the database configurations has also changed. Instead of
1101
- calling hash methods on the `configurations` hash directly, a new method `configs_for` has
1102
- been provided that allows you to select the correct configuration. `env_name` and
1103
- `spec_name` arguments are optional. For example, these return an array of
1104
- database config objects for the requested environment and a single database config object
1105
- will be returned for the requested environment and specification name respectively.
1254
+ *Eugene Kenny*
1106
1255
 
1107
- ```
1108
- ActiveRecord::Base.configurations.configs_for(env_name: "development")
1109
- ActiveRecord::Base.configurations.configs_for(env_name: "development", spec_name: "primary")
1110
- ```
1256
+ * Allow bulk `ALTER` statements to drop and recreate indexes with the same name.
1111
1257
 
1112
- *Eileen M. Uchitelle*, *Aaron Patterson*
1258
+ *Eugene Kenny*
1113
1259
 
1114
- * Add database configuration to disable advisory locks.
1260
+ * `insert`, `insert_all`, `upsert`, and `upsert_all` now clear the query cache.
1115
1261
 
1116
- ```
1117
- production:
1118
- adapter: postgresql
1119
- advisory_locks: false
1120
- ```
1262
+ *Eugene Kenny*
1121
1263
 
1122
- *Guo Xiang*
1264
+ * Call `while_preventing_writes` directly from `connected_to`.
1123
1265
 
1124
- * SQLite3 adapter `alter_table` method restores foreign keys.
1266
+ In some cases application authors want to use the database switching middleware and make explicit calls with `connected_to`. It's possible for an app to turn off writes and not turn them back on by the time we call `connected_to(role: :writing)`.
1125
1267
 
1126
- *Yasuo Honda*
1268
+ This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.
1127
1269
 
1128
- * Allow `:to_table` option to `invert_remove_foreign_key`.
1270
+ *Eileen M. Uchitelle*
1129
1271
 
1130
- Example:
1272
+ * Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.
1273
+
1274
+ *Kir Shatrov*
1131
1275
 
1132
- remove_foreign_key :accounts, to_table: :owners
1276
+ * Stop trying to read yaml file fixtures when loading Active Record fixtures.
1133
1277
 
1134
- *Nikolay Epifanov*, *Rich Chen*
1278
+ *Gannon McGibbon*
1135
1279
 
1136
- * Add environment & load_config dependency to `bin/rake db:seed` to enable
1137
- seed load in environments without Rails and custom DB configuration
1280
+ * Deprecate `.reorder(nil)` with `.first` / `.first!` taking non-deterministic result.
1138
1281
 
1139
- *Tobias Bielohlawek*
1282
+ To continue taking non-deterministic result, use `.take` / `.take!` instead.
1140
1283
 
1141
- * Fix default value for mysql time types with specified precision.
1284
+ *Ryuta Kamizono*
1142
1285
 
1143
- *Nikolay Kondratyev*
1286
+ * Preserve user supplied joins order as much as possible.
1144
1287
 
1145
- * Fix `touch` option to behave consistently with `Persistence#touch` method.
1288
+ Fixes #36761, #34328, #24281, #12953.
1146
1289
 
1147
1290
  *Ryuta Kamizono*
1148
1291
 
1149
- * Migrations raise when duplicate column definition.
1292
+ * Allow `matches_regex` and `does_not_match_regexp` on the MySQL Arel visitor.
1150
1293
 
1151
- Fixes #33024.
1294
+ *James Pearson*
1152
1295
 
1153
- *Federico Martinez*
1296
+ * Allow specifying fixtures to be ignored by setting `ignore` in YAML file's '_fixture' section.
1154
1297
 
1155
- * Bump minimum SQLite version to 3.8
1298
+ *Tongfei Gao*
1156
1299
 
1157
- *Yasuo Honda*
1300
+ * Make the DATABASE_URL env variable only affect the primary connection. Add new env variables for multiple databases.
1158
1301
 
1159
- * Fix parent record should not get saved with duplicate children records.
1302
+ *John Crepezzi*, *Eileen Uchitelle*
1160
1303
 
1161
- Fixes #32940.
1304
+ * Add a warning for enum elements with 'not_' prefix.
1162
1305
 
1163
- *Santosh Wadghule*
1306
+ class Foo
1307
+ enum status: [:sent, :not_sent]
1308
+ end
1309
+
1310
+ *Edu Depetris*
1311
+
1312
+ * Make currency symbols optional for money column type in PostgreSQL.
1313
+
1314
+ *Joel Schneider*
1164
1315
 
1165
- * Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur.
1316
+ * Add support for beginless ranges, introduced in Ruby 2.7.
1166
1317
 
1167
- *Brian Durand*
1318
+ *Josh Goodall*
1168
1319
 
1169
- * Ensure `Associations::CollectionAssociation#size` and `Associations::CollectionAssociation#empty?`
1170
- use loaded association ids if present.
1320
+ * Add `database_exists?` method to connection adapters to check if a database exists.
1171
1321
 
1172
- *Graham Turner*
1322
+ *Guilherme Mansur*
1173
1323
 
1174
- * Add support to preload associations of polymorphic associations when not all the records have the requested associations.
1324
+ * Loading the schema for a model that has no `table_name` raises a `TableNotSpecified` error.
1175
1325
 
1176
- *Dana Sherson*
1326
+ *Guilherme Mansur*, *Eugene Kenny*
1177
1327
 
1178
- * Add `touch_all` method to `ActiveRecord::Relation`.
1328
+ * PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
1179
1329
 
1180
- Example:
1330
+ Fixes #36022.
1181
1331
 
1182
- Person.where(name: "David").touch_all(time: Time.new(2020, 5, 16, 0, 0, 0))
1332
+ *Ryuta Kamizono*
1183
1333
 
1184
- *fatkodima*, *duggiefresh*
1334
+ * Make ActiveRecord `ConnectionPool.connections` method thread-safe.
1185
1335
 
1186
- * Add `ActiveRecord::Base.base_class?` predicate.
1336
+ Fixes #36465.
1187
1337
 
1188
- *Bogdan Gusiev*
1338
+ *Jeff Doering*
1189
1339
 
1190
- * Add custom prefix/suffix options to `ActiveRecord::Store.store_accessor`.
1340
+ * Add support for multiple databases to `rails db:abort_if_pending_migrations`.
1191
1341
 
1192
- *Tan Huynh*, *Yukio Mizuta*
1342
+ *Mark Lee*
1193
1343
 
1194
- * Rails 6 requires Ruby 2.5.0 or newer.
1344
+ * Fix sqlite3 collation parsing when using decimal columns.
1345
+
1346
+ *Martin R. Schuster*
1195
1347
 
1196
- *Jeremy Daer*, *Kasper Timm Hansen*
1348
+ * Fix invalid schema when primary key column has a comment.
1197
1349
 
1198
- * Deprecate `update_attributes`/`!` in favor of `update`/`!`.
1350
+ Fixes #29966.
1199
1351
 
1200
- *Eddie Lebow*
1352
+ *Guilherme Goettems Schneider*
1201
1353
 
1202
- * Add `ActiveRecord::Base.create_or_find_by`/`!` to deal with the SELECT/INSERT race condition in
1203
- `ActiveRecord::Base.find_or_create_by`/`!` by leaning on unique constraints in the database.
1354
+ * Fix table comment also being applied to the primary key column.
1204
1355
 
1205
- *DHH*
1356
+ *Guilherme Goettems Schneider*
1206
1357
 
1207
- * Add `Relation#pick` as short-hand for single-value plucks.
1358
+ * Allow generated `create_table` migrations to include or skip timestamps.
1208
1359
 
1209
- *DHH*
1360
+ *Michael Duchemin*
1210
1361
 
1211
1362
 
1212
- Please check [5-2-stable](https://github.com/rails/rails/blob/5-2-stable/activerecord/CHANGELOG.md) for previous changes.
1363
+ Please check [6-0-stable](https://github.com/rails/rails/blob/6-0-stable/activerecord/CHANGELOG.md) for previous changes.