activerecord 6.0.3 → 6.1.3

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