activerecord 6.1.4.6 → 7.0.2.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 (240) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +1188 -932
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +1 -1
  5. data/lib/active_record/aggregations.rb +1 -1
  6. data/lib/active_record/association_relation.rb +0 -10
  7. data/lib/active_record/associations/association.rb +33 -17
  8. data/lib/active_record/associations/association_scope.rb +1 -3
  9. data/lib/active_record/associations/belongs_to_association.rb +15 -4
  10. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +10 -2
  11. data/lib/active_record/associations/builder/association.rb +8 -2
  12. data/lib/active_record/associations/builder/belongs_to.rb +19 -6
  13. data/lib/active_record/associations/builder/collection_association.rb +10 -3
  14. data/lib/active_record/associations/builder/has_many.rb +3 -2
  15. data/lib/active_record/associations/builder/has_one.rb +2 -1
  16. data/lib/active_record/associations/builder/singular_association.rb +2 -2
  17. data/lib/active_record/associations/collection_association.rb +34 -27
  18. data/lib/active_record/associations/collection_proxy.rb +8 -3
  19. data/lib/active_record/associations/disable_joins_association_scope.rb +59 -0
  20. data/lib/active_record/associations/has_many_association.rb +1 -1
  21. data/lib/active_record/associations/has_many_through_association.rb +2 -1
  22. data/lib/active_record/associations/has_one_association.rb +10 -7
  23. data/lib/active_record/associations/has_one_through_association.rb +1 -1
  24. data/lib/active_record/associations/join_dependency.rb +6 -2
  25. data/lib/active_record/associations/preloader/association.rb +187 -55
  26. data/lib/active_record/associations/preloader/batch.rb +48 -0
  27. data/lib/active_record/associations/preloader/branch.rb +147 -0
  28. data/lib/active_record/associations/preloader/through_association.rb +49 -13
  29. data/lib/active_record/associations/preloader.rb +39 -113
  30. data/lib/active_record/associations/singular_association.rb +8 -2
  31. data/lib/active_record/associations/through_association.rb +3 -3
  32. data/lib/active_record/associations.rb +119 -90
  33. data/lib/active_record/asynchronous_queries_tracker.rb +60 -0
  34. data/lib/active_record/attribute_assignment.rb +1 -1
  35. data/lib/active_record/attribute_methods/before_type_cast.rb +7 -2
  36. data/lib/active_record/attribute_methods/dirty.rb +49 -16
  37. data/lib/active_record/attribute_methods/primary_key.rb +2 -2
  38. data/lib/active_record/attribute_methods/query.rb +2 -2
  39. data/lib/active_record/attribute_methods/read.rb +7 -5
  40. data/lib/active_record/attribute_methods/serialization.rb +66 -12
  41. data/lib/active_record/attribute_methods/time_zone_conversion.rb +4 -3
  42. data/lib/active_record/attribute_methods/write.rb +7 -10
  43. data/lib/active_record/attribute_methods.rb +13 -14
  44. data/lib/active_record/attributes.rb +24 -35
  45. data/lib/active_record/autosave_association.rb +8 -23
  46. data/lib/active_record/base.rb +19 -1
  47. data/lib/active_record/callbacks.rb +2 -2
  48. data/lib/active_record/connection_adapters/abstract/connection_handler.rb +292 -0
  49. data/lib/active_record/connection_adapters/abstract/connection_pool/queue.rb +209 -0
  50. data/lib/active_record/connection_adapters/abstract/connection_pool/reaper.rb +76 -0
  51. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +47 -561
  52. data/lib/active_record/connection_adapters/abstract/database_limits.rb +0 -17
  53. data/lib/active_record/connection_adapters/abstract/database_statements.rb +46 -22
  54. data/lib/active_record/connection_adapters/abstract/query_cache.rb +24 -12
  55. data/lib/active_record/connection_adapters/abstract/quoting.rb +42 -72
  56. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +4 -17
  57. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +38 -13
  58. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +14 -1
  59. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +78 -22
  60. data/lib/active_record/connection_adapters/abstract/transaction.rb +15 -22
  61. data/lib/active_record/connection_adapters/abstract_adapter.rb +149 -74
  62. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +97 -81
  63. data/lib/active_record/connection_adapters/column.rb +4 -0
  64. data/lib/active_record/connection_adapters/mysql/database_statements.rb +38 -24
  65. data/lib/active_record/connection_adapters/mysql/quoting.rb +35 -21
  66. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +7 -1
  67. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +5 -1
  68. data/lib/active_record/connection_adapters/mysql2_adapter.rb +12 -6
  69. data/lib/active_record/connection_adapters/pool_config.rb +7 -7
  70. data/lib/active_record/connection_adapters/postgresql/column.rb +17 -1
  71. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +21 -12
  72. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +8 -0
  73. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +5 -0
  74. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +53 -14
  75. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +1 -1
  76. data/lib/active_record/connection_adapters/postgresql/oid/timestamp.rb +15 -0
  77. data/lib/active_record/connection_adapters/postgresql/oid/timestamp_with_time_zone.rb +30 -0
  78. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +18 -6
  79. data/lib/active_record/connection_adapters/postgresql/oid.rb +2 -0
  80. data/lib/active_record/connection_adapters/postgresql/quoting.rb +50 -50
  81. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +32 -0
  82. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +21 -1
  83. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +22 -1
  84. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +25 -0
  85. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +35 -19
  86. data/lib/active_record/connection_adapters/postgresql_adapter.rb +207 -107
  87. data/lib/active_record/connection_adapters/schema_cache.rb +29 -4
  88. data/lib/active_record/connection_adapters/sqlite3/database_statements.rb +27 -19
  89. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +28 -16
  90. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +16 -14
  91. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +89 -30
  92. data/lib/active_record/connection_adapters.rb +6 -5
  93. data/lib/active_record/connection_handling.rb +47 -53
  94. data/lib/active_record/core.rb +122 -132
  95. data/lib/active_record/database_configurations/connection_url_resolver.rb +3 -1
  96. data/lib/active_record/database_configurations/database_config.rb +12 -9
  97. data/lib/active_record/database_configurations/hash_config.rb +63 -5
  98. data/lib/active_record/database_configurations/url_config.rb +2 -2
  99. data/lib/active_record/database_configurations.rb +16 -32
  100. data/lib/active_record/delegated_type.rb +52 -11
  101. data/lib/active_record/destroy_association_async_job.rb +1 -1
  102. data/lib/active_record/disable_joins_association_relation.rb +39 -0
  103. data/lib/active_record/dynamic_matchers.rb +1 -1
  104. data/lib/active_record/encryption/cipher/aes256_gcm.rb +98 -0
  105. data/lib/active_record/encryption/cipher.rb +53 -0
  106. data/lib/active_record/encryption/config.rb +44 -0
  107. data/lib/active_record/encryption/configurable.rb +61 -0
  108. data/lib/active_record/encryption/context.rb +35 -0
  109. data/lib/active_record/encryption/contexts.rb +72 -0
  110. data/lib/active_record/encryption/derived_secret_key_provider.rb +12 -0
  111. data/lib/active_record/encryption/deterministic_key_provider.rb +14 -0
  112. data/lib/active_record/encryption/encryptable_record.rb +208 -0
  113. data/lib/active_record/encryption/encrypted_attribute_type.rb +140 -0
  114. data/lib/active_record/encryption/encrypted_fixtures.rb +38 -0
  115. data/lib/active_record/encryption/encrypting_only_encryptor.rb +12 -0
  116. data/lib/active_record/encryption/encryptor.rb +155 -0
  117. data/lib/active_record/encryption/envelope_encryption_key_provider.rb +55 -0
  118. data/lib/active_record/encryption/errors.rb +15 -0
  119. data/lib/active_record/encryption/extended_deterministic_queries.rb +160 -0
  120. data/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb +28 -0
  121. data/lib/active_record/encryption/key.rb +28 -0
  122. data/lib/active_record/encryption/key_generator.rb +42 -0
  123. data/lib/active_record/encryption/key_provider.rb +46 -0
  124. data/lib/active_record/encryption/message.rb +33 -0
  125. data/lib/active_record/encryption/message_serializer.rb +90 -0
  126. data/lib/active_record/encryption/null_encryptor.rb +21 -0
  127. data/lib/active_record/encryption/properties.rb +76 -0
  128. data/lib/active_record/encryption/read_only_null_encryptor.rb +24 -0
  129. data/lib/active_record/encryption/scheme.rb +99 -0
  130. data/lib/active_record/encryption.rb +55 -0
  131. data/lib/active_record/enum.rb +49 -42
  132. data/lib/active_record/errors.rb +67 -4
  133. data/lib/active_record/explain_registry.rb +11 -6
  134. data/lib/active_record/fixture_set/file.rb +15 -1
  135. data/lib/active_record/fixture_set/table_row.rb +41 -6
  136. data/lib/active_record/fixture_set/table_rows.rb +4 -4
  137. data/lib/active_record/fixtures.rb +17 -20
  138. data/lib/active_record/future_result.rb +139 -0
  139. data/lib/active_record/gem_version.rb +4 -4
  140. data/lib/active_record/inheritance.rb +55 -17
  141. data/lib/active_record/insert_all.rb +80 -14
  142. data/lib/active_record/integration.rb +4 -3
  143. data/lib/active_record/internal_metadata.rb +3 -5
  144. data/lib/active_record/legacy_yaml_adapter.rb +2 -39
  145. data/lib/active_record/locking/optimistic.rb +10 -9
  146. data/lib/active_record/locking/pessimistic.rb +9 -3
  147. data/lib/active_record/log_subscriber.rb +14 -3
  148. data/lib/active_record/middleware/database_selector/resolver.rb +6 -10
  149. data/lib/active_record/middleware/database_selector.rb +8 -3
  150. data/lib/active_record/middleware/shard_selector.rb +60 -0
  151. data/lib/active_record/migration/command_recorder.rb +4 -4
  152. data/lib/active_record/migration/compatibility.rb +107 -3
  153. data/lib/active_record/migration/join_table.rb +1 -1
  154. data/lib/active_record/migration.rb +109 -79
  155. data/lib/active_record/model_schema.rb +45 -58
  156. data/lib/active_record/nested_attributes.rb +13 -12
  157. data/lib/active_record/no_touching.rb +3 -3
  158. data/lib/active_record/null_relation.rb +2 -6
  159. data/lib/active_record/persistence.rb +219 -52
  160. data/lib/active_record/query_cache.rb +2 -2
  161. data/lib/active_record/query_logs.rb +138 -0
  162. data/lib/active_record/querying.rb +15 -5
  163. data/lib/active_record/railtie.rb +127 -17
  164. data/lib/active_record/railties/controller_runtime.rb +1 -1
  165. data/lib/active_record/railties/databases.rake +66 -129
  166. data/lib/active_record/readonly_attributes.rb +11 -0
  167. data/lib/active_record/reflection.rb +67 -50
  168. data/lib/active_record/relation/batches/batch_enumerator.rb +19 -5
  169. data/lib/active_record/relation/batches.rb +3 -3
  170. data/lib/active_record/relation/calculations.rb +43 -38
  171. data/lib/active_record/relation/delegation.rb +7 -7
  172. data/lib/active_record/relation/finder_methods.rb +31 -35
  173. data/lib/active_record/relation/merger.rb +20 -13
  174. data/lib/active_record/relation/predicate_builder.rb +1 -6
  175. data/lib/active_record/relation/query_attribute.rb +5 -11
  176. data/lib/active_record/relation/query_methods.rb +249 -61
  177. data/lib/active_record/relation/record_fetch_warning.rb +7 -9
  178. data/lib/active_record/relation/spawn_methods.rb +2 -2
  179. data/lib/active_record/relation/where_clause.rb +10 -19
  180. data/lib/active_record/relation.rb +184 -84
  181. data/lib/active_record/result.rb +17 -7
  182. data/lib/active_record/runtime_registry.rb +9 -13
  183. data/lib/active_record/sanitization.rb +11 -7
  184. data/lib/active_record/schema.rb +38 -23
  185. data/lib/active_record/schema_dumper.rb +25 -19
  186. data/lib/active_record/schema_migration.rb +4 -4
  187. data/lib/active_record/scoping/default.rb +61 -12
  188. data/lib/active_record/scoping/named.rb +3 -11
  189. data/lib/active_record/scoping.rb +64 -34
  190. data/lib/active_record/serialization.rb +1 -1
  191. data/lib/active_record/signed_id.rb +1 -1
  192. data/lib/active_record/suppressor.rb +11 -15
  193. data/lib/active_record/tasks/database_tasks.rb +120 -58
  194. data/lib/active_record/tasks/mysql_database_tasks.rb +1 -1
  195. data/lib/active_record/tasks/postgresql_database_tasks.rb +19 -12
  196. data/lib/active_record/test_databases.rb +1 -1
  197. data/lib/active_record/test_fixtures.rb +4 -4
  198. data/lib/active_record/timestamp.rb +3 -4
  199. data/lib/active_record/transactions.rb +9 -14
  200. data/lib/active_record/translation.rb +2 -2
  201. data/lib/active_record/type/adapter_specific_registry.rb +32 -7
  202. data/lib/active_record/type/hash_lookup_type_map.rb +34 -1
  203. data/lib/active_record/type/internal/timezone.rb +2 -2
  204. data/lib/active_record/type/serialized.rb +1 -1
  205. data/lib/active_record/type/type_map.rb +17 -20
  206. data/lib/active_record/type.rb +1 -2
  207. data/lib/active_record/validations/associated.rb +1 -1
  208. data/lib/active_record/validations/uniqueness.rb +1 -1
  209. data/lib/active_record.rb +204 -28
  210. data/lib/arel/attributes/attribute.rb +0 -8
  211. data/lib/arel/crud.rb +28 -22
  212. data/lib/arel/delete_manager.rb +18 -4
  213. data/lib/arel/filter_predications.rb +9 -0
  214. data/lib/arel/insert_manager.rb +2 -3
  215. data/lib/arel/nodes/casted.rb +1 -1
  216. data/lib/arel/nodes/delete_statement.rb +12 -13
  217. data/lib/arel/nodes/filter.rb +10 -0
  218. data/lib/arel/nodes/function.rb +1 -0
  219. data/lib/arel/nodes/insert_statement.rb +2 -2
  220. data/lib/arel/nodes/select_core.rb +2 -2
  221. data/lib/arel/nodes/select_statement.rb +2 -2
  222. data/lib/arel/nodes/update_statement.rb +8 -3
  223. data/lib/arel/nodes.rb +1 -0
  224. data/lib/arel/predications.rb +11 -3
  225. data/lib/arel/select_manager.rb +10 -4
  226. data/lib/arel/table.rb +0 -1
  227. data/lib/arel/tree_manager.rb +0 -12
  228. data/lib/arel/update_manager.rb +18 -4
  229. data/lib/arel/visitors/dot.rb +80 -90
  230. data/lib/arel/visitors/mysql.rb +8 -2
  231. data/lib/arel/visitors/postgresql.rb +0 -10
  232. data/lib/arel/visitors/to_sql.rb +58 -2
  233. data/lib/arel.rb +2 -1
  234. data/lib/rails/generators/active_record/application_record/templates/application_record.rb.tt +1 -1
  235. data/lib/rails/generators/active_record/model/templates/abstract_base_class.rb.tt +1 -1
  236. data/lib/rails/generators/active_record/model/templates/model.rb.tt +1 -1
  237. data/lib/rails/generators/active_record/model/templates/module.rb.tt +2 -2
  238. data/lib/rails/generators/active_record/multi_db/multi_db_generator.rb +16 -0
  239. data/lib/rails/generators/active_record/multi_db/templates/multi_db.rb.tt +44 -0
  240. metadata +56 -11
data/CHANGELOG.md CHANGED
@@ -1,1621 +1,1877 @@
1
- ## Rails 6.1.4.6 (February 11, 2022) ##
1
+ ## Rails 7.0.2.3 (March 08, 2022) ##
2
2
 
3
3
  * No changes.
4
4
 
5
5
 
6
- ## Rails 6.1.4.5 (February 11, 2022) ##
6
+ ## Rails 7.0.2.2 (February 11, 2022) ##
7
7
 
8
8
  * No changes.
9
9
 
10
10
 
11
- ## Rails 6.1.4.4 (December 15, 2021) ##
11
+ ## Rails 7.0.2.1 (February 11, 2022) ##
12
12
 
13
13
  * No changes.
14
14
 
15
15
 
16
- ## Rails 6.1.4.3 (December 14, 2021) ##
16
+ ## Rails 7.0.2 (February 08, 2022) ##
17
17
 
18
- * No changes.
18
+ * Fix `PG.connect` keyword arguments deprecation warning on ruby 2.7.
19
19
 
20
+ *Nikita Vasilevsky*
20
21
 
21
- ## Rails 6.1.4.2 (December 14, 2021) ##
22
+ * Fix the ability to exclude encryption params from being autofiltered.
22
23
 
23
- * No changes.
24
+ *Mark Gangl*
24
25
 
26
+ * Dump the precision for datetime columns following the new defaults.
25
27
 
26
- ## Rails 6.1.4.1 (August 19, 2021) ##
28
+ *Rafael Mendonça França*
27
29
 
28
- * No changes.
30
+ * Make sure encrypted attributes are not being filtered twice.
29
31
 
32
+ *Nikita Vasilevsky*
30
33
 
31
- ## Rails 6.1.4 (June 24, 2021) ##
34
+ * Dump the database schema containing the current Rails version.
32
35
 
33
- * Do not try to rollback transactions that failed due to a `ActiveRecord::TransactionRollbackError`.
36
+ Since https://github.com/rails/rails/pull/42297, Rails now generate datetime columns
37
+ with a default precision of 6. This means that users upgrading to Rails 7.0 from 6.1,
38
+ when loading the database schema, would get the new precision value, which would not match
39
+ the production schema.
34
40
 
35
- *Jamie McCarthy*
41
+ To avoid this the schema dumper will generate the new format which will include the Rails
42
+ version and will look like this:
36
43
 
37
- * Raise an error if `pool_config` is `nil` in `set_pool_config`.
44
+ ```
45
+ ActiveRecord::Schema[7.0].define
46
+ ```
38
47
 
39
- *Eileen M. Uchitelle*
48
+ When upgrading from Rails 6.1 to Rails 7.0, you can run the `rails app:update` task that will
49
+ set the current schema version to 6.1.
40
50
 
41
- * Fix compatibility with `psych >= 4`.
51
+ *Rafael Mendonça França*
42
52
 
43
- Starting in Psych 4.0.0 `YAML.load` behaves like `YAML.safe_load`. To preserve compatibility
44
- Active Record's schema cache loader and `YAMLColumn` now uses `YAML.unsafe_load` if available.
53
+ * Fix parsing expression for PostgreSQL generated column.
45
54
 
46
- *Jean Boussier*
55
+ *fatkodima*
47
56
 
48
- * Support using replicas when using `rails dbconsole`.
57
+ * Fix `Mysql2::Error: Commands out of sync; you can't run this command now`
58
+ when bulk-inserting fixtures that exceed `max_allowed_packet` configuration.
49
59
 
50
- *Christopher Thornton*
60
+ *Nikita Vasilevsky*
51
61
 
52
- * Restore connection pools after transactional tests.
62
+ * Fix error when saving an association with a relation named `record`.
53
63
 
54
- *Eugene Kenny*
64
+ *Dorian Marié*
55
65
 
56
- * Change `upsert_all` to fails cleanly for MySQL when `:unique_by` is used.
66
+ * Fix `MySQL::SchemaDumper` behavior about datetime precision value.
57
67
 
58
- *Bastian Bartmann*
68
+ *y0t4*
59
69
 
60
- * Fix user-defined `self.default_scope` to respect table alias.
70
+ * Improve associated with no reflection error.
61
71
 
62
- *Ryuta Kamizono*
72
+ *Nikolai*
63
73
 
64
- * Clear `@cache_keys` cache after `update_all`, `delete_all`, `destroy_all`.
74
+ * Fix PG.connect keyword arguments deprecation warning on ruby 2.7.
65
75
 
66
- *Ryuta Kamizono*
76
+ Fixes #44307.
67
77
 
68
- * Changed Arel predications `contains` and `overlaps` to use
69
- `quoted_node` so that PostgreSQL arrays are quoted properly.
78
+ *Nikita Vasilevsky*
70
79
 
71
- *Bradley Priest*
80
+ * Fix passing options to `check_constraint` from `change_table`.
72
81
 
73
- * Fix `merge` when the `where` clauses have string contents.
82
+ *Frederick Cheung*
74
83
 
75
- *Ryuta Kamizono*
76
84
 
77
- * Fix rollback of parent destruction with nested `dependent: :destroy`.
85
+ ## Rails 7.0.1 (January 06, 2022) ##
78
86
 
79
- *Jacopo Beschi*
80
87
 
81
- * Fix binds logging for `"WHERE ... IN ..."` statements.
88
+ * Change `QueryMethods#in_order_of` to drop records not listed in values.
82
89
 
83
- *Ricardo Díaz*
90
+ `in_order_of` now filters down to the values provided, to match the behavior of the `Enumerable` version.
84
91
 
85
- * Handle `false` in relation strict loading checks.
92
+ *Kevin Newton*
86
93
 
87
- Previously when a model had strict loading set to true and then had a
88
- relation set `strict_loading` to false the false wasn't considered when
89
- deciding whether to raise/warn about strict loading.
94
+ * Allow named expression indexes to be revertible.
90
95
 
91
- ```
92
- class Dog < ActiveRecord::Base
93
- self.strict_loading_by_default = true
96
+ Previously, the following code would raise an error in a reversible migration executed while rolling back, due to the index name not being used in the index removal.
94
97
 
95
- has_many :treats, strict_loading: false
96
- end
98
+ ```ruby
99
+ add_index(:settings, "(data->'property')", using: :gin, name: :index_settings_data_property)
97
100
  ```
98
101
 
99
- In the example, `dog.treats` would still raise even though
100
- `strict_loading` was set to false. This is a bug effecting more than
101
- Active Storage which is why I made this PR superceeding #41461. We need
102
- to fix this for all applications since the behavior is a little
103
- surprising. I took the test from ##41461 and the code suggestion from #41453
104
- with some additions.
102
+ Fixes #43331.
105
103
 
106
- *Eileen M. Uchitelle*, *Radamés Roriz*
104
+ *Oliver Günther*
107
105
 
108
- * Fix numericality validator without precision.
106
+ * Better error messages when association name is invalid in the argument of `ActiveRecord::QueryMethods::WhereChain#missing`.
109
107
 
110
- *Ryuta Kamizono*
108
+ *ykpythemind*
111
109
 
112
- * Fix aggregate attribute on Enum types.
110
+ * Fix ordered migrations for single db in multi db environment.
113
111
 
114
- *Ryuta Kamizono*
112
+ *Himanshu*
115
113
 
116
- * Fix `CREATE INDEX` statement generation for PostgreSQL.
114
+ * Extract `on update CURRENT_TIMESTAMP` for mysql2 adapter.
117
115
 
118
- *eltongo*
116
+ *Kazuhiro Masuda*
119
117
 
120
- * Fix where clause on enum attribute when providing array of strings.
118
+ * Fix incorrect argument in PostgreSQL structure dump tasks.
121
119
 
122
- *Ryuta Kamizono*
120
+ Updating the `--no-comment` argument added in Rails 7 to the correct `--no-comments` argument.
123
121
 
124
- * Fix `unprepared_statement` to work it when nesting.
122
+ *Alex Dent*
125
123
 
126
- *Ryuta Kamizono*
124
+ * Fix schema dumping column default SQL values for sqlite3.
127
125
 
126
+ *fatkodima*
128
127
 
129
- ## Rails 6.1.3.2 (May 05, 2021) ##
128
+ * Correctly parse complex check constraint expressions for PostgreSQL.
130
129
 
131
- * No changes.
130
+ *fatkodima*
131
+
132
+ * Fix `timestamptz` attributes on PostgreSQL handle blank inputs.
132
133
 
134
+ *Alex Ghiculescu*
133
135
 
134
- ## Rails 6.1.3.1 (March 26, 2021) ##
136
+ * Fix migration compatibility to create SQLite references/belongs_to column as integer when migration version is 6.0.
135
137
 
136
- * No changes.
138
+ Reference/belongs_to in migrations with version 6.0 were creating columns as
139
+ bigint instead of integer for the SQLite Adapter.
137
140
 
141
+ *Marcelo Lauxen*
138
142
 
139
- ## Rails 6.1.3 (February 17, 2021) ##
143
+ * Fix joining through a polymorphic association.
140
144
 
141
- * Fix the MySQL adapter to always set the right collation and charset
142
- to the connection session.
145
+ *Alexandre Ruban*
143
146
 
144
- *Rafael Mendonça França*
147
+ * Fix `QueryMethods#in_order_of` to handle empty order list.
145
148
 
146
- * Fix MySQL adapter handling of time objects when prepared statements
147
- are enabled.
149
+ ```ruby
150
+ Post.in_order_of(:id, []).to_a
151
+ ```
148
152
 
149
- *Rafael Mendonça França*
153
+ Also more explicitly set the column as secondary order, so that any other
154
+ value is still ordered.
150
155
 
151
- * Fix scoping in enum fields using conditions that would generate
152
- an `IN` clause.
156
+ *Jean Boussier*
153
157
 
154
- *Ryuta Kamizono*
158
+ * Fix `rails dbconsole` for 3-tier config.
155
159
 
156
- * Skip optimised #exist? query when #include? is called on a relation
157
- with a having clause
160
+ *Eileen M. Uchitelle*
158
161
 
159
- Relations that have aliased select values AND a having clause that
160
- references an aliased select value would generate an error when
161
- #include? was called, due to an optimisation that would generate
162
- call #exists? on the relation instead, which effectively alters
163
- the select values of the query (and thus removes the aliased select
164
- values), but leaves the having clause intact. Because the having
165
- clause is then referencing an aliased column that is no longer
166
- present in the simplified query, an ActiveRecord::InvalidStatement
167
- error was raised.
162
+ * Fix quoting of column aliases generated by calculation methods.
168
163
 
169
- An sample query affected by this problem:
164
+ Since the alias is derived from the table name, we can't assume the result
165
+ is a valid identifier.
170
166
 
171
167
  ```ruby
172
- Author.select('COUNT(*) as total_posts', 'authors.*')
173
- .joins(:posts)
174
- .group(:id)
175
- .having('total_posts > 2')
176
- .include?(Author.first)
168
+ class Test < ActiveRecord::Base
169
+ self.table_name = '1abc'
170
+ end
171
+ Test.group(:id).count
172
+ # syntax error at or near "1" (ActiveRecord::StatementInvalid)
173
+ # LINE 1: SELECT COUNT(*) AS count_all, "1abc"."id" AS 1abc_id FROM "1...
177
174
  ```
178
175
 
179
- This change adds an addition check to the condition that skips the
180
- simplified #exists? query, which simply checks for the presence of
181
- a having clause.
182
-
183
- Fixes #41417
184
-
185
- *Michael Smart*
186
-
187
- * Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
188
- without Rails knowledge (e.g., if app gets kill -9d during long-running query or due to Rack::Timeout), app won't end
189
- up in perpetual crash state for being inconsistent with Postgres.
190
-
191
- *wbharding*, *Martin Tepper*
192
-
176
+ *Jean Boussier*
193
177
 
194
- ## Rails 6.1.2.1 (February 10, 2021) ##
195
178
 
196
- * Fix possible DoS vector in PostgreSQL money type
179
+ ## Rails 7.0.0 (December 15, 2021) ##
197
180
 
198
- Carefully crafted input can cause a DoS via the regular expressions used
199
- for validating the money format in the PostgreSQL adapter. This patch
200
- fixes the regexp.
181
+ * Better handle SQL queries with invalid encoding.
201
182
 
202
- Thanks to @dee-see from Hackerone for this patch!
183
+ ```ruby
184
+ Post.create(name: "broken \xC8 UTF-8")
185
+ ```
203
186
 
204
- [CVE-2021-22880]
187
+ Would cause all adapters to fail in a non controlled way in the code
188
+ responsible to detect write queries.
205
189
 
206
- *Aaron Patterson*
190
+ The query is now properly passed to the database connection, which might or might
191
+ not be able to handle it, but will either succeed or failed in a more correct way.
207
192
 
193
+ *Jean Boussier*
208
194
 
209
- ## Rails 6.1.2 (February 09, 2021) ##
195
+ * Move database and shard selection config options to a generator.
210
196
 
211
- * Fix timestamp type for sqlite3.
197
+ Rather than generating the config options in `production.rb` when applications are created, applications can now run a generator to create an initializer and uncomment / update options as needed. All multi-db configuration can be implemented in this initializer.
212
198
 
213
199
  *Eileen M. Uchitelle*
214
200
 
215
- * Make destroy async transactional.
216
201
 
217
- An active record rollback could occur while enqueuing a job. In this
218
- case the job would enqueue even though the database deletion
219
- rolledback putting things in a funky state.
202
+ ## Rails 7.0.0.rc3 (December 14, 2021) ##
220
203
 
221
- Now the jobs are only enqueued until after the db transaction has been committed.
204
+ * No changes.
222
205
 
223
- *Cory Gwin*
224
206
 
225
- * Fix malformed packet error in MySQL statement for connection configuration.
207
+ ## Rails 7.0.0.rc2 (December 14, 2021) ##
226
208
 
227
- *robinroestenburg*
209
+ * No changes.
228
210
 
229
- * Connection specification now passes the "url" key as a configuration for the
230
- adapter if the "url" protocol is "jdbc", "http", or "https". Previously only
231
- urls with the "jdbc" prefix were passed to the Active Record Adapter, others
232
- are assumed to be adapter specification urls.
233
211
 
234
- Fixes #41137.
212
+ ## Rails 7.0.0.rc1 (December 06, 2021) ##
235
213
 
236
- *Jonathan Bracy*
214
+ * Remove deprecated `ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name`.
237
215
 
238
- * Fix granular connection swapping when there are multiple abstract classes.
216
+ *Rafael Mendonça França*
239
217
 
240
- *Eileen M. Uchitelle*
218
+ * Remove deprecated `ActiveRecord::Connection#in_clause_length`.
241
219
 
242
- * Fix `find_by` with custom primary key for belongs_to association.
220
+ *Rafael Mendonça França*
243
221
 
244
- *Ryuta Kamizono*
222
+ * Remove deprecated `ActiveRecord::Connection#allowed_index_name_length`.
245
223
 
246
- * Add support for `rails console --sandbox` for multiple database applications.
224
+ *Rafael Mendonça França*
247
225
 
248
- *alpaca-tc*
226
+ * Remove deprecated `ActiveRecord::Base#remove_connection`.
249
227
 
250
- * Fix `where` on polymorphic association with empty array.
228
+ *Rafael Mendonça França*
251
229
 
252
- *Ryuta Kamizono*
230
+ * Load STI Models in fixtures
253
231
 
254
- * Fix preventing writes for `ApplicationRecord`.
232
+ Data from Fixtures now loads based on the specific class for models with
233
+ Single Table Inheritance. This affects enums defined in subclasses, previously
234
+ the value of these fields was not parsed and remained `nil`
255
235
 
256
- *Eileen M. Uchitelle*
236
+ *Andres Howard*
257
237
 
238
+ * `#authenticate` returns false when the password is blank instead of raising an error.
258
239
 
259
- ## Rails 6.1.1 (January 07, 2021) ##
240
+ *Muhammad Muhammad Ibrahim*
260
241
 
261
- * Fix fixtures loading when strict loading is enabled for the association.
242
+ * Fix `ActiveRecord::QueryMethods#in_order_of` behavior for integer enums.
262
243
 
263
- *Alex Ghiculescu*
244
+ `ActiveRecord::QueryMethods#in_order_of` didn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.
264
245
 
265
- * Fix `where` with custom primary key for belongs_to association.
246
+ The following example now works as expected:
266
247
 
267
- *Ryuta Kamizono*
248
+ ```ruby
249
+ class Book < ApplicationRecord
250
+ enum status: [:proposed, :written, :published]
251
+ end
268
252
 
269
- * Fix `where` with aliased associations.
253
+ Book.in_order_of(:status, %w[written published proposed])
254
+ ```
270
255
 
271
- *Ryuta Kamizono*
256
+ *Alexandre Ruban*
272
257
 
273
- * Fix `composed_of` with symbol mapping.
258
+ * Ignore persisted in-memory records when merging target lists.
274
259
 
275
- *Ryuta Kamizono*
260
+ *Kevin Sjöberg*
276
261
 
277
- * Don't skip money's type cast for pluck and calculations.
262
+ * Add a new option `:update_only` to `upsert_all` to configure the list of columns to update in case of conflict.
278
263
 
279
- *Ryuta Kamizono*
264
+ Before, you could only customize the update SQL sentence via `:on_duplicate`. There is now a new option `:update_only` that lets you provide a list of columns to update in case of conflict:
280
265
 
281
- * Fix `where` on polymorphic association with non Active Record object.
266
+ ```ruby
267
+ Commodity.upsert_all(
268
+ [
269
+ { id: 2, name: "Copper", price: 4.84 },
270
+ { id: 4, name: "Gold", price: 1380.87 },
271
+ { id: 6, name: "Aluminium", price: 0.35 }
272
+ ],
273
+ update_only: [:price] # Only prices will be updated
274
+ )
275
+ ```
282
276
 
283
- *Ryuta Kamizono*
277
+ *Jorge Manrubia*
284
278
 
285
- * Make sure `db:prepare` works even the schema file doesn't exist.
279
+ * Remove deprecated `ActiveRecord::Result#map!` and `ActiveRecord::Result#collect!`.
286
280
 
287
281
  *Rafael Mendonça França*
288
282
 
289
- * Fix complicated `has_many :through` with nested where condition.
283
+ * Remove deprecated `ActiveRecord::Base.configurations.to_h`.
290
284
 
291
- *Ryuta Kamizono*
285
+ *Rafael Mendonça França*
292
286
 
293
- * Handle STI models for `has_many dependent: :destroy_async`.
287
+ * Remove deprecated `ActiveRecord::Base.configurations.default_hash`.
294
288
 
295
- *Muhammad Usman*
289
+ *Rafael Mendonça França*
296
290
 
297
- * Restore possibility of passing `false` to :polymorphic option of `belongs_to`.
291
+ * Remove deprecated `ActiveRecord::Base.arel_attribute`.
298
292
 
299
- Previously, passing `false` would trigger the option validation logic
300
- to throw an error saying :polymorphic would not be a valid option.
293
+ *Rafael Mendonça França*
301
294
 
302
- *glaszig*
295
+ * Remove deprecated `ActiveRecord::Base.connection_config`.
303
296
 
304
- * Allow adding nonnamed expression indexes to be revertible.
297
+ *Rafael Mendonça França*
305
298
 
306
- Fixes #40732.
299
+ * Filter attributes in SQL logs
307
300
 
308
- Previously, the following code would raise an error, when executed while rolling back,
309
- and the index name should be specified explicitly. Now, the index name is inferred
310
- automatically.
301
+ Previously, SQL queries in logs containing `ActiveRecord::Base.filter_attributes` were not filtered.
302
+
303
+ Now, the filter attributes will be masked `[FILTERED]` in the logs when `prepared_statement` is enabled.
311
304
 
312
- ```ruby
313
- add_index(:items, "to_tsvector('english', description)")
314
305
  ```
306
+ # Before:
307
+ Foo Load (0.2ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "hello"], ["LIMIT", 1]]
315
308
 
316
- *fatkodima*
309
+ # After:
310
+ Foo Load (0.5ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "[FILTERED]"], ["LIMIT", 1]]
311
+ ```
317
312
 
313
+ *Aishwarya Subramanian*
318
314
 
319
- ## Rails 6.1.0 (December 09, 2020) ##
315
+ * Remove deprecated `Tasks::DatabaseTasks.spec`.
320
316
 
321
- * Only warn about negative enums if a positive form that would cause conflicts exists.
317
+ *Rafael Mendonça França*
322
318
 
323
- Fixes #39065.
319
+ * Remove deprecated `Tasks::DatabaseTasks.current_config`.
324
320
 
325
- *Alex Ghiculescu*
321
+ *Rafael Mendonça França*
326
322
 
327
- * Change `attribute_for_inspect` to take `filter_attributes` in consideration.
323
+ * Deprecate `Tasks::DatabaseTasks.schema_file_type`.
328
324
 
329
325
  *Rafael Mendonça França*
330
326
 
331
- * Fix odd behavior of inverse_of with multiple belongs_to to same class.
327
+ * Remove deprecated `Tasks::DatabaseTasks.dump_filename`.
332
328
 
333
- Fixes #35204.
334
-
335
- *Tomoyuki Kai*
329
+ *Rafael Mendonça França*
336
330
 
337
- * Build predicate conditions with objects that delegate `#id` and primary key:
331
+ * Remove deprecated `Tasks::DatabaseTasks.schema_file`.
338
332
 
339
- ```ruby
340
- class AdminAuthor
341
- delegate_missing_to :@author
333
+ *Rafael Mendonça França*
342
334
 
343
- def initialize(author)
344
- @author = author
345
- end
346
- end
335
+ * Remove deprecated `environment` and `name` arguments from `Tasks::DatabaseTasks.schema_up_to_date?`.
347
336
 
348
- Post.where(author: AdminAuthor.new(author))
349
- ```
337
+ *Rafael Mendonça França*
350
338
 
351
- *Sean Doyle*
339
+ * Merging conditions on the same column no longer maintain both conditions,
340
+ and will be consistently replaced by the latter condition.
352
341
 
353
- * Add `connected_to_many` API.
342
+ ```ruby
343
+ # Rails 6.1 (IN clause is replaced by merger side equality condition)
344
+ Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
345
+ # Rails 6.1 (both conflict conditions exists, deprecated)
346
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
347
+ # Rails 6.1 with rewhere to migrate to Rails 7.0's behavior
348
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
349
+ # Rails 7.0 (same behavior with IN clause, mergee side condition is consistently replaced)
350
+ Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
351
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
354
352
 
355
- This API allows applications to connect to multiple databases at once without switching all of them or implementing a deeply nested stack.
353
+ *Rafael Mendonça França*
356
354
 
357
- Before:
355
+ * Remove deprecated support to `Model.reorder(nil).first` to search using non-deterministic order.
358
356
 
359
- AnimalsRecord.connected_to(role: :reading) do
360
- MealsRecord.connected_to(role: :reading) do
361
- Dog.first # read from animals replica
362
- Dinner.first # read from meals replica
363
- Person.first # read from primary writer
364
- end
365
- end
357
+ *Rafael Mendonça França*
366
358
 
367
- After:
359
+ * Remove deprecated rake tasks:
368
360
 
369
- ActiveRecord::Base.connected_to_many([AnimalsRecord, MealsRecord], role: :reading) do
370
- Dog.first # read from animals replica
371
- Dinner.first # read from meals replica
372
- Person.first # read from primary writer
373
- end
361
+ * `db:schema:load_if_ruby`
362
+ * `db:structure:dump`
363
+ * `db:structure:load`
364
+ * `db:structure:load_if_sql`
365
+ * `db:structure:dump:#{name}`
366
+ * `db:structure:load:#{name}`
367
+ * `db:test:load_structure`
368
+ * `db:test:load_structure:#{name}`
374
369
 
375
- *Eileen M. Uchitelle*, *John Crepezzi*
370
+ *Rafael Mendonça França*
376
371
 
377
- * Add option to raise or log for `ActiveRecord::StrictLoadingViolationError`.
372
+ * Remove deprecated `DatabaseConfig#config` method.
378
373
 
379
- 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.
374
+ *Rafael Mendonça França*
380
375
 
381
- Set `config.active_record.action_on_strict_loading_violation` to `:log` errors instead of raising.
376
+ * Rollback transactions when the block returns earlier than expected.
382
377
 
383
- *Eileen M. Uchitelle*
378
+ Before this change, when a transaction block returned early, the transaction would be committed.
384
379
 
385
- * Allow the inverse of a `has_one` association that was previously autosaved to be loaded.
380
+ The problem is that timeouts triggered inside the transaction block was also making the incomplete transaction
381
+ to be committed, so in order to avoid this mistake, the transaction block is rolled back.
386
382
 
387
- Fixes #34255.
383
+ *Rafael Mendonça França*
388
384
 
389
- *Steven Weber*
385
+ * Add middleware for automatic shard swapping.
390
386
 
391
- * Optimise the length of index names for polymorphic references by using the reference name rather than the type and id column names.
387
+ Provides a basic middleware to perform automatic shard swapping. Applications will provide a resolver which will determine for an individual request which shard should be used. Example:
392
388
 
393
- 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.
389
+ ```ruby
390
+ config.active_record.shard_resolver = ->(request) {
391
+ subdomain = request.subdomain
392
+ tenant = Tenant.find_by_subdomain!(subdomain)
393
+ tenant.shard
394
+ }
395
+ ```
394
396
 
395
- This change reduces the chance of that happening by using the reference name, e.g. `index_my_table_on_my_reference`.
397
+ See guides for more details.
396
398
 
397
- Fixes #38655.
399
+ *Eileen M. Uchitelle*, *John Crepezzi*
398
400
 
399
- *Luke Redpath*
401
+ * Remove deprecated support to pass a column to `type_cast`.
400
402
 
401
- * MySQL: Uniqueness validator now respects default database collation,
402
- no longer enforce case sensitive comparison by default.
403
+ *Rafael Mendonça França*
403
404
 
404
- *Ryuta Kamizono*
405
+ * Remove deprecated support to type cast to database values `ActiveRecord::Base` objects.
405
406
 
406
- * Remove deprecated methods from `ActiveRecord::ConnectionAdapters::DatabaseLimits`.
407
+ *Rafael Mendonça França*
407
408
 
408
- `column_name_length`
409
- `table_name_length`
410
- `columns_per_table`
411
- `indexes_per_table`
412
- `columns_per_multicolumn_index`
413
- `sql_query_length`
414
- `joins_per_query`
409
+ * Remove deprecated support to quote `ActiveRecord::Base` objects.
415
410
 
416
411
  *Rafael Mendonça França*
417
412
 
418
- * Remove deprecated `ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_multi_insert?`.
413
+ * Remove deprecacated support to resolve connection using `"primary"` as connection specification name.
419
414
 
420
415
  *Rafael Mendonça França*
421
416
 
422
- * Remove deprecated `ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_foreign_keys_in_create?`.
417
+ * Remove deprecation warning when using `:interval` column is used in PostgreSQL database.
423
418
 
424
- *Rafael Mendonça França*
419
+ Now, interval columns will return `ActiveSupport::Duration` objects instead of strings.
420
+
421
+ To keep the old behavior, you can add this line to your model:
425
422
 
426
- * Remove deprecated `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#supports_ranges?`.
423
+ ```ruby
424
+ attribute :column, :string
425
+ ```
427
426
 
428
427
  *Rafael Mendonça França*
429
428
 
430
- * Remove deprecated `ActiveRecord::Base#update_attributes` and `ActiveRecord::Base#update_attributes!`.
429
+ * Remove deprecated support to YAML load `ActiveRecord::Base` instance in the Rails 4.2 and 4.1 formats.
431
430
 
432
431
  *Rafael Mendonça França*
433
432
 
434
- * Remove deprecated `migrations_path` argument in `ActiveRecord::ConnectionAdapter::SchemaStatements#assume_migrated_upto_version`.
433
+ * Remove deprecated option `:spec_name` in the `configs_for` method.
435
434
 
436
435
  *Rafael Mendonça França*
437
436
 
438
- * Remove deprecated `config.active_record.sqlite3.represent_boolean_as_integer`.
437
+ * Remove deprecated `ActiveRecord::Base.allow_unsafe_raw_sql`.
439
438
 
440
439
  *Rafael Mendonça França*
441
440
 
442
- * `relation.create` does no longer leak scope to class level querying methods
443
- in initialization block and callbacks.
441
+ * Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations.
444
442
 
445
- Before:
446
-
447
- User.where(name: "John").create do |john|
448
- User.find_by(name: "David") # => nil
449
- end
443
+ Fixes #43132
450
444
 
451
- After:
445
+ *Alexander Pauly*
452
446
 
453
- User.where(name: "John").create do |john|
454
- User.find_by(name: "David") # => #<User name: "David", ...>
455
- end
447
+ * Fix `has_many` inversing recursion on models with recursive associations.
456
448
 
457
- *Ryuta Kamizono*
449
+ *Gannon McGibbon*
458
450
 
459
- * Named scope chain does no longer leak scope to class level querying methods.
451
+ * Add `accepts_nested_attributes_for` support for `delegated_type`
460
452
 
461
- class User < ActiveRecord::Base
462
- scope :david, -> { User.where(name: "David") }
463
- end
453
+ ```ruby
454
+ class Entry < ApplicationRecord
455
+ delegated_type :entryable, types: %w[ Message Comment ]
456
+ accepts_nested_attributes_for :entryable
457
+ end
464
458
 
465
- Before:
459
+ entry = Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
460
+ # => #<Entry:0x00>
461
+ # id: 1
462
+ # entryable_id: 1,
463
+ # entryable_type: 'Message'
464
+ # ...>
465
+
466
+ entry.entryable
467
+ # => #<Message:0x01>
468
+ # id: 1
469
+ # content: 'Hello world'
470
+ # ...>
471
+ ```
466
472
 
467
- User.where(name: "John").david
468
- # SELECT * FROM users WHERE name = 'John' AND name = 'David'
473
+ Previously it would raise an error:
469
474
 
470
- After:
475
+ ```ruby
476
+ Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
477
+ # ArgumentError: Cannot build association `entryable'. Are you trying to build a polymorphic one-to-one association?
478
+ ```
471
479
 
472
- User.where(name: "John").david
473
- # SELECT * FROM users WHERE name = 'David'
480
+ *Sjors Baltus*
474
481
 
475
- *Ryuta Kamizono*
482
+ * Use subquery for DELETE with GROUP_BY and HAVING clauses.
476
483
 
477
- * Remove deprecated methods from `ActiveRecord::DatabaseConfigurations`.
484
+ Prior to this change, deletes with GROUP_BY and HAVING were returning an error.
478
485
 
479
- `fetch`
480
- `each`
481
- `first`
482
- `values`
483
- `[]=`
486
+ After this change, GROUP_BY and HAVING are valid clauses in DELETE queries, generating the following query:
484
487
 
485
- *Rafael Mendonça França*
488
+ ```sql
489
+ DELETE FROM "posts" WHERE "posts"."id" IN (
490
+ SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" GROUP BY "posts"."id" HAVING (count(comments.id) >= 2))
491
+ ) [["flagged", "t"]]
492
+ ```
486
493
 
487
- * `where.not` now generates NAND predicates instead of NOR.
494
+ *Ignacio Chiazzo Cardarello*
488
495
 
489
- Before:
496
+ * Use subquery for UPDATE with GROUP_BY and HAVING clauses.
490
497
 
491
- User.where.not(name: "Jon", role: "admin")
492
- # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
498
+ Prior to this change, updates with GROUP_BY and HAVING were being ignored, generating a SQL like this:
493
499
 
494
- After:
500
+ ```sql
501
+ UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
502
+ SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
503
+ ) [["flagged", "t"]]
504
+ ```
495
505
 
496
- User.where.not(name: "Jon", role: "admin")
497
- # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin')
506
+ After this change, GROUP_BY and HAVING clauses are used as a subquery in updates, like this:
498
507
 
499
- *Rafael Mendonça França*
508
+ ```sql
509
+ UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
510
+ SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
511
+ GROUP BY posts.id HAVING (count(comments.id) >= 2)
512
+ ) [["flagged", "t"]]
513
+ ```
500
514
 
501
- * Remove deprecated `ActiveRecord::Result#to_hash` method.
515
+ *Ignacio Chiazzo Cardarello*
502
516
 
503
- *Rafael Mendonça França*
517
+ * Add support for setting the filename of the schema or structure dump in the database config.
504
518
 
505
- * Deprecate `ActiveRecord::Base.allow_unsafe_raw_sql`.
519
+ Applications may now set their the filename or path of the schema / structure dump file in their database configuration.
506
520
 
507
- *Rafael Mendonça França*
521
+ ```yaml
522
+ production:
523
+ primary:
524
+ database: my_db
525
+ schema_dump: my_schema_dump_filename.rb
526
+ animals:
527
+ database: animals_db
528
+ schema_dump: false
529
+ ```
508
530
 
509
- * Remove deprecated support for using unsafe raw SQL in `ActiveRecord::Relation` methods.
531
+ The filename set in `schema_dump` will be used by the application. If set to `false` the schema will not be dumped. The database tasks are responsible for adding the database directory to the filename. If a full path is provided, the Rails tasks will use that instead of `ActiveRecord::DatabaseTasks.db_dir`.
510
532
 
511
- *Rafael Mendonça França*
533
+ *Eileen M. Uchitelle*, *Ryan Kerr*
512
534
 
513
- * Allow users to silence the "Rails couldn't infer whether you are using multiple databases..."
514
- message using `config.active_record.suppress_multiple_database_warning`.
535
+ * Add `ActiveRecord::Base.prohibit_shard_swapping` to prevent attempts to change the shard within a block.
515
536
 
516
- *Omri Gabay*
537
+ *John Crepezzi*, *Eileen M. Uchitelle*
517
538
 
518
- * Connections can be granularly switched for abstract classes when `connected_to` is called.
539
+ * Filter unchanged attributes with default function from insert query when `partial_inserts` is disabled.
519
540
 
520
- 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.
541
+ *Akshay Birajdar*, *Jacopo Beschi*
521
542
 
522
- Example usage:
543
+ * Add support for FILTER clause (SQL:2003) to Arel.
523
544
 
524
- 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`.
545
+ Currently supported by PostgreSQL 9.4+ and SQLite 3.30+.
525
546
 
526
- ```ruby
527
- ActiveRecord::Base.connected_to(role: :reading) do
528
- User.first # reads from default replica
529
- Dog.first # reads from default replica
547
+ *Andrey Novikov*
530
548
 
531
- AnimalsRecord.connected_to(role: :writing, shard: :one) do
532
- User.first # reads from default replica
533
- Dog.first # reads from shard one primary
534
- end
549
+ * Automatically set timestamps on record creation during bulk insert/upsert
535
550
 
536
- User.first # reads from default replica
537
- Dog.first # reads from default replica
551
+ Prior to this change, only updates during an upsert operation (e.g. `upsert_all`) would touch timestamps (`updated_{at,on}`). Now, record creations also touch timestamp columns (`{created,updated}_{at,on}`).
538
552
 
539
- ApplicationRecord.connected_to(role: :writing, shard: :two) do
540
- User.first # reads from shard two primary
541
- Dog.first # reads from default replica
542
- end
543
- end
544
- ```
553
+ This behaviour is controlled by the `<model>.record_timestamps` config, matching the behaviour of `create`, `update`, etc. It can also be overridden by using the `record_timestamps:` keyword argument.
545
554
 
546
- *Eileen M. Uchitelle*, *John Crepezzi*
555
+ Note that this means `upsert_all` on models with `record_timestamps = false` will no longer touch `updated_{at,on}` automatically.
547
556
 
548
- * Allow double-dash comment syntax when querying read-only databases
557
+ *Sam Bostock*
549
558
 
550
- *James Adam*
559
+ * Don't require `role` when passing `shard` to `connected_to`.
551
560
 
552
- * Add `values_at` method.
561
+ `connected_to` can now be called with a `shard` only. Note that `role` is still inherited if `connected_to` calls are nested.
553
562
 
554
- Returns an array containing the values associated with the given methods.
563
+ *Eileen M. Uchitelle*
555
564
 
556
- ```ruby
557
- topic = Topic.first
558
- topic.values_at(:title, :author_name)
559
- # => ["Budget", "Jason"]
560
- ```
565
+ * Add option to lazily load the schema cache on the connection.
561
566
 
562
- Similar to `Hash#values_at` but on an Active Record instance.
567
+ Previously, the only way to load the schema cache in Active Record was through the Railtie on boot. This option provides the ability to load the schema cache on the connection after it's been established. Loading the cache lazily on the connection can be beneficial for Rails applications that use multiple databases because it will load the cache at the time the connection is established. Currently Railties doesn't have access to the connections before boot.
563
568
 
564
- *Guillaume Briday*
569
+ To use the cache, set `config.active_record.lazily_load_schema_cache = true` in your application configuration. In addition a `schema_cache_path` should be set in your database configuration if you don't want to use the default "db/schema_cache.yml" path.
565
570
 
566
- * Fix `read_attribute_before_type_cast` to consider attribute aliases.
571
+ *Eileen M. Uchitelle*
567
572
 
568
- *Marcelo Lauxen*
573
+ * Allow automatic `inverse_of` detection for associations with scopes.
569
574
 
570
- * Support passing record to uniqueness validator `:conditions` callable:
575
+ Automatic `inverse_of` detection now works for associations with scopes. For
576
+ example, the `comments` association here now automatically detects
577
+ `inverse_of: :post`, so we don't need to pass that option:
571
578
 
572
579
  ```ruby
573
- class Article < ApplicationRecord
574
- validates_uniqueness_of :title, conditions: ->(article) {
575
- published_at = article.published_at
576
- where(published_at: published_at.beginning_of_year..published_at.end_of_year)
577
- }
580
+ class Post < ActiveRecord::Base
581
+ has_many :comments, -> { visible }
582
+ end
583
+
584
+ class Comment < ActiveRecord::Base
585
+ belongs_to :post
578
586
  end
579
587
  ```
580
588
 
581
- *Eliot Sykes*
589
+ Note that the automatic detection still won't work if the inverse
590
+ association has a scope. In this example a scope on the `post` association
591
+ would still prevent Rails from finding the inverse for the `comments`
592
+ association.
582
593
 
583
- * `BatchEnumerator#update_all` and `BatchEnumerator#delete_all` now return the
584
- total number of rows affected, just like their non-batched counterparts.
594
+ This will be the default for new apps in Rails 7. To opt in:
585
595
 
586
596
  ```ruby
587
- Person.in_batches.update_all("first_name = 'Eugene'") # => 42
588
- Person.in_batches.delete_all # => 42
597
+ config.active_record.automatic_scope_inversing = true
589
598
  ```
590
599
 
591
- Fixes #40287.
592
-
593
- *Eugene Kenny*
600
+ *Daniel Colson*, *Chris Bloom*
594
601
 
595
- * Add support for PostgreSQL `interval` data type with conversion to
596
- `ActiveSupport::Duration` when loading records from database and
597
- serialization to ISO 8601 formatted duration string on save.
598
- Add support to define a column in migrations and get it in a schema dump.
599
- Optional column precision is supported.
602
+ * Accept optional transaction args to `ActiveRecord::Locking::Pessimistic#with_lock`
600
603
 
601
- To use this in 6.1, you need to place the next string to your model file:
604
+ `#with_lock` now accepts transaction options like `requires_new:`,
605
+ `isolation:`, and `joinable:`
602
606
 
603
- attribute :duration, :interval
607
+ *John Mileham*
604
608
 
605
- To keep old behavior until 6.2 is released:
609
+ * Adds support for deferrable foreign key constraints in PostgreSQL.
606
610
 
607
- attribute :duration, :string
611
+ By default, foreign key constraints in PostgreSQL are checked after each statement. This works for most use cases,
612
+ but becomes a major limitation when creating related records before the parent record is inserted into the database.
613
+ One example of this is looking up / creating a person via one or more unique alias.
608
614
 
609
- Example:
615
+ ```ruby
616
+ Person.transaction do
617
+ alias = Alias
618
+ .create_with(user_id: SecureRandom.uuid)
619
+ .create_or_find_by(name: "DHH")
620
+
621
+ person = Person
622
+ .create_with(name: "David Heinemeier Hansson")
623
+ .create_or_find_by(id: alias.user_id)
624
+ end
625
+ ```
610
626
 
611
- create_table :events do |t|
612
- t.string :name
613
- t.interval :duration
614
- end
627
+ Using the default behavior, the transaction would fail when executing the first `INSERT` statement.
615
628
 
616
- class Event < ApplicationRecord
617
- attribute :duration, :interval
618
- end
629
+ By passing the `:deferrable` option to the `add_foreign_key` statement in migrations, it's possible to defer this
630
+ check.
619
631
 
620
- Event.create!(name: 'Rock Fest', duration: 2.days)
621
- Event.last.duration # => 2 days
622
- Event.last.duration.iso8601 # => "P2D"
623
- Event.new(duration: 'P1DT12H3S').duration # => 1 day, 12 hours, and 3 seconds
624
- Event.new(duration: '1 day') # Unknown value will be ignored and NULL will be written to database
632
+ ```ruby
633
+ add_foreign_key :aliases, :person, deferrable: true
634
+ ```
625
635
 
626
- *Andrey Novikov*
636
+ Passing `deferrable: true` doesn't change the default behavior, but allows manually deferring the check using
637
+ `SET CONSTRAINTS ALL DEFERRED` within a transaction. This will cause the foreign keys to be checked after the
638
+ transaction.
627
639
 
628
- * Allow associations supporting the `dependent:` key to take `dependent: :destroy_async`.
640
+ It's also possible to adjust the default behavior from an immediate check (after the statement), to a deferred check
641
+ (after the transaction):
629
642
 
630
643
  ```ruby
631
- class Account < ActiveRecord::Base
632
- belongs_to :supplier, dependent: :destroy_async
633
- end
644
+ add_foreign_key :aliases, :person, deferrable: :deferred
634
645
  ```
635
646
 
636
- `:destroy_async` will enqueue a job to destroy associated records in the background.
647
+ *Benedikt Deicke*
648
+
649
+ * Allow configuring Postgres password through the socket URL.
637
650
 
638
- *DHH*, *George Claghorn*, *Cory Gwin*, *Rafael Mendonça França*, *Adrianna Chang*
651
+ For example:
652
+ ```ruby
653
+ ActiveRecord::DatabaseConfigurations::UrlConfig.new(
654
+ :production, :production, 'postgres:///?user=user&password=secret&dbname=app', {}
655
+ ).configuration_hash
656
+ ```
639
657
 
640
- * Add `SKIP_TEST_DATABASE` environment variable to disable modifying the test database when `rails db:create` and `rails db:drop` are called.
658
+ will now return,
641
659
 
642
- *Jason Schweier*
660
+ ```ruby
661
+ { :user=>"user", :password=>"secret", :dbname=>"app", :adapter=>"postgresql" }
662
+ ```
643
663
 
644
- * `connects_to` can only be called on `ActiveRecord::Base` or abstract classes.
664
+ *Abeid Ahmed*
645
665
 
646
- 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.
666
+ * PostgreSQL: support custom enum types
647
667
 
648
- *Eileen M. Uchitelle*, *John Crepezzi*
668
+ In migrations, use `create_enum` to add a new enum type, and `t.enum` to add a column.
649
669
 
650
- * All connection adapters `execute` now raises `ActiveRecord::ConnectionNotEstablished` rather than
651
- `ActiveRecord::StatementInvalid` when they encounter a connection error.
670
+ ```ruby
671
+ def up
672
+ create_enum :mood, ["happy", "sad"]
652
673
 
653
- *Jean Boussier*
674
+ change_table :cats do |t|
675
+ t.enum :current_mood, enum_type: "mood", default: "happy", null: false
676
+ end
677
+ end
678
+ ```
654
679
 
655
- * `Mysql2Adapter#quote_string` now raises `ActiveRecord::ConnectionNotEstablished` rather than
656
- `ActiveRecord::StatementInvalid` when it can't connect to the MySQL server.
680
+ Enums will be presented correctly in `schema.rb`. Note that this is only supported by
681
+ the PostgreSQL adapter.
657
682
 
658
- *Jean Boussier*
683
+ *Alex Ghiculescu*
659
684
 
660
- * Add support for check constraints that are `NOT VALID` via `validate: false` (PostgreSQL-only).
685
+ * Avoid COMMENT statements in PostgreSQL structure dumps
661
686
 
662
- *Alex Robbin*
687
+ COMMENT statements are now omitted from the output of `db:structure:dump` when using PostgreSQL >= 11.
688
+ This allows loading the dump without a pgsql superuser account.
663
689
 
664
- * Ensure the default configuration is considered primary or first for an environment
690
+ Fixes #36816, #43107.
665
691
 
666
- 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.
692
+ *Janosch Müller*
667
693
 
668
- *Eileen M. Uchitelle*
694
+ * Add support for generated columns in PostgreSQL adapter
669
695
 
670
- * Allow `where` references association names as joined table name aliases.
696
+ Generated columns are supported since version 12.0 of PostgreSQL. This adds
697
+ support of those to the PostgreSQL adapter.
671
698
 
672
699
  ```ruby
673
- class Comment < ActiveRecord::Base
674
- enum label: [:default, :child]
675
- has_many :children, class_name: "Comment", foreign_key: :parent_id
700
+ create_table :users do |t|
701
+ t.string :name
702
+ t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true
676
703
  end
677
-
678
- # ... FROM comments LEFT OUTER JOIN comments children ON ... WHERE children.label = 1
679
- Comment.includes(:children).where("children.label": "child")
680
704
  ```
681
705
 
682
- *Ryuta Kamizono*
706
+ *Michał Begejowicz*
683
707
 
684
- * Support storing demodulized class name for polymorphic type.
685
708
 
686
- Before Rails 6.1, storing demodulized class name is supported only for STI type
687
- by `store_full_sti_class` class attribute.
709
+ ## Rails 7.0.0.alpha2 (September 15, 2021) ##
688
710
 
689
- Now `store_full_class_name` class attribute can handle both STI and polymorphic types.
711
+ * No changes.
690
712
 
691
- *Ryuta Kamizono*
692
713
 
693
- * Deprecate `rails db:structure:{load, dump}` tasks and extend
694
- `rails db:schema:{load, dump}` tasks to work with either `:ruby` or `:sql` format,
695
- depending on `config.active_record.schema_format` configuration value.
714
+ ## Rails 7.0.0.alpha1 (September 15, 2021) ##
696
715
 
697
- *fatkodima*
716
+ * Remove warning when overwriting existing scopes
698
717
 
699
- * Respect the `select` values for eager loading.
718
+ Removes the following unnecessary warning message that appeared when overwriting existing scopes
700
719
 
701
- ```ruby
702
- post = Post.select("UPPER(title) AS title").first
703
- post.title # => "WELCOME TO THE WEBLOG"
704
- post.body # => ActiveModel::MissingAttributeError
720
+ ```
721
+ Creating scope :my_scope_name. Overwriting existing method "MyClass.my_scope_name" when overwriting existing scopes
722
+ ```
705
723
 
706
- # Rails 6.0 (ignore the `select` values)
707
- post = Post.select("UPPER(title) AS title").eager_load(:comments).first
708
- post.title # => "Welcome to the weblog"
709
- post.body # => "Such a lovely day"
724
+ *Weston Ganger*
710
725
 
711
- # Rails 6.1 (respect the `select` values)
712
- post = Post.select("UPPER(title) AS title").eager_load(:comments).first
713
- post.title # => "WELCOME TO THE WEBLOG"
714
- post.body # => ActiveModel::MissingAttributeError
715
- ```
726
+ * Use full precision for `updated_at` in `insert_all`/`upsert_all`
716
727
 
717
- *Ryuta Kamizono*
728
+ `CURRENT_TIMESTAMP` provides differing precision depending on the database,
729
+ and not all databases support explicitly specifying additional precision.
718
730
 
719
- * Allow attribute's default to be configured but keeping its own type.
731
+ Instead, we delegate to the new `connection.high_precision_current_timestamp`
732
+ for the SQL to produce a high precision timestamp on the current database.
720
733
 
721
- ```ruby
722
- class Post < ActiveRecord::Base
723
- attribute :written_at, default: -> { Time.now.utc }
724
- end
734
+ Fixes #42992
725
735
 
726
- # Rails 6.0
727
- Post.type_for_attribute(:written_at) # => #<Type::Value ... precision: nil, ...>
736
+ *Sam Bostock*
728
737
 
729
- # Rails 6.1
730
- Post.type_for_attribute(:written_at) # => #<Type::DateTime ... precision: 6, ...>
731
- ```
738
+ * Add ssl support for postgresql database tasks
732
739
 
733
- *Ryuta Kamizono*
740
+ Add `PGSSLMODE`, `PGSSLCERT`, `PGSSLKEY` and `PGSSLROOTCERT` to pg_env from database config
741
+ when running postgresql database tasks.
734
742
 
735
- * Allow default to be configured for Enum.
743
+ ```yaml
744
+ # config/database.yml
736
745
 
737
- ```ruby
738
- class Book < ActiveRecord::Base
739
- enum status: [:proposed, :written, :published], _default: :published
740
- end
746
+ production:
747
+ sslmode: verify-full
748
+ sslcert: client.crt
749
+ sslkey: client.key
750
+ sslrootcert: ca.crt
751
+ ```
752
+
753
+ Environment variables
741
754
 
742
- Book.new.status # => "published"
755
+ ```
756
+ PGSSLMODE=verify-full
757
+ PGSSLCERT=client.crt
758
+ PGSSLKEY=client.key
759
+ PGSSLROOTCERT=ca.crt
743
760
  ```
744
761
 
745
- *Ryuta Kamizono*
762
+ Fixes #42994
746
763
 
747
- * Deprecate YAML loading from legacy format older than Rails 5.0.
764
+ *Michael Bayucot*
748
765
 
749
- *Ryuta Kamizono*
766
+ * Avoid scoping update callbacks in `ActiveRecord::Relation#update!`.
750
767
 
751
- * Added the setting `ActiveRecord::Base.immutable_strings_by_default`, which
752
- allows you to specify that all string columns should be frozen unless
753
- otherwise specified. This will reduce memory pressure for applications which
754
- do not generally mutate string properties of Active Record objects.
768
+ Making it consistent with how scoping is applied only to the query in `ActiveRecord::Relation#update`
769
+ and not also to the callbacks from the update itself.
755
770
 
756
- *Sean Griffin*, *Ryuta Kamizono*
771
+ *Dylan Thacker-Smith*
757
772
 
758
- * Deprecate `map!` and `collect!` on `ActiveRecord::Result`.
773
+ * Fix 2 cases that inferred polymorphic class from the association's `foreign_type`
774
+ using `String#constantize` instead of the model's `polymorphic_class_for`.
759
775
 
760
- *Ryuta Kamizono*
776
+ When updating a polymorphic association, the old `foreign_type` was not inferred correctly when:
777
+ 1. `touch`ing the previously associated record
778
+ 2. updating the previously associated record's `counter_cache`
761
779
 
762
- * Support `relation.and` for intersection as Set theory.
780
+ *Jimmy Bourassa*
763
781
 
764
- ```ruby
765
- david_and_mary = Author.where(id: [david, mary])
766
- mary_and_bob = Author.where(id: [mary, bob])
782
+ * Add config option for ignoring tables when dumping the schema cache.
767
783
 
768
- david_and_mary.merge(mary_and_bob) # => [mary, bob]
784
+ Applications can now be configured to ignore certain tables when dumping the schema cache.
769
785
 
770
- david_and_mary.and(mary_and_bob) # => [mary]
771
- david_and_mary.or(mary_and_bob) # => [david, mary, bob]
772
- ```
786
+ The configuration option can table an array of tables:
773
787
 
774
- *Ryuta Kamizono*
788
+ ```ruby
789
+ config.active_record.schema_cache_ignored_tables = ["ignored_table", "another_ignored_table"]
790
+ ```
775
791
 
776
- * Merging conditions on the same column no longer maintain both conditions,
777
- and will be consistently replaced by the latter condition in Rails 6.2.
778
- To migrate to Rails 6.2's behavior, use `relation.merge(other, rewhere: true)`.
792
+ Or a regex:
779
793
 
780
794
  ```ruby
781
- # Rails 6.1 (IN clause is replaced by merger side equality condition)
782
- Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
795
+ config.active_record.schema_cache_ignored_tables = [/^_/]
796
+ ```
783
797
 
784
- # Rails 6.1 (both conflict conditions exists, deprecated)
785
- Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
798
+ *Eileen M. Uchitelle*
786
799
 
787
- # Rails 6.1 with rewhere to migrate to Rails 6.2's behavior
788
- Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
800
+ * Make schema cache methods return consistent results.
789
801
 
790
- # Rails 6.2 (same behavior with IN clause, mergee side condition is consistently replaced)
791
- Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
792
- Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
793
- ```
802
+ Previously the schema cache methods `primary_keys`, `columns`, `columns_hash`, and `indexes`
803
+ would behave differently than one another when a table didn't exist and differently across
804
+ database adapters. This change unifies the behavior so each method behaves the same regardless
805
+ of adapter.
794
806
 
795
- *Ryuta Kamizono*
807
+ The behavior now is:
796
808
 
797
- * Do not mark Postgresql MAC address and UUID attributes as changed when the assigned value only varies by case.
809
+ `columns`: (unchanged) raises a db error if the table does not exist.
810
+ `columns_hash`: (unchanged) raises a db error if the table does not exist.
811
+ `primary_keys`: (unchanged) returns `nil` if the table does not exist.
812
+ `indexes`: (changed for mysql2) returns `[]` if the table does not exist.
798
813
 
799
- *Peter Fry*
814
+ *Eileen M. Uchitelle*
800
815
 
801
- * Resolve issue with insert_all unique_by option when used with expression index.
816
+ * Reestablish connection to previous database after after running `db:schema:load:name`
802
817
 
803
- When the `:unique_by` option of `ActiveRecord::Persistence.insert_all` and
804
- `ActiveRecord::Persistence.upsert_all` was used with the name of an expression index, an error
805
- was raised. Adding a guard around the formatting behavior for the `:unique_by` corrects this.
818
+ After running `db:schema:load:name` the previous connection is restored.
806
819
 
807
- Usage:
820
+ *Jacopo Beschi*
808
821
 
809
- ```ruby
810
- create_table :books, id: :integer, force: true do |t|
811
- t.column :name, :string
812
- t.index "lower(name)", unique: true
813
- end
822
+ * Add database config option `database_tasks`
814
823
 
815
- Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_name
816
- ```
824
+ If you would like to connect to an external database without any database
825
+ management tasks such as schema management, migrations, seeds, etc. you can set
826
+ the per database config option `database_tasks: false`
817
827
 
818
- Fixes #39516.
828
+ ```yaml
829
+ # config/database.yml
819
830
 
820
- *Austen Madden*
831
+ production:
832
+ primary:
833
+ database: my_database
834
+ adapter: mysql2
835
+ animals:
836
+ database: my_animals_database
837
+ adapter: mysql2
838
+ database_tasks: false
839
+ ```
821
840
 
822
- * Add basic support for CHECK constraints to database migrations.
841
+ *Weston Ganger*
823
842
 
824
- Usage:
843
+ * Fix `ActiveRecord::InternalMetadata` to not be broken by `config.active_record.record_timestamps = false`
825
844
 
826
- ```ruby
827
- add_check_constraint :products, "price > 0", name: "price_check"
828
- remove_check_constraint :products, name: "price_check"
829
- ```
845
+ Since the model always create the timestamp columns, it has to set them, otherwise it breaks
846
+ various DB management tasks.
830
847
 
831
- *fatkodima*
848
+ Fixes #42983
832
849
 
833
- * Add `ActiveRecord::Base.strict_loading_by_default` and `ActiveRecord::Base.strict_loading_by_default=`
834
- to enable/disable strict_loading mode by default for a model. The configuration's value is
835
- inheritable by subclasses, but they can override that value and it will not impact parent class.
850
+ * Add `ActiveRecord::QueryLogs`.
836
851
 
837
- Usage:
852
+ Configurable tags can be automatically added to all SQL queries generated by Active Record.
838
853
 
839
854
  ```ruby
840
- class Developer < ApplicationRecord
841
- self.strict_loading_by_default = true
842
-
843
- has_many :projects
855
+ # config/application.rb
856
+ module MyApp
857
+ class Application < Rails::Application
858
+ config.active_record.query_log_tags_enabled = true
859
+ end
844
860
  end
845
-
846
- dev = Developer.first
847
- dev.projects.first
848
- # => ActiveRecord::StrictLoadingViolationError Exception: Developer is marked as strict_loading and Project cannot be lazily loaded.
849
861
  ```
850
862
 
851
- *bogdanvlviv*
852
-
853
- * Deprecate passing an Active Record object to `quote`/`type_cast` directly.
854
-
855
- *Ryuta Kamizono*
856
-
857
- * Default engine `ENGINE=InnoDB` is no longer dumped to make schema more agnostic.
858
-
859
- Before:
863
+ By default the application, controller and action details are added to the query tags:
860
864
 
861
865
  ```ruby
862
- create_table "accounts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
866
+ class BooksController < ApplicationController
867
+ def index
868
+ @books = Book.all
869
+ end
863
870
  end
864
871
  ```
865
872
 
866
- After:
873
+ ```ruby
874
+ GET /books
875
+ # SELECT * FROM books /*application:MyApp;controller:books;action:index*/
876
+ ```
877
+
878
+ Custom tags containing static values and Procs can be defined in the application configuration:
867
879
 
868
880
  ```ruby
869
- create_table "accounts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
870
- end
881
+ config.active_record.query_log_tags = [
882
+ :application,
883
+ :controller,
884
+ :action,
885
+ {
886
+ custom_static: "foo",
887
+ custom_dynamic: -> { Time.now }
888
+ }
889
+ ]
871
890
  ```
872
891
 
873
- *Ryuta Kamizono*
892
+ *Keeran Raj Hawoldar*, *Eileen M. Uchitelle*, *Kasper Timm Hansen*
893
+
894
+ * Added support for multiple databases to `rails db:setup` and `rails db:reset`.
895
+
896
+ *Ryan Hall*
874
897
 
875
- * Added delegated type as an alternative to single-table inheritance for representing class hierarchies.
876
- See ActiveRecord::DelegatedType for the full description.
898
+ * Add `ActiveRecord::Relation#structurally_compatible?`.
877
899
 
878
- *DHH*
900
+ Adds a query method by which a user can tell if the relation that they're
901
+ about to use for `#or` or `#and` is structurally compatible with the
902
+ receiver.
879
903
 
880
- * Deprecate aggregations with group by duplicated fields.
904
+ *Kevin Newton*
881
905
 
882
- To migrate to Rails 6.2's behavior, use `uniq!(:group)` to deduplicate group fields.
906
+ * Add `ActiveRecord::QueryMethods#in_order_of`.
907
+
908
+ This allows you to specify an explicit order that you'd like records
909
+ returned in based on a SQL expression. By default, this will be accomplished
910
+ using a case statement, as in:
883
911
 
884
912
  ```ruby
885
- accounts = Account.group(:firm_id)
913
+ Post.in_order_of(:id, [3, 5, 1])
914
+ ```
886
915
 
887
- # duplicated group fields, deprecated.
888
- accounts.merge(accounts.where.not(credit_limit: nil)).sum(:credit_limit)
889
- # => {
890
- # [1, 1] => 50,
891
- # [2, 2] => 60
892
- # }
916
+ will generate the SQL:
893
917
 
894
- # use `uniq!(:group)` to deduplicate group fields.
895
- accounts.merge(accounts.where.not(credit_limit: nil)).uniq!(:group).sum(:credit_limit)
896
- # => {
897
- # 1 => 50,
898
- # 2 => 60
899
- # }
918
+ ```sql
919
+ SELECT "posts".* FROM "posts" ORDER BY CASE "posts"."id" WHEN 3 THEN 1 WHEN 5 THEN 2 WHEN 1 THEN 3 ELSE 4 END ASC
900
920
  ```
901
921
 
902
- *Ryuta Kamizono*
922
+ However, because this functionality is built into MySQL in the form of the
923
+ `FIELD` function, that connection adapter will generate the following SQL
924
+ instead:
903
925
 
904
- * Deprecate duplicated query annotations.
926
+ ```sql
927
+ SELECT "posts".* FROM "posts" ORDER BY FIELD("posts"."id", 1, 5, 3) DESC
928
+ ```
905
929
 
906
- To migrate to Rails 6.2's behavior, use `uniq!(:annotate)` to deduplicate query annotations.
930
+ *Kevin Newton*
907
931
 
908
- ```ruby
909
- accounts = Account.where(id: [1, 2]).annotate("david and mary")
932
+ * Fix `eager_loading?` when ordering with `Symbol`.
910
933
 
911
- # duplicated annotations, deprecated.
912
- accounts.merge(accounts.rewhere(id: 3))
913
- # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */ /* david and mary */
934
+ `eager_loading?` is triggered correctly when using `order` with symbols.
914
935
 
915
- # use `uniq!(:annotate)` to deduplicate annotations.
916
- accounts.merge(accounts.rewhere(id: 3)).uniq!(:annotate)
917
- # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */
936
+ ```ruby
937
+ scope = Post.includes(:comments).order(:"comments.label")
938
+ => true
918
939
  ```
919
940
 
920
- *Ryuta Kamizono*
921
-
922
- * Resolve conflict between counter cache and optimistic locking.
941
+ *Jacopo Beschi*
923
942
 
924
- Bump an Active Record instance's lock version after updating its counter
925
- cache. This avoids raising an unnecessary `ActiveRecord::StaleObjectError`
926
- upon subsequent transactions by maintaining parity with the corresponding
927
- database record's `lock_version` column.
943
+ * Two change tracking methods are added for `belongs_to` associations.
928
944
 
929
- Fixes #16449.
945
+ The `association_changed?` method (assuming an association named `:association`) returns true
946
+ if a different associated object has been assigned and the foreign key will be updated in the
947
+ next save.
930
948
 
931
- *Aaron Lipman*
949
+ The `association_previously_changed?` method returns true if the previous save updated the
950
+ association to reference a different associated object.
932
951
 
933
- * Support merging option `:rewhere` to allow mergee side condition to be replaced exactly.
952
+ *George Claghorn*
934
953
 
935
- ```ruby
936
- david_and_mary = Author.where(id: david.id..mary.id)
954
+ * Add option to disable schema dump per-database.
937
955
 
938
- # both conflict conditions exists
939
- david_and_mary.merge(Author.where(id: bob)) # => []
956
+ Dumping the schema is on by default for all databases in an application. To turn it off for a
957
+ specific database, use the `schema_dump` option:
940
958
 
941
- # mergee side condition is replaced by rewhere
942
- david_and_mary.merge(Author.rewhere(id: bob)) # => [bob]
959
+ ```yaml
960
+ # config/database.yml
943
961
 
944
- # mergee side condition is replaced by rewhere option
945
- david_and_mary.merge(Author.where(id: bob), rewhere: true) # => [bob]
962
+ production:
963
+ schema_dump: false
946
964
  ```
947
965
 
948
- *Ryuta Kamizono*
966
+ *Luis Vasconcellos*, *Eileen M. Uchitelle*
967
+
968
+ * Fix `eager_loading?` when ordering with `Hash` syntax.
949
969
 
950
- * Add support for finding records based on signed ids, which are tamper-proof, verified ids that can be
951
- set to expire and scoped with a purpose. This is particularly useful for things like password reset
952
- or email verification, where you want the bearer of the signed id to be able to interact with the
953
- underlying record, but usually only within a certain time period.
970
+ `eager_loading?` is triggered correctly when using `order` with hash syntax
971
+ on an outer table.
954
972
 
955
973
  ```ruby
956
- signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset
974
+ Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading?
975
+ # => true
976
+ ```
957
977
 
958
- User.find_signed signed_id # => nil, since the purpose does not match
978
+ *Jacopo Beschi*
959
979
 
960
- travel 16.minutes
961
- User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired
980
+ * Move the forcing of clear text encoding to the `ActiveRecord::Encryption::Encryptor`.
962
981
 
963
- travel_back
964
- User.find_signed signed_id, purpose: :password_reset # => User.first
982
+ Fixes #42699.
965
983
 
966
- User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
967
- ```
984
+ *J Smith*
968
985
 
969
- *DHH*
986
+ * `partial_inserts` is now disabled by default in new apps.
970
987
 
971
- * Support `ALGORITHM = INSTANT` DDL option for index operations on MySQL.
988
+ This will be the default for new apps in Rails 7. To opt in:
972
989
 
973
- *Ryuta Kamizono*
990
+ ```ruby
991
+ config.active_record.partial_inserts = true
992
+ ```
974
993
 
975
- * Fix index creation to preserve index comment in bulk change table on MySQL.
994
+ If a migration removes the default value of a column, this option
995
+ would cause old processes to no longer be able to create new records.
976
996
 
977
- *Ryuta Kamizono*
997
+ If you need to remove a column, you should first use `ignored_columns`
998
+ to stop using it.
978
999
 
979
- * Allow `unscope` to be aware of table name qualified values.
1000
+ *Jean Boussier*
1001
+
1002
+ * Rails can now verify foreign keys after loading fixtures in tests.
980
1003
 
981
- It is possible to unscope only the column in the specified table.
1004
+ This will be the default for new apps in Rails 7. To opt in:
982
1005
 
983
1006
  ```ruby
984
- posts = Post.joins(:comments).group(:"posts.hidden")
985
- posts = posts.where("posts.hidden": false, "comments.hidden": false)
1007
+ config.active_record.verify_foreign_keys_for_fixtures = true
1008
+ ```
986
1009
 
987
- posts.count
988
- # => { false => 10 }
1010
+ Tests will not run if there is a foreign key constraint violation in your fixture data.
989
1011
 
990
- # unscope both hidden columns
991
- posts.unscope(where: :hidden).count
992
- # => { false => 11, true => 1 }
1012
+ The feature is supported by SQLite and PostgreSQL, other adapters can also add support for it.
993
1013
 
994
- # unscope only comments.hidden column
995
- posts.unscope(where: :"comments.hidden").count
996
- # => { false => 11 }
997
- ```
1014
+ *Alex Ghiculescu*
998
1015
 
999
- *Ryuta Kamizono*, *Slava Korolev*
1016
+ * Clear cached `has_one` association after setting `belongs_to` association to `nil`.
1000
1017
 
1001
- * Fix `rewhere` to truly overwrite collided where clause by new where clause.
1018
+ After setting a `belongs_to` relation to `nil` and updating an unrelated attribute on the owner,
1019
+ the owner should still return `nil` on the `has_one` relation.
1002
1020
 
1003
- ```ruby
1004
- steve = Person.find_by(name: "Steve")
1005
- david = Author.find_by(name: "David")
1021
+ Fixes #42597.
1006
1022
 
1007
- relation = Essay.where(writer: steve)
1023
+ *Michiel de Mare*
1008
1024
 
1009
- # Before
1010
- relation.rewhere(writer: david).to_a # => []
1025
+ * OpenSSL constants are now used for Digest computations.
1011
1026
 
1012
- # After
1013
- relation.rewhere(writer: david).to_a # => [david]
1014
- ```
1027
+ *Dirkjan Bussink*
1015
1028
 
1016
- *Ryuta Kamizono*
1029
+ * Adds support for `if_not_exists` to `add_foreign_key` and `if_exists` to `remove_foreign_key`.
1017
1030
 
1018
- * Inspect time attributes with subsec and time zone offset.
1031
+ Applications can set their migrations to ignore exceptions raised when adding a foreign key
1032
+ that already exists or when removing a foreign key that does not exist.
1033
+
1034
+ Example Usage:
1019
1035
 
1020
1036
  ```ruby
1021
- p Knot.create
1022
- => #<Knot id: 1, created_at: "2016-05-05 01:29:47.116928000 +0000">
1037
+ class AddAuthorsForeignKeyToArticles < ActiveRecord::Migration[7.0]
1038
+ def change
1039
+ add_foreign_key :articles, :authors, if_not_exists: true
1040
+ end
1041
+ end
1023
1042
  ```
1024
1043
 
1025
- *akinomaeni*, *Jonathan Hefner*
1044
+ ```ruby
1045
+ class RemoveAuthorsForeignKeyFromArticles < ActiveRecord::Migration[7.0]
1046
+ def change
1047
+ remove_foreign_key :articles, :authors, if_exists: true
1048
+ end
1049
+ end
1050
+ ```
1026
1051
 
1027
- * Deprecate passing a column to `type_cast`.
1052
+ *Roberto Miranda*
1028
1053
 
1029
- *Ryuta Kamizono*
1054
+ * Prevent polluting ENV during postgresql structure dump/load.
1030
1055
 
1031
- * Deprecate `in_clause_length` and `allowed_index_name_length` in `DatabaseLimits`.
1056
+ Some configuration parameters were provided to pg_dump / psql via
1057
+ environment variables which persisted beyond the command being run, and may
1058
+ have caused subsequent commands and connections to fail. Tasks running
1059
+ across multiple postgresql databases like `rails db:test:prepare` may have
1060
+ been affected.
1032
1061
 
1033
- *Ryuta Kamizono*
1062
+ *Samuel Cochran*
1034
1063
 
1035
- * Support bulk insert/upsert on relation to preserve scope values.
1064
+ * Set precision 6 by default for `datetime` columns.
1036
1065
 
1037
- *Josef Šimánek*, *Ryuta Kamizono*
1066
+ By default, datetime columns will have microseconds precision instead of seconds precision.
1038
1067
 
1039
- * Preserve column comment value on changing column name on MySQL.
1068
+ *Roberto Miranda*
1040
1069
 
1041
- *Islam Taha*
1070
+ * Allow preloading of associations with instance dependent scopes.
1042
1071
 
1043
- * Add support for `if_exists` option for removing an index.
1072
+ *John Hawthorn*, *John Crepezzi*, *Adam Hess*, *Eileen M. Uchitelle*, *Dinah Shi*
1044
1073
 
1045
- 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.
1074
+ * Do not try to rollback transactions that failed due to a `ActiveRecord::TransactionRollbackError`.
1046
1075
 
1047
- *Eileen M. Uchitelle*
1076
+ *Jamie McCarthy*
1048
1077
 
1049
- * Remove ibm_db, informix, mssql, oracle, and oracle12 Arel visitors which are not used in the code base.
1078
+ * Active Record Encryption will now encode values as UTF-8 when using deterministic
1079
+ encryption. The encoding is part of the encrypted payload, so different encodings for
1080
+ different values result in different ciphertexts. This can break unique constraints and
1081
+ queries.
1050
1082
 
1051
- *Ryuta Kamizono*
1083
+ The new behavior is configurable via `active_record.encryption.forced_encoding_for_deterministic_encryption`
1084
+ that is `Encoding::UTF_8` by default. It can be disabled by setting it to `nil`.
1052
1085
 
1053
- * Prevent `build_association` from `touching` a parent record if the record isn't persisted for `has_one` associations.
1086
+ *Jorge Manrubia*
1054
1087
 
1055
- Fixes #38219.
1088
+ * The MySQL adapter now cast numbers and booleans bind parameters to string for safety reasons.
1056
1089
 
1057
- *Josh Brody*
1090
+ When comparing a string and a number in a query, MySQL converts the string to a number. So for
1091
+ instance `"foo" = 0`, will implicitly cast `"foo"` to `0` and will evaluate to `TRUE` which can
1092
+ lead to security vulnerabilities.
1058
1093
 
1059
- * Add support for `if_not_exists` option for adding index.
1094
+ Active Record already protect against that vulnerability when it knows the type of the column
1095
+ being compared, however until now it was still vulnerable when using bind parameters:
1060
1096
 
1061
- The `add_index` method respects `if_not_exists` option. If it is set to true
1062
- index won't be added.
1097
+ ```ruby
1098
+ User.where("login_token = ?", 0).first
1099
+ ```
1063
1100
 
1064
- Usage:
1101
+ Would perform:
1065
1102
 
1066
- ```ruby
1067
- add_index :users, :account_id, if_not_exists: true
1103
+ ```sql
1104
+ SELECT * FROM `users` WHERE `login_token` = 0 LIMIT 1;
1068
1105
  ```
1069
1106
 
1070
- The `if_not_exists` option passed to `create_table` also gets propagated to indexes
1071
- created within that migration so that if table and its indexes exist then there is no
1072
- attempt to create them again.
1107
+ Now it will perform:
1073
1108
 
1074
- *Prathamesh Sonpatki*
1109
+ ```sql
1110
+ SELECT * FROM `users` WHERE `login_token` = '0' LIMIT 1;
1111
+ ```
1075
1112
 
1076
- * Add `ActiveRecord::Base#previously_new_record?` to show if a record was new before the last save.
1113
+ *Jean Boussier*
1077
1114
 
1078
- *Tom Ward*
1115
+ * Fixture configurations (`_fixture`) are now strictly validated.
1079
1116
 
1080
- * Support descending order for `find_each`, `find_in_batches`, and `in_batches`.
1117
+ If an error will be raised if that entry contains unknown keys while previously it
1118
+ would silently have no effects.
1081
1119
 
1082
- 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.
1120
+ *Jean Boussier*
1083
1121
 
1084
- This change allows reversing the order, batching from newest to oldest. This is useful when you need to process newer batches of records first.
1122
+ * Add `ActiveRecord::Base.update!` that works like `ActiveRecord::Base.update` but raises exceptions.
1085
1123
 
1086
- Pass `order: :desc` to yield batches in descending order. The default remains `order: :asc`.
1124
+ This allows for the same behavior as the instance method `#update!` at a class level.
1087
1125
 
1088
1126
  ```ruby
1089
- Person.find_each(order: :desc) do |person|
1090
- person.party_all_night!
1091
- end
1127
+ Person.update!(:all, state: "confirmed")
1092
1128
  ```
1093
1129
 
1094
- *Alexey Vasiliev*
1130
+ *Dorian Marié*
1095
1131
 
1096
- * Fix `insert_all` with enum values.
1132
+ * Add `ActiveRecord::Base#attributes_for_database`.
1097
1133
 
1098
- Fixes #38716.
1134
+ Returns attributes with values for assignment to the database.
1099
1135
 
1100
- *Joel Blum*
1136
+ *Chris Salzberg*
1101
1137
 
1102
- * Add support for `db:rollback:name` for multiple database applications.
1138
+ * Use an empty query to check if the PostgreSQL connection is still active.
1103
1139
 
1104
- Multiple database applications will now raise if `db:rollback` is call and recommend using the `db:rollback:[NAME]` to rollback migrations.
1140
+ An empty query is faster than `SELECT 1`.
1105
1141
 
1106
- *Eileen M. Uchitelle*
1142
+ *Heinrich Lee Yu*
1107
1143
 
1108
- * `Relation#pick` now uses already loaded results instead of making another query.
1144
+ * Add `ActiveRecord::Base#previously_persisted?`.
1109
1145
 
1110
- *Eugene Kenny*
1146
+ Returns `true` if the object has been previously persisted but now it has been deleted.
1111
1147
 
1112
- * Deprecate using `return`, `break` or `throw` to exit a transaction block after writes.
1148
+ * Deprecate `partial_writes` in favor of `partial_inserts` and `partial_updates`.
1113
1149
 
1114
- *Dylan Thacker-Smith*
1150
+ This allows to have a different behavior on update and create.
1115
1151
 
1116
- * Dump the schema or structure of a database when calling `db:migrate:name`.
1152
+ *Jean Boussier*
1117
1153
 
1118
- 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.
1154
+ * Fix compatibility with `psych >= 4`.
1119
1155
 
1120
- Going forward, calls to `rails db:migrate:name` will dump the schema (or structure) of the database being migrated.
1156
+ Starting in Psych 4.0.0 `YAML.load` behaves like `YAML.safe_load`. To preserve compatibility,
1157
+ Active Record's schema cache loader and `YAMLColumn` now uses `YAML.unsafe_load` if available.
1121
1158
 
1122
- *Kyle Thompson*
1159
+ *Jean Boussier*
1123
1160
 
1124
- * Reset the `ActiveRecord::Base` connection after `rails db:migrate:name`.
1161
+ * `ActiveRecord::Base.logger` is now a `class_attribute`.
1125
1162
 
1126
- 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.
1163
+ This means it can no longer be accessed directly through `@@logger`, and that setting `logger =`
1164
+ on a subclass won't change the parent's logger.
1127
1165
 
1128
- *Kyle Thompson*
1166
+ *Jean Boussier*
1129
1167
 
1130
- * Disallow calling `connected_to` on subclasses of `ActiveRecord::Base`.
1168
+ * Add `.asc.nulls_first` for all databases. Unfortunately MySQL still doesn't like `nulls_last`.
1131
1169
 
1132
- 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.
1170
+ *Keenan Brock*
1133
1171
 
1134
- *Eileen M. Uchitelle*, *John Crepezzi*
1172
+ * Improve performance of `one?` and `many?` by limiting the generated count query to 2 results.
1135
1173
 
1136
- * Add support for horizontal sharding to `connects_to` and `connected_to`.
1174
+ *Gonzalo Riestra*
1137
1175
 
1138
- 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.
1176
+ * Don't check type when using `if_not_exists` on `add_column`.
1139
1177
 
1140
- Usage:
1178
+ Previously, if a migration called `add_column` with the `if_not_exists` option set to true
1179
+ the `column_exists?` check would look for a column with the same name and type as the migration.
1141
1180
 
1142
- Given the following configuration:
1181
+ Recently it was discovered that the type passed to the migration is not always the same type
1182
+ as the column after migration. For example a column set to `:mediumblob` in the migration will
1183
+ be casted to `binary` when calling `column.type`. Since there is no straightforward way to cast
1184
+ the type to the database type without running the migration, we opted to drop the type check from
1185
+ `add_column`. This means that migrations adding a duplicate column with a different type will no
1186
+ longer raise an error.
1143
1187
 
1144
- ```yaml
1145
- # config/database.yml
1146
- production:
1147
- primary:
1148
- database: my_database
1149
- primary_shard_one:
1150
- database: my_database_shard_one
1151
- ```
1188
+ *Eileen M. Uchitelle*
1152
1189
 
1153
- Connect to multiple shards:
1190
+ * Log a warning message when running SQLite in production.
1154
1191
 
1155
- ```ruby
1156
- class ApplicationRecord < ActiveRecord::Base
1157
- self.abstract_class = true
1192
+ Using SQLite in production ENV is generally discouraged. SQLite is also the default adapter
1193
+ in a new Rails application.
1194
+ For the above reasons log a warning message when running SQLite in production.
1158
1195
 
1159
- connects_to shards: {
1160
- default: { writing: :primary },
1161
- shard_one: { writing: :primary_shard_one }
1162
- }
1163
- ```
1196
+ The warning can be disabled by setting `config.active_record.sqlite3_production_warning=false`.
1197
+
1198
+ *Jacopo Beschi*
1199
+
1200
+ * Add option to disable joins for `has_one` associations.
1201
+
1202
+ In a multiple database application, associations can't join across
1203
+ databases. When set, this option instructs Rails to generate 2 or
1204
+ more queries rather than generating joins for `has_one` associations.
1164
1205
 
1165
- Swap between shards in your controller / model code:
1206
+ Set the option on a has one through association:
1166
1207
 
1167
1208
  ```ruby
1168
- ActiveRecord::Base.connected_to(shard: :shard_one) do
1169
- # Read from shard one
1209
+ class Person
1210
+ has_one :dog
1211
+ has_one :veterinarian, through: :dog, disable_joins: true
1170
1212
  end
1171
1213
  ```
1172
1214
 
1173
- The horizontal sharding API also supports read replicas. See guides for more details.
1215
+ Then instead of generating join SQL, two queries are used for `@person.veterinarian`:
1174
1216
 
1175
- *Eileen M. Uchitelle*, *John Crepezzi*
1217
+ ```
1218
+ SELECT "dogs"."id" FROM "dogs" WHERE "dogs"."person_id" = ? [["person_id", 1]]
1219
+ SELECT "veterinarians".* FROM "veterinarians" WHERE "veterinarians"."dog_id" = ? [["dog_id", 1]]
1220
+ ```
1176
1221
 
1177
- * Deprecate `spec_name` in favor of `name` on database configurations.
1222
+ *Sarah Vessels*, *Eileen M. Uchitelle*
1178
1223
 
1179
- The accessors for `spec_name` on `configs_for` and `DatabaseConfig` are deprecated. Please use `name` instead.
1224
+ * `Arel::Visitors::Dot` now renders a complete set of properties when visiting
1225
+ `Arel::Nodes::SelectCore`, `SelectStatement`, `InsertStatement`, `UpdateStatement`, and
1226
+ `DeleteStatement`, which fixes #42026. Previously, some properties were omitted.
1180
1227
 
1181
- Deprecated behavior:
1228
+ *Mike Dalessio*
1182
1229
 
1183
- ```ruby
1184
- db_config = ActiveRecord::Base.configurations.configs_for(env_name: "development", spec_name: "primary")
1185
- db_config.spec_name
1186
- ```
1230
+ * `Arel::Visitors::Dot` now supports `Arel::Nodes::Bin`, `Case`, `CurrentRow`, `Distinct`,
1231
+ `DistinctOn`, `Else`, `Except`, `InfixOperation`, `Intersect`, `Lock`, `NotRegexp`, `Quoted`,
1232
+ `Regexp`, `UnaryOperation`, `Union`, `UnionAll`, `When`, and `With`. Previously, these node
1233
+ types caused an exception to be raised by `Arel::Visitors::Dot#accept`.
1187
1234
 
1188
- New behavior:
1235
+ *Mike Dalessio*
1236
+
1237
+ * Optimize `remove_columns` to use a single SQL statement.
1189
1238
 
1190
1239
  ```ruby
1191
- db_config = ActiveRecord::Base.configurations.configs_for(env_name: "development", name: "primary")
1192
- db_config.name
1240
+ remove_columns :my_table, :col_one, :col_two
1193
1241
  ```
1194
1242
 
1195
- *Eileen M. Uchitelle*
1196
-
1197
- * Add additional database-specific rake tasks for multi-database users.
1198
-
1199
- Previously, `rails db:create`, `rails db:drop`, and `rails db:migrate` were the only rails tasks that could operate on a single
1200
- database. For example:
1243
+ Now results in the following SQL:
1201
1244
 
1202
- ```
1203
- rails db:create
1204
- rails db:create:primary
1205
- rails db:create:animals
1206
- rails db:drop
1207
- rails db:drop:primary
1208
- rails db:drop:animals
1209
- rails db:migrate
1210
- rails db:migrate:primary
1211
- rails db:migrate:animals
1245
+ ```sql
1246
+ ALTER TABLE "my_table" DROP COLUMN "col_one", DROP COLUMN "col_two"
1212
1247
  ```
1213
1248
 
1214
- With these changes, `rails db:schema:dump`, `rails db:schema:load`, `rails db:structure:dump`, `rails db:structure:load` and
1215
- `rails db:test:prepare` can additionally operate on a single database. For example:
1249
+ *Jon Dufresne*
1216
1250
 
1217
- ```
1218
- rails db:schema:dump
1219
- rails db:schema:dump:primary
1220
- rails db:schema:dump:animals
1221
- rails db:schema:load
1222
- rails db:schema:load:primary
1223
- rails db:schema:load:animals
1224
- rails db:structure:dump
1225
- rails db:structure:dump:primary
1226
- rails db:structure:dump:animals
1227
- rails db:structure:load
1228
- rails db:structure:load:primary
1229
- rails db:structure:load:animals
1230
- rails db:test:prepare
1231
- rails db:test:prepare:primary
1232
- rails db:test:prepare:animals
1233
- ```
1251
+ * Ensure `has_one` autosave association callbacks get called once.
1234
1252
 
1235
- *Kyle Thompson*
1253
+ Change the `has_one` autosave callback to be non cyclic as well.
1254
+ By doing this the autosave callback are made more consistent for
1255
+ all 3 cases: `has_many`, `has_one`, and `belongs_to`.
1236
1256
 
1237
- * Add support for `strict_loading` mode on association declarations.
1257
+ *Petrik de Heus*
1238
1258
 
1239
- 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.
1259
+ * Add option to disable joins for associations.
1240
1260
 
1241
- Usage:
1261
+ In a multiple database application, associations can't join across
1262
+ databases. When set, this option instructs Rails to generate 2 or
1263
+ more queries rather than generating joins for associations.
1264
+
1265
+ Set the option on a has many through association:
1242
1266
 
1243
1267
  ```ruby
1244
- class Developer < ApplicationRecord
1245
- has_many :projects, strict_loading: true
1268
+ class Dog
1269
+ has_many :treats, through: :humans, disable_joins: true
1270
+ has_many :humans
1246
1271
  end
1272
+ ```
1273
+
1274
+ Then instead of generating join SQL, two queries are used for `@dog.treats`:
1247
1275
 
1248
- dev = Developer.first
1249
- dev.projects.first
1250
- # => ActiveRecord::StrictLoadingViolationError: The projects association is marked as strict_loading and cannot be lazily loaded.
1276
+ ```
1277
+ SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ? [["dog_id", 1]]
1278
+ SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?) [["human_id", 1], ["human_id", 2], ["human_id", 3]]
1251
1279
  ```
1252
1280
 
1253
- *Kevin Deisz*
1281
+ *Eileen M. Uchitelle*, *Aaron Patterson*, *Lee Quarella*
1254
1282
 
1255
- * Add support for `strict_loading` mode to prevent lazy loading of records.
1283
+ * Add setting for enumerating column names in SELECT statements.
1256
1284
 
1257
- 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.
1285
+ Adding a column to a PostgreSQL database, for example, while the application is running can
1286
+ change the result of wildcard `SELECT *` queries, which invalidates the result
1287
+ of cached prepared statements and raises a `PreparedStatementCacheExpired` error.
1258
1288
 
1259
- Usage:
1289
+ When enabled, Active Record will avoid wildcards and always include column names
1290
+ in `SELECT` queries, which will return consistent results and avoid prepared
1291
+ statement errors.
1292
+
1293
+ Before:
1260
1294
 
1261
1295
  ```ruby
1262
- dev = Developer.strict_loading.first
1263
- dev.audit_logs.to_a
1264
- # => ActiveRecord::StrictLoadingViolationError: Developer is marked as strict_loading and AuditLog cannot be lazily loaded.
1296
+ Book.limit(5)
1297
+ # SELECT * FROM books LIMIT 5
1265
1298
  ```
1266
1299
 
1267
- *Eileen M. Uchitelle*, *Aaron Patterson*
1300
+ After:
1268
1301
 
1269
- * Add support for PostgreSQL 11+ partitioned indexes when using `upsert_all`.
1302
+ ```ruby
1303
+ # config/application.rb
1304
+ module MyApp
1305
+ class Application < Rails::Application
1306
+ config.active_record.enumerate_columns_in_select_statements = true
1307
+ end
1308
+ end
1270
1309
 
1271
- *Sebastián Palma*
1310
+ # or, configure per-model
1311
+ class Book < ApplicationRecord
1312
+ self.enumerate_columns_in_select_statements = true
1313
+ end
1314
+ ```
1272
1315
 
1273
- * Adds support for `if_not_exists` to `add_column` and `if_exists` to `remove_column`.
1316
+ ```ruby
1317
+ Book.limit(5)
1318
+ # SELECT id, author_id, name, format, status, language, etc FROM books LIMIT 5
1319
+ ```
1274
1320
 
1275
- 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.
1321
+ *Matt Duszynski*
1276
1322
 
1277
- Example Usage:
1323
+ * Allow passing SQL as `on_duplicate` value to `#upsert_all` to make it possible to use raw SQL to update columns on conflict:
1278
1324
 
1279
1325
  ```ruby
1280
- class AddColumnTitle < ActiveRecord::Migration[6.1]
1281
- def change
1282
- add_column :posts, :title, :string, if_not_exists: true
1283
- end
1284
- end
1326
+ Book.upsert_all(
1327
+ [{ id: 1, status: 1 }, { id: 2, status: 1 }],
1328
+ on_duplicate: Arel.sql("status = GREATEST(books.status, EXCLUDED.status)")
1329
+ )
1285
1330
  ```
1286
1331
 
1332
+ *Vladimir Dementyev*
1333
+
1334
+ * Allow passing SQL as `returning` statement to `#upsert_all`:
1335
+
1287
1336
  ```ruby
1288
- class RemoveColumnTitle < ActiveRecord::Migration[6.1]
1289
- def change
1290
- remove_column :posts, :title, if_exists: true
1291
- end
1292
- end
1337
+ Article.insert_all(
1338
+ [
1339
+ { title: "Article 1", slug: "article-1", published: false },
1340
+ { title: "Article 2", slug: "article-2", published: false }
1341
+ ],
1342
+ returning: Arel.sql("id, (xmax = '0') as inserted, name as new_name")
1343
+ )
1293
1344
  ```
1294
1345
 
1346
+ *Vladimir Dementyev*
1347
+
1348
+ * Deprecate `legacy_connection_handling`.
1349
+
1295
1350
  *Eileen M. Uchitelle*
1296
1351
 
1297
- * Regexp-escape table name for MS SQL Server.
1352
+ * Add attribute encryption support.
1298
1353
 
1299
- 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.
1354
+ Encrypted attributes are declared at the model level. These
1355
+ are regular Active Record attributes backed by a column with
1356
+ the same name. The system will transparently encrypt these
1357
+ attributes before saving them into the database and will
1358
+ decrypt them when retrieving their values.
1300
1359
 
1301
- *Larry Reid*
1302
1360
 
1303
- * Store advisory locks on their own named connection.
1361
+ ```ruby
1362
+ class Person < ApplicationRecord
1363
+ encrypts :name
1364
+ encrypts :email_address, deterministic: true
1365
+ end
1366
+ ```
1304
1367
 
1305
- 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.
1368
+ You can learn more in the [Active Record Encryption
1369
+ guide](https://edgeguides.rubyonrails.org/active_record_encryption.html).
1306
1370
 
1307
- 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.
1371
+ *Jorge Manrubia*
1308
1372
 
1309
- *Eileen M. Uchitelle*, *John Crepezzi*
1373
+ * Changed Arel predications `contains` and `overlaps` to use
1374
+ `quoted_node` so that PostgreSQL arrays are quoted properly.
1310
1375
 
1311
- * Allow schema cache path to be defined in the database configuration file.
1376
+ *Bradley Priest*
1312
1377
 
1313
- For example:
1378
+ * Add mode argument to record level `strict_loading!`.
1314
1379
 
1315
- ```yaml
1316
- development:
1317
- adapter: postgresql
1318
- database: blog_development
1319
- pool: 5
1320
- schema_cache_path: tmp/schema/main.yml
1380
+ This argument can be used when enabling strict loading for a single record
1381
+ to specify that we only want to raise on n plus one queries.
1382
+
1383
+ ```ruby
1384
+ developer.strict_loading!(mode: :n_plus_one_only)
1385
+
1386
+ developer.projects.to_a # Does not raise
1387
+ developer.projects.first.client # Raises StrictLoadingViolationError
1321
1388
  ```
1322
1389
 
1323
- *Katrina Owen*
1390
+ Previously, enabling strict loading would cause any lazily loaded
1391
+ association to raise an error. Using `n_plus_one_only` mode allows us to
1392
+ lazily load belongs_to, has_many, and other associations that are fetched
1393
+ through a single query.
1324
1394
 
1325
- * Deprecate `#remove_connection` in favor of `#remove_connection_pool` when called on the handler.
1395
+ *Dinah Shi*
1326
1396
 
1327
- `#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.
1397
+ * Fix Float::INFINITY assignment to datetime column with postgresql adapter.
1328
1398
 
1329
- *Eileen M. Uchitelle*, *John Crepezzi*
1399
+ Before:
1330
1400
 
1331
- * Deprecate `#default_hash` and it's alias `#[]` on database configurations.
1401
+ ```ruby
1402
+ # With this config
1403
+ ActiveRecord::Base.time_zone_aware_attributes = true
1332
1404
 
1333
- Applications should use `configs_for`. `#default_hash` and `#[]` will be removed in 6.2.
1405
+ # and the following schema:
1406
+ create_table "postgresql_infinities" do |t|
1407
+ t.datetime "datetime"
1408
+ end
1334
1409
 
1335
- *Eileen M. Uchitelle*, *John Crepezzi*
1410
+ # This test fails
1411
+ record = PostgresqlInfinity.create!(datetime: Float::INFINITY)
1412
+ assert_equal Float::INFINITY, record.datetime # record.datetime gets nil
1413
+ ```
1336
1414
 
1337
- * Add scale support to `ActiveRecord::Validations::NumericalityValidator`.
1415
+ After this commit, `record.datetime` gets `Float::INFINITY` as expected.
1338
1416
 
1339
- *Gannon McGibbon*
1417
+ *Shunichi Ikegami*
1340
1418
 
1341
- * Find orphans by looking for missing relations through chaining `where.missing`:
1419
+ * Type cast enum values by the original attribute type.
1342
1420
 
1343
- Before:
1421
+ The notable thing about this change is that unknown labels will no longer match 0 on MySQL.
1344
1422
 
1345
1423
  ```ruby
1346
- Post.left_joins(:author).where(authors: { id: nil })
1424
+ class Book < ActiveRecord::Base
1425
+ enum :status, { proposed: 0, written: 1, published: 2 }
1426
+ end
1347
1427
  ```
1348
1428
 
1349
- After:
1429
+ Before:
1350
1430
 
1351
1431
  ```ruby
1352
- Post.where.missing(:author)
1432
+ # SELECT `books`.* FROM `books` WHERE `books`.`status` = 'prohibited' LIMIT 1
1433
+ Book.find_by(status: :prohibited)
1434
+ # => #<Book id: 1, status: "proposed", ...> (for mysql2 adapter)
1435
+ # => ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for type integer: "prohibited" (for postgresql adapter)
1436
+ # => nil (for sqlite3 adapter)
1353
1437
  ```
1354
1438
 
1355
- *Tom Rossi*
1356
-
1357
- * Ensure `:reading` connections always raise if a write is attempted.
1358
-
1359
- 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`.
1439
+ After:
1360
1440
 
1361
- *Eileen M. Uchitelle*
1441
+ ```ruby
1442
+ # SELECT `books`.* FROM `books` WHERE `books`.`status` IS NULL LIMIT 1
1443
+ Book.find_by(status: :prohibited)
1444
+ # => nil (for all adapters)
1445
+ ```
1362
1446
 
1363
- * Deprecate `"primary"` as the `connection_specification_name` for `ActiveRecord::Base`.
1447
+ *Ryuta Kamizono*
1364
1448
 
1365
- `"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"`.
1449
+ * Fixtures for `has_many :through` associations now load timestamps on join tables.
1366
1450
 
1367
- *Eileen M. Uchitelle*, *John Crepezzi*
1451
+ Given this fixture:
1368
1452
 
1369
- * Add `ActiveRecord::Validations::NumericalityValidator` with
1370
- support for casting floats using a database columns' precision value.
1453
+ ```yml
1454
+ ### monkeys.yml
1455
+ george:
1456
+ name: George the Monkey
1457
+ fruits: apple
1371
1458
 
1372
- *Gannon McGibbon*
1459
+ ### fruits.yml
1460
+ apple:
1461
+ name: apple
1462
+ ```
1373
1463
 
1374
- * Enforce fresh ETag header after a collection's contents change by adding
1375
- ActiveRecord::Relation#cache_key_with_version. This method will be used by
1376
- ActionController::ConditionalGet to ensure that when collection cache versioning
1377
- is enabled, requests using ConditionalGet don't return the same ETag header
1378
- after a collection is modified.
1464
+ If the join table (`fruit_monkeys`) contains `created_at` or `updated_at` columns,
1465
+ these will now be populated when loading the fixture. Previously, fixture loading
1466
+ would crash if these columns were required, and leave them as null otherwise.
1379
1467
 
1380
- Fixes #38078.
1468
+ *Alex Ghiculescu*
1381
1469
 
1382
- *Aaron Lipman*
1470
+ * Allow applications to configure the thread pool for async queries.
1383
1471
 
1384
- * Skip test database when running `db:create` or `db:drop` in development
1385
- with `DATABASE_URL` set.
1472
+ Some applications may want one thread pool per database whereas others want to use
1473
+ a single global thread pool for all queries. By default, Rails will set `async_query_executor`
1474
+ to `nil` which will not initialize any executor. If `load_async` is called and no executor
1475
+ has been configured, the query will be executed in the foreground.
1386
1476
 
1387
- *Brian Buchalter*
1477
+ To create one thread pool for all database connections to use applications can set
1478
+ `config.active_record.async_query_executor` to `:global_thread_pool` and optionally define
1479
+ `config.active_record.global_executor_concurrency`. This defaults to 4. For applications that want
1480
+ to have a thread pool for each database connection, `config.active_record.async_query_executor` can
1481
+ be set to `:multi_thread_pool`. The configuration for each thread pool is set in the database
1482
+ configuration.
1388
1483
 
1389
- * Don't allow mutations on the database configurations hash.
1484
+ *Eileen M. Uchitelle*
1390
1485
 
1391
- 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.
1486
+ * Allow new syntax for `enum` to avoid leading `_` from reserved options.
1392
1487
 
1393
1488
  Before:
1394
1489
 
1395
1490
  ```ruby
1396
- @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
1397
- @db_config.configuration_hash.merge!(idle_timeout: "0.02")
1491
+ class Book < ActiveRecord::Base
1492
+ enum status: [ :proposed, :written ], _prefix: true, _scopes: false
1493
+ enum cover: [ :hard, :soft ], _suffix: true, _default: :hard
1494
+ end
1398
1495
  ```
1399
1496
 
1400
1497
  After:
1401
1498
 
1402
1499
  ```ruby
1403
- @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
1404
- config = @db_config.configuration_hash.merge(idle_timeout: "0.02")
1405
- db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(@db_config.env_name, @db_config.spec_name, config)
1500
+ class Book < ActiveRecord::Base
1501
+ enum :status, [ :proposed, :written ], prefix: true, scopes: false
1502
+ enum :cover, [ :hard, :soft ], suffix: true, default: :hard
1503
+ end
1406
1504
  ```
1407
1505
 
1408
- *Eileen M. Uchitelle*, *John Crepezzi*
1506
+ *Ryuta Kamizono*
1409
1507
 
1410
- * Remove `:connection_id` from the `sql.active_record` notification.
1508
+ * Add `ActiveRecord::Relation#load_async`.
1411
1509
 
1412
- *Aaron Patterson*, *Rafael Mendonça França*
1510
+ This method schedules the query to be performed asynchronously from a thread pool.
1413
1511
 
1414
- * The `:name` key will no longer be returned as part of `DatabaseConfig#configuration_hash`. Please use `DatabaseConfig#owner_name` instead.
1512
+ If the result is accessed before a background thread had the opportunity to perform
1513
+ the query, it will be performed in the foreground.
1415
1514
 
1416
- *Eileen M. Uchitelle*, *John Crepezzi*
1515
+ This is useful for queries that can be performed long enough before their result will be
1516
+ needed, or for controllers which need to perform several independent queries.
1417
1517
 
1418
- * ActiveRecord's `belongs_to_required_by_default` flag can now be set per model.
1518
+ ```ruby
1519
+ def index
1520
+ @categories = Category.some_complex_scope.load_async
1521
+ @posts = Post.some_complex_scope.load_async
1522
+ end
1523
+ ```
1419
1524
 
1420
- You can now opt-out/opt-in specific models from having their associations required
1421
- by default.
1525
+ Active Record logs will also include timing info for the duration of how long
1526
+ the main thread had to wait to access the result. This timing is useful to know
1527
+ whether or not it's worth to load the query asynchronously.
1422
1528
 
1423
- This change is meant to ease the process of migrating all your models to have
1424
- their association required.
1529
+ ```
1530
+ DEBUG -- : Category Load (62.1ms) SELECT * FROM `categories` LIMIT 50
1531
+ DEBUG -- : ASYNC Post Load (64ms) (db time 126.1ms) SELECT * FROM `posts` LIMIT 100
1532
+ ```
1425
1533
 
1426
- *Edouard Chin*
1534
+ The duration in the first set of parens is how long the main thread was blocked
1535
+ waiting for the results, and the second set of parens with "db time" is how long
1536
+ the entire query took to execute.
1427
1537
 
1428
- * The `connection_config` method has been deprecated, please use `connection_db_config` instead which will return a `DatabaseConfigurations::DatabaseConfig` instead of a `Hash`.
1538
+ *Jean Boussier*
1429
1539
 
1430
- *Eileen M. Uchitelle*, *John Crepezzi*
1540
+ * Implemented `ActiveRecord::Relation#excluding` method.
1431
1541
 
1432
- * Retain explicit selections on the base model after applying `includes` and `joins`.
1542
+ This method excludes the specified record (or collection of records) from
1543
+ the resulting relation:
1433
1544
 
1434
- Resolves #34889.
1545
+ ```ruby
1546
+ Post.excluding(post)
1547
+ Post.excluding(post_one, post_two)
1548
+ ```
1435
1549
 
1436
- *Patrick Rebsch*
1550
+ Also works on associations:
1437
1551
 
1438
- * 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.
1552
+ ```ruby
1553
+ post.comments.excluding(comment)
1554
+ post.comments.excluding(comment_one, comment_two)
1555
+ ```
1439
1556
 
1440
- *Eileen M. Uchitelle*, *John Crepezzi*
1557
+ This is short-hand for `Post.where.not(id: post.id)` (for a single record)
1558
+ and `Post.where.not(id: [post_one.id, post_two.id])` (for a collection).
1441
1559
 
1442
- * Allow attributes to be fetched from Arel node groupings.
1560
+ *Glen Crawford*
1443
1561
 
1444
- *Jeff Emminger*, *Gannon McGibbon*
1562
+ * Skip optimised #exist? query when #include? is called on a relation
1563
+ with a having clause.
1445
1564
 
1446
- * A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgreSQL `options`.
1565
+ Relations that have aliased select values AND a having clause that
1566
+ references an aliased select value would generate an error when
1567
+ #include? was called, due to an optimisation that would generate
1568
+ call #exists? on the relation instead, which effectively alters
1569
+ the select values of the query (and thus removes the aliased select
1570
+ values), but leaves the having clause intact. Because the having
1571
+ clause is then referencing an aliased column that is no longer
1572
+ present in the simplified query, an ActiveRecord::InvalidStatement
1573
+ error was raised.
1447
1574
 
1448
- *Joshua Flanagan*
1575
+ A sample query affected by this problem:
1449
1576
 
1450
- * 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`.
1577
+ ```ruby
1578
+ Author.select('COUNT(*) as total_posts', 'authors.*')
1579
+ .joins(:posts)
1580
+ .group(:id)
1581
+ .having('total_posts > 2')
1582
+ .include?(Author.first)
1583
+ ```
1451
1584
 
1452
- *John Crepezzi*
1585
+ This change adds an addition check to the condition that skips the
1586
+ simplified #exists? query, which simply checks for the presence of
1587
+ a having clause.
1453
1588
 
1454
- * Specifying `implicit_order_column` now subsorts the records by primary key if available to ensure deterministic results.
1589
+ Fixes #41417.
1455
1590
 
1456
- *Paweł Urbanek*
1591
+ *Michael Smart*
1457
1592
 
1458
- * `where(attr => [])` now loads an empty result without making a query.
1593
+ * Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
1594
+ without Rails knowledge (e.g., if app gets killed during long-running query or due to Rack::Timeout), app won't end
1595
+ up in perpetual crash state for being inconsistent with PostgreSQL.
1459
1596
 
1460
- *John Hawthorn*
1597
+ *wbharding*, *Martin Tepper*
1461
1598
 
1462
- * Fixed the performance regression for `primary_keys` introduced MySQL 8.0.
1599
+ * Add ability to apply `scoping` to `all_queries`.
1463
1600
 
1464
- *Hiroyuki Ishii*
1601
+ Some applications may want to use the `scoping` method but previously it only
1602
+ worked on certain types of queries. This change allows the `scoping` method to apply
1603
+ to all queries for a model in a block.
1465
1604
 
1466
- * Add support for `belongs_to` to `has_many` inversing.
1605
+ ```ruby
1606
+ Post.where(blog_id: post.blog_id).scoping(all_queries: true) do
1607
+ post.update(title: "a post title") # adds `posts.blog_id = 1` to the query
1608
+ end
1609
+ ```
1467
1610
 
1468
- *Gannon McGibbon*
1611
+ *Eileen M. Uchitelle*
1469
1612
 
1470
- * Allow length configuration for `has_secure_token` method. The minimum length
1471
- is set at 24 characters.
1613
+ * `ActiveRecord::Calculations.calculate` called with `:average`
1614
+ (aliased as `ActiveRecord::Calculations.average`) will now use column-based
1615
+ type casting. This means that floating-point number columns will now be
1616
+ aggregated as `Float` and decimal columns will be aggregated as `BigDecimal`.
1472
1617
 
1473
- Before:
1618
+ Integers are handled as a special case returning `BigDecimal` always
1619
+ (this was the case before already).
1474
1620
 
1475
1621
  ```ruby
1476
- has_secure_token :auth_token
1622
+ # With the following schema:
1623
+ create_table "measurements" do |t|
1624
+ t.float "temperature"
1625
+ end
1626
+
1627
+ # Before:
1628
+ Measurement.average(:temperature).class
1629
+ # => BigDecimal
1630
+
1631
+ # After:
1632
+ Measurement.average(:temperature).class
1633
+ # => Float
1477
1634
  ```
1478
1635
 
1479
- After:
1636
+ Before this change, Rails just called `to_d` on average aggregates from the
1637
+ database adapter. This is not the case anymore. If you relied on that kind
1638
+ of magic, you now need to register your own `ActiveRecord::Type`
1639
+ (see `ActiveRecord::Attributes::ClassMethods` for documentation).
1640
+
1641
+ *Josua Schmid*
1642
+
1643
+ * PostgreSQL: introduce `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type`.
1644
+
1645
+ This setting controls what native type Active Record should use when you call `datetime` in
1646
+ a migration or schema. It takes a symbol which must correspond to one of the configured
1647
+ `NATIVE_DATABASE_TYPES`. The default is `:timestamp`, meaning `t.datetime` in a migration
1648
+ will create a "timestamp without time zone" column. To use "timestamp with time zone",
1649
+ change this to `:timestamptz` in an initializer.
1650
+
1651
+ You should run `bin/rails db:migrate` to rebuild your schema.rb if you change this.
1652
+
1653
+ *Alex Ghiculescu*
1654
+
1655
+ * PostgreSQL: handle `timestamp with time zone` columns correctly in `schema.rb`.
1656
+
1657
+ Previously they dumped as `t.datetime :column_name`, now they dump as `t.timestamptz :column_name`,
1658
+ and are created as `timestamptz` columns when the schema is loaded.
1659
+
1660
+ *Alex Ghiculescu*
1661
+
1662
+ * Removing trailing whitespace when matching columns in
1663
+ `ActiveRecord::Sanitization.disallow_raw_sql!`.
1664
+
1665
+ *Gannon McGibbon*, *Adrian Hirt*
1666
+
1667
+ * Expose a way for applications to set a `primary_abstract_class`.
1668
+
1669
+ Multiple database applications that use a primary abstract class that is not
1670
+ named `ApplicationRecord` can now set a specific class to be the `primary_abstract_class`.
1480
1671
 
1481
1672
  ```ruby
1482
- has_secure_token :default_token # 24 characters
1483
- has_secure_token :auth_token, length: 36 # 36 characters
1484
- has_secure_token :invalid_token, length: 12 # => ActiveRecord::SecureToken::MinimumLengthError
1673
+ class PrimaryApplicationRecord
1674
+ self.primary_abstract_class
1675
+ end
1485
1676
  ```
1486
1677
 
1487
- *Bernardo de Araujo*
1678
+ When an application boots it automatically connects to the primary or first database in the
1679
+ database configuration file. In a multiple database application that then call `connects_to`
1680
+ needs to know that the default connection is the same as the `ApplicationRecord` connection.
1681
+ However, some applications have a differently named `ApplicationRecord`. This prevents Active
1682
+ Record from opening duplicate connections to the same database.
1488
1683
 
1489
- * Deprecate `DatabaseConfigurations#to_h`. These connection hashes are still available via `ActiveRecord::Base.configurations.configs_for`.
1490
-
1491
- *Eileen Uchitelle*, *John Crepezzi*
1684
+ *Eileen M. Uchitelle*, *John Crepezzi*
1492
1685
 
1493
- * 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.
1686
+ * Support hash config for `structure_dump_flags` and `structure_load_flags` flags.
1687
+ Now that Active Record supports multiple databases configuration,
1688
+ we need a way to pass specific flags for dump/load databases since
1689
+ the options are not the same for different adapters.
1690
+ We can use in the original way:
1494
1691
 
1495
- *John Crepezzi*, *Eileen Uchitelle*
1692
+ ```ruby
1693
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-defaults', '--skip-add-drop-table']
1694
+ # or
1695
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table'
1696
+ ```
1496
1697
 
1497
- * Allow column names to be passed to `remove_index` positionally along with other options.
1698
+ And also use it passing a hash, with one or more keys, where the key
1699
+ is the adapter
1498
1700
 
1499
- Passing other options can be necessary to make `remove_index` correctly reversible.
1701
+ ```ruby
1702
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = {
1703
+ mysql2: ['--no-defaults', '--skip-add-drop-table'],
1704
+ postgres: '--no-tablespaces'
1705
+ }
1706
+ ```
1500
1707
 
1501
- Before:
1708
+ *Gustavo Gonzalez*
1502
1709
 
1503
- add_index :reports, :report_id # => works
1504
- add_index :reports, :report_id, unique: true # => works
1505
- remove_index :reports, :report_id # => works
1506
- remove_index :reports, :report_id, unique: true # => ArgumentError
1710
+ * Connection specification now passes the "url" key as a configuration for the
1711
+ adapter if the "url" protocol is "jdbc", "http", or "https". Previously only
1712
+ urls with the "jdbc" prefix were passed to the Active Record Adapter, others
1713
+ are assumed to be adapter specification urls.
1507
1714
 
1508
- After:
1715
+ Fixes #41137.
1509
1716
 
1510
- remove_index :reports, :report_id, unique: true # => works
1717
+ *Jonathan Bracy*
1511
1718
 
1512
- *Eugene Kenny*
1719
+ * Allow to opt-out of `strict_loading` mode on a per-record base.
1513
1720
 
1514
- * Allow bulk `ALTER` statements to drop and recreate indexes with the same name.
1721
+ This is useful when strict loading is enabled application wide or on a
1722
+ model level.
1515
1723
 
1516
- *Eugene Kenny*
1724
+ ```ruby
1725
+ class User < ApplicationRecord
1726
+ has_many :bookmarks
1727
+ has_many :articles, strict_loading: true
1728
+ end
1517
1729
 
1518
- * `insert`, `insert_all`, `upsert`, and `upsert_all` now clear the query cache.
1730
+ user = User.first
1731
+ user.articles # => ActiveRecord::StrictLoadingViolationError
1732
+ user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy>
1519
1733
 
1520
- *Eugene Kenny*
1734
+ user.strict_loading!(true) # => true
1735
+ user.bookmarks # => ActiveRecord::StrictLoadingViolationError
1521
1736
 
1522
- * Call `while_preventing_writes` directly from `connected_to`.
1737
+ user.strict_loading!(false) # => false
1738
+ user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy>
1739
+ user.articles.strict_loading!(false) # => #<ActiveRecord::Associations::CollectionProxy>
1740
+ ```
1523
1741
 
1524
- 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)`.
1742
+ *Ayrton De Craene*
1525
1743
 
1526
- 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.
1744
+ * Add `FinderMethods#sole` and `#find_sole_by` to find and assert the
1745
+ presence of exactly one record.
1527
1746
 
1528
- *Eileen M. Uchitelle*
1747
+ Used when you need a single row, but also want to assert that there aren't
1748
+ multiple rows matching the condition; especially for when database
1749
+ constraints aren't enough or are impractical.
1529
1750
 
1530
- * Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.
1751
+ ```ruby
1752
+ Product.where(["price = %?", price]).sole
1753
+ # => ActiveRecord::RecordNotFound (if no Product with given price)
1754
+ # => #<Product ...> (if one Product with given price)
1755
+ # => ActiveRecord::SoleRecordExceeded (if more than one Product with given price)
1531
1756
 
1532
- *Kir Shatrov*
1757
+ user.api_keys.find_sole_by(key: key)
1758
+ # as above
1759
+ ```
1533
1760
 
1534
- * Stop trying to read yaml file fixtures when loading Active Record fixtures.
1761
+ *Asherah Connor*
1535
1762
 
1536
- *Gannon McGibbon*
1763
+ * Makes `ActiveRecord::AttributeMethods::Query` respect the getter overrides defined in the model.
1537
1764
 
1538
- * Deprecate `.reorder(nil)` with `.first` / `.first!` taking non-deterministic result.
1765
+ Before:
1539
1766
 
1540
- To continue taking non-deterministic result, use `.take` / `.take!` instead.
1767
+ ```ruby
1768
+ class User
1769
+ def admin
1770
+ false # Overriding the getter to always return false
1771
+ end
1772
+ end
1541
1773
 
1542
- *Ryuta Kamizono*
1774
+ user = User.first
1775
+ user.update(admin: true)
1543
1776
 
1544
- * Preserve user supplied joins order as much as possible.
1777
+ user.admin # false (as expected, due to the getter overwrite)
1778
+ user.admin? # true (not expected, returned the DB column value)
1779
+ ```
1545
1780
 
1546
- Fixes #36761, #34328, #24281, #12953.
1781
+ After this commit, `user.admin?` above returns false, as expected.
1547
1782
 
1548
- *Ryuta Kamizono*
1783
+ Fixes #40771.
1549
1784
 
1550
- * Allow `matches_regex` and `does_not_match_regexp` on the MySQL Arel visitor.
1785
+ *Felipe*
1551
1786
 
1552
- *James Pearson*
1787
+ * Allow delegated_type to be specified primary_key and foreign_key.
1553
1788
 
1554
- * Allow specifying fixtures to be ignored by setting `ignore` in YAML file's '_fixture' section.
1789
+ Since delegated_type assumes that the foreign_key ends with `_id`,
1790
+ `singular_id` defined by it does not work when the foreign_key does
1791
+ not end with `id`. This change fixes it by taking into account
1792
+ `primary_key` and `foreign_key` in the options.
1555
1793
 
1556
- *Tongfei Gao*
1794
+ *Ryota Egusa*
1557
1795
 
1558
- * Make the DATABASE_URL env variable only affect the primary connection. Add new env variables for multiple databases.
1796
+ * Expose an `invert_where` method that will invert all scope conditions.
1559
1797
 
1560
- *John Crepezzi*, *Eileen Uchitelle*
1798
+ ```ruby
1799
+ class User
1800
+ scope :active, -> { where(accepted: true, locked: false) }
1801
+ end
1561
1802
 
1562
- * Add a warning for enum elements with 'not_' prefix.
1803
+ User.active
1804
+ # ... WHERE `accepted` = 1 AND `locked` = 0
1563
1805
 
1564
- class Foo
1565
- enum status: [:sent, :not_sent]
1566
- end
1806
+ User.active.invert_where
1807
+ # ... WHERE NOT (`accepted` = 1 AND `locked` = 0)
1808
+ ```
1567
1809
 
1568
- *Edu Depetris*
1810
+ *Kevin Deisz*
1569
1811
 
1570
- * Make currency symbols optional for money column type in PostgreSQL.
1812
+ * Restore possibility of passing `false` to :polymorphic option of `belongs_to`.
1571
1813
 
1572
- *Joel Schneider*
1814
+ Previously, passing `false` would trigger the option validation logic
1815
+ to throw an error saying :polymorphic would not be a valid option.
1573
1816
 
1574
- * Add support for beginless ranges, introduced in Ruby 2.7.
1817
+ *glaszig*
1575
1818
 
1576
- *Josh Goodall*
1819
+ * Remove deprecated `database` kwarg from `connected_to`.
1577
1820
 
1578
- * Add `database_exists?` method to connection adapters to check if a database exists.
1821
+ *Eileen M. Uchitelle*, *John Crepezzi*
1579
1822
 
1580
- *Guilherme Mansur*
1823
+ * Allow adding nonnamed expression indexes to be revertible.
1581
1824
 
1582
- * Loading the schema for a model that has no `table_name` raises a `TableNotSpecified` error.
1825
+ Previously, the following code would raise an error, when executed while rolling back,
1826
+ and the index name should be specified explicitly. Now, the index name is inferred
1827
+ automatically.
1583
1828
 
1584
- *Guilherme Mansur*, *Eugene Kenny*
1829
+ ```ruby
1830
+ add_index(:items, "to_tsvector('english', description)")
1831
+ ```
1585
1832
 
1586
- * PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
1833
+ Fixes #40732.
1587
1834
 
1588
- Fixes #36022.
1835
+ *fatkodima*
1589
1836
 
1590
- *Ryuta Kamizono*
1837
+ * Only warn about negative enums if a positive form that would cause conflicts exists.
1591
1838
 
1592
- * Make ActiveRecord `ConnectionPool.connections` method thread-safe.
1839
+ Fixes #39065.
1593
1840
 
1594
- Fixes #36465.
1841
+ *Alex Ghiculescu*
1595
1842
 
1596
- *Jeff Doering*
1843
+ * Add option to run `default_scope` on all queries.
1597
1844
 
1598
- * Add support for multiple databases to `rails db:abort_if_pending_migrations`.
1845
+ Previously, a `default_scope` would only run on select or insert queries. In some cases, like non-Rails tenant sharding solutions, it may be desirable to run `default_scope` on all queries in order to ensure queries are including a foreign key for the shard (i.e. `blog_id`).
1599
1846
 
1600
- *Mark Lee*
1847
+ Now applications can add an option to run on all queries including select, insert, delete, and update by adding an `all_queries` option to the default scope definition.
1601
1848
 
1602
- * Fix sqlite3 collation parsing when using decimal columns.
1849
+ ```ruby
1850
+ class Article < ApplicationRecord
1851
+ default_scope -> { where(blog_id: Current.blog.id) }, all_queries: true
1852
+ end
1853
+ ```
1603
1854
 
1604
- *Martin R. Schuster*
1855
+ *Eileen M. Uchitelle*
1605
1856
 
1606
- * Fix invalid schema when primary key column has a comment.
1857
+ * Add `where.associated` to check for the presence of an association.
1607
1858
 
1608
- Fixes #29966.
1859
+ ```ruby
1860
+ # Before:
1861
+ account.users.joins(:contact).where.not(contact_id: nil)
1609
1862
 
1610
- *Guilherme Goettems Schneider*
1863
+ # After:
1864
+ account.users.where.associated(:contact)
1865
+ ```
1611
1866
 
1612
- * Fix table comment also being applied to the primary key column.
1867
+ Also mirrors `where.missing`.
1613
1868
 
1614
- *Guilherme Goettems Schneider*
1869
+ *Kasper Timm Hansen*
1615
1870
 
1616
- * Allow generated `create_table` migrations to include or skip timestamps.
1871
+ * Allow constructors (`build_association` and `create_association`) on
1872
+ `has_one :through` associations.
1617
1873
 
1618
- *Michael Duchemin*
1874
+ *Santiago Perez Perret*
1619
1875
 
1620
1876
 
1621
- Please check [6-0-stable](https://github.com/rails/rails/blob/6-0-stable/activerecord/CHANGELOG.md) for previous changes.
1877
+ Please check [6-1-stable](https://github.com/rails/rails/blob/6-1-stable/activerecord/CHANGELOG.md) for previous changes.