activerecord 6.1.6 → 7.0.0.alpha1

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