activerecord 6.1.7.6 → 7.0.0

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