activerecord 7.0.0 → 7.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (249) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +1607 -1040
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +17 -18
  5. data/lib/active_record/aggregations.rb +16 -13
  6. data/lib/active_record/association_relation.rb +1 -1
  7. data/lib/active_record/associations/association.rb +18 -3
  8. data/lib/active_record/associations/association_scope.rb +16 -9
  9. data/lib/active_record/associations/belongs_to_association.rb +14 -6
  10. data/lib/active_record/associations/builder/association.rb +3 -3
  11. data/lib/active_record/associations/builder/belongs_to.rb +21 -8
  12. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +1 -5
  13. data/lib/active_record/associations/builder/singular_association.rb +4 -0
  14. data/lib/active_record/associations/collection_association.rb +17 -12
  15. data/lib/active_record/associations/collection_proxy.rb +22 -12
  16. data/lib/active_record/associations/foreign_association.rb +10 -3
  17. data/lib/active_record/associations/has_many_association.rb +27 -17
  18. data/lib/active_record/associations/has_many_through_association.rb +10 -6
  19. data/lib/active_record/associations/has_one_association.rb +10 -3
  20. data/lib/active_record/associations/join_dependency.rb +20 -14
  21. data/lib/active_record/associations/preloader/association.rb +27 -6
  22. data/lib/active_record/associations/preloader/through_association.rb +1 -1
  23. data/lib/active_record/associations/preloader.rb +13 -10
  24. data/lib/active_record/associations/singular_association.rb +1 -1
  25. data/lib/active_record/associations/through_association.rb +22 -11
  26. data/lib/active_record/associations.rb +345 -219
  27. data/lib/active_record/attribute_assignment.rb +0 -2
  28. data/lib/active_record/attribute_methods/before_type_cast.rb +17 -0
  29. data/lib/active_record/attribute_methods/dirty.rb +40 -26
  30. data/lib/active_record/attribute_methods/primary_key.rb +76 -24
  31. data/lib/active_record/attribute_methods/query.rb +28 -16
  32. data/lib/active_record/attribute_methods/read.rb +18 -5
  33. data/lib/active_record/attribute_methods/serialization.rb +172 -69
  34. data/lib/active_record/attribute_methods/write.rb +3 -3
  35. data/lib/active_record/attribute_methods.rb +110 -28
  36. data/lib/active_record/attributes.rb +3 -3
  37. data/lib/active_record/autosave_association.rb +56 -10
  38. data/lib/active_record/base.rb +10 -5
  39. data/lib/active_record/callbacks.rb +16 -32
  40. data/lib/active_record/coders/column_serializer.rb +61 -0
  41. data/lib/active_record/coders/json.rb +1 -1
  42. data/lib/active_record/coders/yaml_column.rb +70 -34
  43. data/lib/active_record/connection_adapters/abstract/connection_handler.rb +164 -89
  44. data/lib/active_record/connection_adapters/abstract/connection_pool/queue.rb +2 -0
  45. data/lib/active_record/connection_adapters/abstract/connection_pool/reaper.rb +3 -1
  46. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +63 -43
  47. data/lib/active_record/connection_adapters/abstract/database_limits.rb +5 -0
  48. data/lib/active_record/connection_adapters/abstract/database_statements.rb +128 -32
  49. data/lib/active_record/connection_adapters/abstract/query_cache.rb +60 -22
  50. data/lib/active_record/connection_adapters/abstract/quoting.rb +52 -8
  51. data/lib/active_record/connection_adapters/abstract/savepoints.rb +4 -3
  52. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +18 -4
  53. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +163 -29
  54. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +14 -1
  55. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +302 -129
  56. data/lib/active_record/connection_adapters/abstract/transaction.rb +287 -58
  57. data/lib/active_record/connection_adapters/abstract_adapter.rb +504 -106
  58. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +217 -104
  59. data/lib/active_record/connection_adapters/column.rb +9 -0
  60. data/lib/active_record/connection_adapters/mysql/column.rb +1 -0
  61. data/lib/active_record/connection_adapters/mysql/database_statements.rb +23 -144
  62. data/lib/active_record/connection_adapters/mysql/quoting.rb +29 -12
  63. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +9 -0
  64. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +10 -1
  65. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +8 -2
  66. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +38 -14
  67. data/lib/active_record/connection_adapters/mysql2/database_statements.rb +148 -0
  68. data/lib/active_record/connection_adapters/mysql2_adapter.rb +98 -53
  69. data/lib/active_record/connection_adapters/pool_config.rb +14 -5
  70. data/lib/active_record/connection_adapters/pool_manager.rb +19 -9
  71. data/lib/active_record/connection_adapters/postgresql/column.rb +3 -2
  72. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +72 -45
  73. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +1 -1
  74. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +2 -2
  75. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +11 -2
  76. data/lib/active_record/connection_adapters/postgresql/oid/timestamp_with_time_zone.rb +3 -1
  77. data/lib/active_record/connection_adapters/postgresql/quoting.rb +41 -8
  78. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +6 -10
  79. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +76 -6
  80. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +131 -2
  81. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +53 -0
  82. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +358 -57
  83. data/lib/active_record/connection_adapters/postgresql/utils.rb +9 -10
  84. data/lib/active_record/connection_adapters/postgresql_adapter.rb +343 -181
  85. data/lib/active_record/connection_adapters/schema_cache.rb +287 -59
  86. data/lib/active_record/connection_adapters/sqlite3/column.rb +49 -0
  87. data/lib/active_record/connection_adapters/sqlite3/database_statements.rb +45 -39
  88. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +22 -5
  89. data/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb +7 -0
  90. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +41 -22
  91. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +242 -81
  92. data/lib/active_record/connection_adapters/statement_pool.rb +7 -0
  93. data/lib/active_record/connection_adapters/trilogy/database_statements.rb +98 -0
  94. data/lib/active_record/connection_adapters/trilogy_adapter.rb +254 -0
  95. data/lib/active_record/connection_adapters.rb +3 -1
  96. data/lib/active_record/connection_handling.rb +73 -96
  97. data/lib/active_record/core.rb +136 -148
  98. data/lib/active_record/counter_cache.rb +46 -25
  99. data/lib/active_record/database_configurations/connection_url_resolver.rb +1 -0
  100. data/lib/active_record/database_configurations/database_config.rb +9 -3
  101. data/lib/active_record/database_configurations/hash_config.rb +22 -12
  102. data/lib/active_record/database_configurations/url_config.rb +17 -11
  103. data/lib/active_record/database_configurations.rb +87 -34
  104. data/lib/active_record/delegated_type.rb +9 -4
  105. data/lib/active_record/deprecator.rb +7 -0
  106. data/lib/active_record/destroy_association_async_job.rb +2 -0
  107. data/lib/active_record/disable_joins_association_relation.rb +1 -1
  108. data/lib/active_record/encryption/auto_filtered_parameters.rb +66 -0
  109. data/lib/active_record/encryption/cipher/aes256_gcm.rb +4 -1
  110. data/lib/active_record/encryption/config.rb +25 -1
  111. data/lib/active_record/encryption/configurable.rb +13 -14
  112. data/lib/active_record/encryption/context.rb +10 -3
  113. data/lib/active_record/encryption/contexts.rb +8 -4
  114. data/lib/active_record/encryption/derived_secret_key_provider.rb +9 -3
  115. data/lib/active_record/encryption/deterministic_key_provider.rb +1 -1
  116. data/lib/active_record/encryption/encryptable_record.rb +38 -22
  117. data/lib/active_record/encryption/encrypted_attribute_type.rb +19 -8
  118. data/lib/active_record/encryption/encryptor.rb +7 -7
  119. data/lib/active_record/encryption/envelope_encryption_key_provider.rb +3 -3
  120. data/lib/active_record/encryption/extended_deterministic_queries.rb +83 -71
  121. data/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb +3 -3
  122. data/lib/active_record/encryption/key_generator.rb +12 -1
  123. data/lib/active_record/encryption/message.rb +1 -1
  124. data/lib/active_record/encryption/message_serializer.rb +2 -0
  125. data/lib/active_record/encryption/properties.rb +4 -4
  126. data/lib/active_record/encryption/scheme.rb +20 -23
  127. data/lib/active_record/encryption.rb +1 -0
  128. data/lib/active_record/enum.rb +114 -27
  129. data/lib/active_record/errors.rb +108 -15
  130. data/lib/active_record/explain.rb +23 -3
  131. data/lib/active_record/explain_subscriber.rb +1 -1
  132. data/lib/active_record/fixture_set/model_metadata.rb +14 -4
  133. data/lib/active_record/fixture_set/render_context.rb +2 -0
  134. data/lib/active_record/fixture_set/table_row.rb +29 -8
  135. data/lib/active_record/fixtures.rb +121 -73
  136. data/lib/active_record/future_result.rb +30 -5
  137. data/lib/active_record/gem_version.rb +2 -2
  138. data/lib/active_record/inheritance.rb +30 -16
  139. data/lib/active_record/insert_all.rb +55 -8
  140. data/lib/active_record/integration.rb +10 -10
  141. data/lib/active_record/internal_metadata.rb +118 -30
  142. data/lib/active_record/locking/optimistic.rb +32 -18
  143. data/lib/active_record/locking/pessimistic.rb +8 -5
  144. data/lib/active_record/log_subscriber.rb +39 -17
  145. data/lib/active_record/marshalling.rb +56 -0
  146. data/lib/active_record/message_pack.rb +124 -0
  147. data/lib/active_record/middleware/database_selector/resolver.rb +4 -0
  148. data/lib/active_record/middleware/database_selector.rb +18 -13
  149. data/lib/active_record/middleware/shard_selector.rb +7 -5
  150. data/lib/active_record/migration/command_recorder.rb +104 -9
  151. data/lib/active_record/migration/compatibility.rb +158 -64
  152. data/lib/active_record/migration/default_strategy.rb +23 -0
  153. data/lib/active_record/migration/execution_strategy.rb +19 -0
  154. data/lib/active_record/migration.rb +271 -117
  155. data/lib/active_record/model_schema.rb +82 -50
  156. data/lib/active_record/nested_attributes.rb +23 -3
  157. data/lib/active_record/normalization.rb +159 -0
  158. data/lib/active_record/persistence.rb +200 -47
  159. data/lib/active_record/promise.rb +84 -0
  160. data/lib/active_record/query_cache.rb +3 -21
  161. data/lib/active_record/query_logs.rb +87 -51
  162. data/lib/active_record/query_logs_formatter.rb +41 -0
  163. data/lib/active_record/querying.rb +16 -3
  164. data/lib/active_record/railtie.rb +127 -61
  165. data/lib/active_record/railties/controller_runtime.rb +12 -8
  166. data/lib/active_record/railties/databases.rake +142 -143
  167. data/lib/active_record/railties/job_runtime.rb +23 -0
  168. data/lib/active_record/readonly_attributes.rb +32 -5
  169. data/lib/active_record/reflection.rb +177 -45
  170. data/lib/active_record/relation/batches/batch_enumerator.rb +5 -3
  171. data/lib/active_record/relation/batches.rb +190 -61
  172. data/lib/active_record/relation/calculations.rb +200 -83
  173. data/lib/active_record/relation/delegation.rb +23 -9
  174. data/lib/active_record/relation/finder_methods.rb +77 -16
  175. data/lib/active_record/relation/merger.rb +2 -0
  176. data/lib/active_record/relation/predicate_builder/association_query_value.rb +31 -3
  177. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +4 -6
  178. data/lib/active_record/relation/predicate_builder/relation_handler.rb +5 -1
  179. data/lib/active_record/relation/predicate_builder.rb +26 -14
  180. data/lib/active_record/relation/query_attribute.rb +25 -1
  181. data/lib/active_record/relation/query_methods.rb +429 -76
  182. data/lib/active_record/relation/spawn_methods.rb +18 -1
  183. data/lib/active_record/relation.rb +98 -41
  184. data/lib/active_record/result.rb +25 -9
  185. data/lib/active_record/runtime_registry.rb +10 -1
  186. data/lib/active_record/sanitization.rb +57 -16
  187. data/lib/active_record/schema.rb +36 -22
  188. data/lib/active_record/schema_dumper.rb +65 -23
  189. data/lib/active_record/schema_migration.rb +68 -33
  190. data/lib/active_record/scoping/default.rb +20 -12
  191. data/lib/active_record/scoping/named.rb +2 -2
  192. data/lib/active_record/scoping.rb +2 -1
  193. data/lib/active_record/secure_password.rb +60 -0
  194. data/lib/active_record/secure_token.rb +21 -3
  195. data/lib/active_record/serialization.rb +5 -0
  196. data/lib/active_record/signed_id.rb +9 -7
  197. data/lib/active_record/store.rb +16 -11
  198. data/lib/active_record/suppressor.rb +3 -1
  199. data/lib/active_record/table_metadata.rb +16 -3
  200. data/lib/active_record/tasks/database_tasks.rb +138 -107
  201. data/lib/active_record/tasks/mysql_database_tasks.rb +15 -6
  202. data/lib/active_record/tasks/postgresql_database_tasks.rb +17 -15
  203. data/lib/active_record/tasks/sqlite_database_tasks.rb +15 -7
  204. data/lib/active_record/test_fixtures.rb +123 -99
  205. data/lib/active_record/timestamp.rb +26 -14
  206. data/lib/active_record/token_for.rb +113 -0
  207. data/lib/active_record/touch_later.rb +11 -6
  208. data/lib/active_record/transactions.rb +39 -13
  209. data/lib/active_record/translation.rb +1 -1
  210. data/lib/active_record/type/adapter_specific_registry.rb +1 -8
  211. data/lib/active_record/type/internal/timezone.rb +7 -2
  212. data/lib/active_record/type/serialized.rb +8 -4
  213. data/lib/active_record/type/time.rb +4 -0
  214. data/lib/active_record/validations/absence.rb +1 -1
  215. data/lib/active_record/validations/associated.rb +3 -3
  216. data/lib/active_record/validations/numericality.rb +5 -4
  217. data/lib/active_record/validations/presence.rb +5 -28
  218. data/lib/active_record/validations/uniqueness.rb +50 -5
  219. data/lib/active_record/validations.rb +8 -4
  220. data/lib/active_record/version.rb +1 -1
  221. data/lib/active_record.rb +143 -16
  222. data/lib/arel/errors.rb +10 -0
  223. data/lib/arel/factory_methods.rb +4 -0
  224. data/lib/arel/filter_predications.rb +1 -1
  225. data/lib/arel/nodes/and.rb +4 -0
  226. data/lib/arel/nodes/binary.rb +6 -1
  227. data/lib/arel/nodes/bound_sql_literal.rb +61 -0
  228. data/lib/arel/nodes/cte.rb +36 -0
  229. data/lib/arel/nodes/filter.rb +1 -1
  230. data/lib/arel/nodes/fragments.rb +35 -0
  231. data/lib/arel/nodes/homogeneous_in.rb +0 -8
  232. data/lib/arel/nodes/leading_join.rb +8 -0
  233. data/lib/arel/nodes/node.rb +111 -2
  234. data/lib/arel/nodes/sql_literal.rb +6 -0
  235. data/lib/arel/nodes/table_alias.rb +4 -0
  236. data/lib/arel/nodes.rb +4 -0
  237. data/lib/arel/predications.rb +2 -0
  238. data/lib/arel/table.rb +9 -5
  239. data/lib/arel/visitors/mysql.rb +8 -1
  240. data/lib/arel/visitors/to_sql.rb +81 -17
  241. data/lib/arel/visitors/visitor.rb +2 -2
  242. data/lib/arel.rb +16 -2
  243. data/lib/rails/generators/active_record/application_record/USAGE +8 -0
  244. data/lib/rails/generators/active_record/migration.rb +3 -1
  245. data/lib/rails/generators/active_record/model/USAGE +113 -0
  246. data/lib/rails/generators/active_record/model/model_generator.rb +15 -6
  247. metadata +50 -15
  248. data/lib/active_record/connection_adapters/legacy_pool_manager.rb +0 -35
  249. data/lib/active_record/null_relation.rb +0 -63
data/CHANGELOG.md CHANGED
@@ -1,1697 +1,2264 @@
1
- ## Rails 7.0.0 (December 15, 2021) ##
1
+ ## Rails 7.1.0 (October 05, 2023) ##
2
2
 
3
- * Better handle SQL queries with invalid encoding.
3
+ * No changes.
4
+
5
+
6
+ ## Rails 7.1.0.rc2 (October 01, 2023) ##
7
+
8
+ * Remove -shm and -wal SQLite files when `rails db:drop` is run.
9
+
10
+ *Niklas Häusele*
11
+
12
+ * Revert the change to raise an `ArgumentError` when `#accepts_nested_attributes_for` is declared more than once for
13
+ an association in the same class.
14
+
15
+ The reverted behavior broke the case where the `#accepts_nested_attributes_for` was defined in a concern and
16
+ where overridden in the class that included the concern.
17
+
18
+ *Rafael Mendonça França*
19
+
20
+
21
+ ## Rails 7.1.0.rc1 (September 27, 2023) ##
22
+
23
+ * Better naming for unique constraints support.
24
+
25
+ Naming unique keys leads to misunderstanding it's a short-hand of unique indexes.
26
+ Just naming it unique constraints is not misleading.
27
+
28
+ In Rails 7.1.0.beta1 or before:
4
29
 
5
30
  ```ruby
6
- Post.create(name: "broken \xC8 UTF-8")
31
+ add_unique_key :sections, [:position], deferrable: :deferred, name: "unique_section_position"
32
+ remove_unique_key :sections, name: "unique_section_position"
7
33
  ```
8
34
 
9
- Would cause all adapters to fail in a non controlled way in the code
10
- responsible to detect write queries.
35
+ Now:
11
36
 
12
- The query is now properly passed to the database connection, which might or might
13
- not be able to handle it, but will either succeed or failed in a more correct way.
37
+ ```ruby
38
+ add_unique_constraint :sections, [:position], deferrable: :deferred, name: "unique_section_position"
39
+ remove_unique_constraint :sections, name: "unique_section_position"
40
+ ```
14
41
 
15
- *Jean Boussier*
42
+ *Ryuta Kamizono*
16
43
 
17
- * Move database and shard selection config options to a generator.
44
+ * Fix duplicate quoting for check constraint expressions in schema dump when using MySQL
18
45
 
19
- Rather than generating the config options in `production.rb` when applications are created, applications can now run a generator to create an initializer and uncomment / update options as needed. All multi-db configuration can be implemented in this initializer.
46
+ A check constraint with an expression, that already contains quotes, lead to an invalid schema
47
+ dump with the mysql2 adapter.
20
48
 
21
- *Eileen M. Uchitelle*
49
+ Fixes #42424.
22
50
 
23
- ## Rails 7.0.0.rc3 (December 14, 2021) ##
51
+ *Felix Tscheulin*
24
52
 
25
- * No changes.
53
+ * Performance tune the SQLite3 adapter connection configuration
26
54
 
55
+ For Rails applications, the Write-Ahead-Log in normal syncing mode with a capped journal size, a healthy shared memory buffer and a shared cache will perform, on average, 2× better.
27
56
 
28
- ## Rails 7.0.0.rc2 (December 14, 2021) ##
57
+ *Stephen Margheim*
29
58
 
30
- * No changes.
59
+ * Allow SQLite3 `busy_handler` to be configured with simple max number of `retries`
31
60
 
32
- ## Rails 7.0.0.rc1 (December 06, 2021) ##
61
+ Retrying busy connections without delay is a preferred practice for performance-sensitive applications. Add support for a `database.yml` `retries` integer, which is used in a simple `busy_handler` function to retry busy connections without exponential backoff up to the max number of `retries`.
33
62
 
34
- * Remove deprecated `ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name`.
63
+ *Stephen Margheim*
35
64
 
36
- *Rafael Mendonça França*
65
+ * The SQLite3 adapter now supports `supports_insert_returning?`
37
66
 
38
- * Remove deprecated `ActiveRecord::Connection#in_clause_length`.
67
+ Implementing the full `supports_insert_returning?` contract means the SQLite3 adapter supports auto-populated columns (#48241) as well as custom primary keys.
39
68
 
40
- *Rafael Mendonça França*
69
+ *Stephen Margheim*
41
70
 
42
- * Remove deprecated `ActiveRecord::Connection#allowed_index_name_length`.
71
+ * Ensure the SQLite3 adapter handles default functions with the `||` concatenation operator
43
72
 
44
- *Rafael Mendonça França*
73
+ Previously, this default function would produce the static string `"'Ruby ' || 'on ' || 'Rails'"`.
74
+ Now, the adapter will appropriately receive and use `"Ruby on Rails"`.
75
+
76
+ ```ruby
77
+ change_column_default "test_models", "ruby_on_rails", -> { "('Ruby ' || 'on ' || 'Rails')" }
78
+ ```
45
79
 
46
- * Remove deprecated `ActiveRecord::Base#remove_connection`.
80
+ *Stephen Margheim*
47
81
 
48
- *Rafael Mendonça França*
82
+ * Dump PostgreSQL schemas as part of the schema dump.
49
83
 
50
- * Load STI Models in fixtures
84
+ *Lachlan Sylvester*
51
85
 
52
- Data from Fixtures now loads based on the specific class for models with
53
- Single Table Inheritance. This affects enums defined in subclasses, previously
54
- the value of these fields was not parsed and remained `nil`
55
86
 
56
- *Andres Howard*
87
+ ## Rails 7.1.0.beta1 (September 13, 2023) ##
57
88
 
58
- * `#authenticate` returns false when the password is blank instead of raising an error.
89
+ * Encryption now supports `support_unencrypted_data` being set per-attribute.
59
90
 
60
- *Muhammad Muhammad Ibrahim*
91
+ You can now opt out of `support_unencrypted_data` on a specific encrypted attribute.
92
+ This only has an effect if `ActiveRecord::Encryption.config.support_unencrypted_data == true`.
61
93
 
62
- * Fix `ActiveRecord::QueryMethods#in_order_of` behavior for integer enums.
94
+ ```ruby
95
+ class User < ActiveRecord::Base
96
+ encrypts :name, deterministic: true, support_unencrypted_data: false
97
+ encrypts :email, deterministic: true
98
+ end
99
+ ```
63
100
 
64
- `ActiveRecord::QueryMethods#in_order_of` didn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.
101
+ *Alex Ghiculescu*
65
102
 
66
- The following example now works as expected:
103
+ * Add instrumentation for Active Record transactions
104
+
105
+ Allows subscribing to transaction events for tracking/instrumentation. The event payload contains the connection and the outcome (commit, rollback, restart, incomplete), as well as timing details.
67
106
 
68
107
  ```ruby
69
- class Book < ApplicationRecord
70
- enum status: [:proposed, :written, :published]
108
+ ActiveSupport::Notifications.subscribe("transaction.active_record") do |event|
109
+ puts "Transaction event occurred!"
110
+ connection = event.payload[:connection]
111
+ puts "Connection: #{connection.inspect}"
71
112
  end
72
-
73
- Book.in_order_of(:status, %w[written published proposed])
74
113
  ```
75
114
 
76
- *Alexandre Ruban*
115
+ *Daniel Colson*, *Ian Candy*
77
116
 
78
- * Ignore persisted in-memory records when merging target lists.
117
+ * Support composite foreign keys via migration helpers.
79
118
 
80
- *Kevin Sjöberg*
119
+ ```ruby
120
+ # Assuming "carts" table has "(shop_id, user_id)" as a primary key.
81
121
 
82
- * Add a new option `:update_only` to `upsert_all` to configure the list of columns to update in case of conflict.
122
+ add_foreign_key(:orders, :carts, primary_key: [:shop_id, :user_id])
83
123
 
84
- Before, you could only customize the update SQL sentence via `:on_duplicate`. There is now a new option `:update_only` that lets you provide a list of columns to update in case of conflict:
124
+ remove_foreign_key(:orders, :carts, primary_key: [:shop_id, :user_id])
125
+ foreign_key_exists?(:orders, :carts, primary_key: [:shop_id, :user_id])
126
+ ```
127
+
128
+ *fatkodima*
129
+
130
+ * Adds support for `if_not_exists` when adding a check constraint.
85
131
 
86
132
  ```ruby
87
- Commodity.upsert_all(
88
- [
89
- { id: 2, name: "Copper", price: 4.84 },
90
- { id: 4, name: "Gold", price: 1380.87 },
91
- { id: 6, name: "Aluminium", price: 0.35 }
92
- ],
93
- update_only: [:price] # Only prices will be updated
94
- )
133
+ add_check_constraint :posts, "post_type IN ('blog', 'comment', 'share')", if_not_exists: true
95
134
  ```
96
135
 
97
- *Jorge Manrubia*
136
+ *Cody Cutrer*
98
137
 
99
- * Remove deprecated `ActiveRecord::Result#map!` and `ActiveRecord::Result#collect!`.
138
+ * Raise an `ArgumentError` when `#accepts_nested_attributes_for` is declared more than once for an association in
139
+ the same class. Previously, the last declaration would silently override the previous one. Overriding in a subclass
140
+ is still allowed.
100
141
 
101
- *Rafael Mendonça França*
142
+ *Joshua Young*
102
143
 
103
- * Remove deprecated `ActiveRecord::Base.configurations.to_h`.
144
+ * Deprecate `rewhere` argument on `#merge`.
104
145
 
105
- *Rafael Mendonça França*
146
+ The `rewhere` argument on `#merge`is deprecated without replacement and
147
+ will be removed in Rails 7.2.
106
148
 
107
- * Remove deprecated `ActiveRecord::Base.configurations.default_hash`.
149
+ *Adam Hess*
108
150
 
109
- *Rafael Mendonça França*
151
+ * Fix unscope is not working in specific case
110
152
 
111
- * Remove deprecated `ActiveRecord::Base.arel_attribute`.
153
+ Before:
154
+ ```ruby
155
+ Post.where(id: 1...3).unscope(where: :id).to_sql # "SELECT `posts`.* FROM `posts` WHERE `posts`.`id` >= 1 AND `posts`.`id` < 3"
112
156
 
113
- *Rafael Mendonça França*
157
+ ```
114
158
 
115
- * Remove deprecated `ActiveRecord::Base.connection_config`.
159
+ After:
160
+ ```ruby
161
+ Post.where(id: 1...3).unscope(where: :id).to_sql # "SELECT `posts`.* FROM `posts`"
162
+ ```
116
163
 
117
- *Rafael Mendonça França*
164
+ Fixes #48094.
165
+
166
+ *Kazuya Hatanaka*
118
167
 
119
- * Filter attributes in SQL logs
168
+ * Change `has_secure_token` default to `on: :initialize`
120
169
 
121
- Previously, SQL queries in logs containing `ActiveRecord::Base.filter_attributes` were not filtered.
170
+ Change the new default value from `on: :create` to `on: :initialize`
122
171
 
123
- Now, the filter attributes will be masked `[FILTERED]` in the logs when `prepared_statement` is enabled.
172
+ Can be controlled by the `config.active_record.generate_secure_token_on`
173
+ configuration:
124
174
 
175
+ ```ruby
176
+ config.active_record.generate_secure_token_on = :create
125
177
  ```
126
- # Before:
127
- Foo Load (0.2ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "hello"], ["LIMIT", 1]]
128
178
 
129
- # After:
130
- Foo Load (0.5ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "[FILTERED]"], ["LIMIT", 1]]
179
+ *Sean Doyle*
180
+
181
+ * Fix `change_column` not setting `precision: 6` on `datetime` columns when
182
+ using 7.0+ Migrations and SQLite.
183
+
184
+ *Hartley McGuire*
185
+
186
+ * Support composite identifiers in `to_key`
187
+
188
+ `to_key` avoids wrapping `#id` value into an `Array` if `#id` already an array
189
+
190
+ *Nikita Vasilevsky*
191
+
192
+ * Add validation option for `enum`
193
+
194
+ ```ruby
195
+ class Contract < ApplicationRecord
196
+ enum :status, %w[in_progress completed], validate: true
197
+ end
198
+ Contract.new(status: "unknown").valid? # => false
199
+ Contract.new(status: nil).valid? # => false
200
+ Contract.new(status: "completed").valid? # => true
201
+
202
+ class Contract < ApplicationRecord
203
+ enum :status, %w[in_progress completed], validate: { allow_nil: true }
204
+ end
205
+ Contract.new(status: "unknown").valid? # => false
206
+ Contract.new(status: nil).valid? # => true
207
+ Contract.new(status: "completed").valid? # => true
131
208
  ```
132
209
 
133
- *Aishwarya Subramanian*
210
+ *Edem Topuzov*, *Ryuta Kamizono*
134
211
 
135
- * Remove deprecated `Tasks::DatabaseTasks.spec`.
212
+ * Allow batching methods to use already loaded relation if available
136
213
 
137
- *Rafael Mendonça França*
214
+ Calling batch methods on already loaded relations will use the records previously loaded instead of retrieving
215
+ them from the database again.
138
216
 
139
- * Remove deprecated `Tasks::DatabaseTasks.current_config`.
217
+ *Adam Hess*
140
218
 
141
- *Rafael Mendonça França*
219
+ * Deprecate `read_attribute(:id)` returning the primary key if the primary key is not `:id`.
142
220
 
143
- * Deprecate `Tasks::DatabaseTasks.schema_file_type`.
221
+ Starting in Rails 7.2, `read_attribute(:id)` will return the value of the id column, regardless of the model's
222
+ primary key. To retrieve the value of the primary key, use `#id` instead. `read_attribute(:id)` for composite
223
+ primary key models will now return the value of the id column.
144
224
 
145
- *Rafael Mendonça França*
225
+ *Adrianna Chang*
146
226
 
147
- * Remove deprecated `Tasks::DatabaseTasks.dump_filename`.
227
+ * Fix `change_table` setting datetime precision for 6.1 Migrations
148
228
 
149
- *Rafael Mendonça França*
229
+ *Hartley McGuire*
150
230
 
151
- * Remove deprecated `Tasks::DatabaseTasks.schema_file`.
231
+ * Fix change_column setting datetime precision for 6.1 Migrations
152
232
 
153
- *Rafael Mendonça França*
233
+ *Hartley McGuire*
154
234
 
155
- * Remove deprecated `environment` and `name` arguments from `Tasks::DatabaseTasks.schema_up_to_date?`.
235
+ * Add `ActiveRecord::Base#id_value` alias to access the raw value of a record's id column.
156
236
 
157
- *Rafael Mendonça França*
237
+ This alias is only provided for models that declare an `:id` column.
158
238
 
159
- * Merging conditions on the same column no longer maintain both conditions,
160
- and will be consistently replaced by the latter condition.
239
+ *Adrianna Chang*
161
240
 
162
- ```ruby
163
- # Rails 6.1 (IN clause is replaced by merger side equality condition)
164
- Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
165
- # Rails 6.1 (both conflict conditions exists, deprecated)
166
- Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
167
- # Rails 6.1 with rewhere to migrate to Rails 7.0's behavior
168
- Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
169
- # Rails 7.0 (same behavior with IN clause, mergee side condition is consistently replaced)
170
- Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
171
- Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
241
+ * Fix previous change tracking for `ActiveRecord::Store` when using a column with JSON structured database type
172
242
 
173
- *Rafael Mendonça França*
243
+ Before, the methods to access the changes made during the last save `#saved_change_to_key?`, `#saved_change_to_key`, and `#key_before_last_save` did not work if the store was defined as a `store_accessor` on a column with a JSON structured database type
174
244
 
175
- * Remove deprecated support to `Model.reorder(nil).first` to search using non-deterministic order.
245
+ *Robert DiMartino*
176
246
 
177
- *Rafael Mendonça França*
247
+ * Fully support `NULLS [NOT] DISTINCT` for PostgreSQL 15+ indexes.
178
248
 
179
- * Remove deprecated rake tasks:
249
+ Previous work was done to allow the index to be created in a migration, but it was not
250
+ supported in schema.rb. Additionally, the matching for `NULLS [NOT] DISTINCT` was not
251
+ in the correct order, which could have resulted in inconsistent schema detection.
180
252
 
181
- * `db:schema:load_if_ruby`
182
- * `db:structure:dump`
183
- * `db:structure:load`
184
- * `db:structure:load_if_sql`
185
- * `db:structure:dump:#{name}`
186
- * `db:structure:load:#{name}`
187
- * `db:test:load_structure`
188
- * `db:test:load_structure:#{name}`
253
+ *Gregory Jones*
189
254
 
190
- *Rafael Mendonça França*
255
+ * Allow escaping of literal colon characters in `sanitize_sql_*` methods when named bind variables are used
191
256
 
192
- * Remove deprecated `DatabaseConfig#config` method.
257
+ *Justin Bull*
193
258
 
194
- *Rafael Mendonça França*
259
+ * Fix `#previously_new_record?` to return true for destroyed records.
195
260
 
196
- * Rollback transactions when the block returns earlier than expected.
261
+ Before, if a record was created and then destroyed, `#previously_new_record?` would return true.
262
+ Now, any UPDATE or DELETE to a record is considered a change, and will result in `#previously_new_record?`
263
+ returning false.
197
264
 
198
- Before this change, when a transaction block returned early, the transaction would be committed.
265
+ *Adrianna Chang*
199
266
 
200
- The problem is that timeouts triggered inside the transaction block was also making the incomplete transaction
201
- to be committed, so in order to avoid this mistake, the transaction block is rolled back.
267
+ * Specify callback in `has_secure_token`
202
268
 
203
- *Rafael Mendonça França*
269
+ ```ruby
270
+ class User < ApplicationRecord
271
+ has_secure_token on: :initialize
272
+ end
273
+
274
+ User.new.token # => "abc123...."
275
+ ```
204
276
 
205
- * Add middleware for automatic shard swapping.
277
+ *Sean Doyle*
206
278
 
207
- Provides a basic middleware to perform automatic shard swapping. Applications will provide a resolver which will determine for an individual request which shard should be used. Example:
279
+ * Fix incrementation of in memory counter caches when associations overlap
280
+
281
+ When two associations had a similarly named counter cache column, Active Record
282
+ could sometime increment the wrong one.
283
+
284
+ *Jacopo Beschi*, *Jean Boussier*
285
+
286
+ * Don't show secrets for Active Record's `Cipher::Aes256Gcm#inspect`.
287
+
288
+ Before:
208
289
 
209
290
  ```ruby
210
- config.active_record.shard_resolver = ->(request) {
211
- subdomain = request.subdomain
212
- tenant = Tenant.find_by_subdomain!(subdomain)
213
- tenant.shard
214
- }
291
+ ActiveRecord::Encryption::Cipher::Aes256Gcm.new(secret).inspect
292
+ "#<ActiveRecord::Encryption::Cipher::Aes256Gcm:0x0000000104888038 ... @secret=\"\\xAF\\bFh]LV}q\\nl\\xB2U\\xB3 ... >"
215
293
  ```
216
294
 
217
- See guides for more details.
295
+ After:
296
+
297
+ ```ruby
298
+ ActiveRecord::Encryption::Cipher::Aes256Gcm(secret).inspect
299
+ "#<ActiveRecord::Encryption::Cipher::Aes256Gcm:0x0000000104888038>"
300
+ ```
218
301
 
219
- *Eileen M. Uchitelle*, *John Crepezzi*
302
+ *Petrik de Heus*
220
303
 
221
- * Remove deprecated support to pass a column to `type_cast`.
304
+ * Bring back the historical behavior of committing transaction on non-local return.
222
305
 
223
- *Rafael Mendonça França*
306
+ ```ruby
307
+ Model.transaction do
308
+ model.save
309
+ return
310
+ other_model.save # not executed
311
+ end
312
+ ```
224
313
 
225
- * Remove deprecated support to type cast to database values `ActiveRecord::Base` objects.
314
+ Historically only raised errors would trigger a rollback, but in Ruby `2.3`, the `timeout` library
315
+ started using `throw` to interrupt execution which had the adverse effect of committing open transactions.
226
316
 
227
- *Rafael Mendonça França*
317
+ To solve this, in Active Record 6.1 the behavior was changed to instead rollback the transaction as it was safer
318
+ than to potentially commit an incomplete transaction.
228
319
 
229
- * Remove deprecated support to quote `ActiveRecord::Base` objects.
320
+ Using `return`, `break` or `throw` inside a `transaction` block was essentially deprecated from Rails 6.1 onwards.
230
321
 
231
- *Rafael Mendonça França*
322
+ However with the release of `timeout 0.4.0`, `Timeout.timeout` now raises an error again, and Active Record is able
323
+ to return to its original, less surprising, behavior.
232
324
 
233
- * Remove deprecacated support to resolve connection using `"primary"` as connection specification name.
325
+ This historical behavior can now be opt-ed in via:
234
326
 
235
- *Rafael Mendonça França*
327
+ ```
328
+ Rails.application.config.active_record.commit_transaction_on_non_local_return = true
329
+ ```
330
+
331
+ And is the default for new applications created in Rails 7.1.
332
+
333
+ *Jean Boussier*
334
+
335
+ * Deprecate `name` argument on `#remove_connection`.
336
+
337
+ The `name` argument is deprecated on `#remove_connection` without replacement. `#remove_connection` should be called directly on the class that established the connection.
338
+
339
+ *Eileen M. Uchitelle*
340
+
341
+ * Fix has_one through singular building with inverse.
342
+
343
+ Allows building of records from an association with a has_one through a
344
+ singular association with inverse. For belongs_to through associations,
345
+ linking the foreign key to the primary key model isn't needed.
346
+ For has_one, we cannot build records due to the association not being mutable.
347
+
348
+ *Gannon McGibbon*
349
+
350
+ * Disable database prepared statements when query logs are enabled
236
351
 
237
- * Remove deprecation warning when using `:interval` column is used in PostgreSQL database.
352
+ Prepared Statements and Query Logs are incompatible features due to query logs making every query unique.
238
353
 
239
- Now, interval columns will return `ActiveSupport::Duration` objects instead of strings.
354
+ *zzak, Jean Boussier*
240
355
 
241
- To keep the old behavior, you can add this line to your model:
356
+ * Support decrypting data encrypted non-deterministically with a SHA1 hash digest.
357
+
358
+ This adds a new Active Record encryption option to support decrypting data encrypted
359
+ non-deterministically with a SHA1 hash digest:
360
+
361
+ ```
362
+ Rails.application.config.active_record.encryption.support_sha1_for_non_deterministic_encryption = true
363
+ ```
364
+
365
+ The new option addresses a problem when upgrading from 7.0 to 7.1. Due to a bug in how Active Record
366
+ Encryption was getting initialized, the key provider used for non-deterministic encryption were using
367
+ SHA-1 as its digest class, instead of the one configured globally by Rails via
368
+ `Rails.application.config.active_support.key_generator_hash_digest_class`.
369
+
370
+ *Cadu Ribeiro and Jorge Manrubia*
371
+
372
+ * Added PostgreSQL migration commands for enum rename, add value, and rename value.
373
+
374
+ `rename_enum` and `rename_enum_value` are reversible. Due to Postgres
375
+ limitation, `add_enum_value` is not reversible since you cannot delete enum
376
+ values. As an alternative you should drop and recreate the enum entirely.
242
377
 
243
378
  ```ruby
244
- attribute :column, :string
379
+ rename_enum :article_status, to: :article_state
245
380
  ```
246
381
 
247
- *Rafael Mendonça França*
382
+ ```ruby
383
+ add_enum_value :article_state, "archived" # will be at the end of existing values
384
+ add_enum_value :article_state, "in review", before: "published"
385
+ add_enum_value :article_state, "approved", after: "in review"
386
+ ```
248
387
 
249
- * Remove deprecated support to YAML load `ActiveRecord::Base` instance in the Rails 4.2 and 4.1 formats.
388
+ ```ruby
389
+ rename_enum_value :article_state, from: "archived", to: "deleted"
390
+ ```
250
391
 
251
- *Rafael Mendonça França*
392
+ *Ray Faddis*
252
393
 
253
- * Remove deprecated option `:spec_name` in the `configs_for` method.
394
+ * Allow composite primary key to be derived from schema
254
395
 
255
- *Rafael Mendonça França*
396
+ Booting an application with a schema that contains composite primary keys
397
+ will not issue warning and won't `nil`ify the `ActiveRecord::Base#primary_key` value anymore.
256
398
 
257
- * Remove deprecated `ActiveRecord::Base.allow_unsafe_raw_sql`.
399
+ Given a `travel_routes` table definition and a `TravelRoute` model like:
400
+ ```ruby
401
+ create_table :travel_routes, primary_key: [:origin, :destination], force: true do |t|
402
+ t.string :origin
403
+ t.string :destination
404
+ end
258
405
 
259
- *Rafael Mendonça França*
406
+ class TravelRoute < ActiveRecord::Base; end
407
+ ```
408
+ The `TravelRoute.primary_key` value will be automatically derived to `["origin", "destination"]`
260
409
 
261
- * Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations.
410
+ *Nikita Vasilevsky*
262
411
 
263
- Fixes #43132
412
+ * Include the `connection_pool` with exceptions raised from an adapter.
264
413
 
265
- *Alexander Pauly*
414
+ The `connection_pool` provides added context such as the connection used
415
+ that led to the exception as well as which role and shard.
266
416
 
267
- * Fix `has_many` inversing recursion on models with recursive associations.
417
+ *Luan Vieira*
268
418
 
269
- *Gannon McGibbon*
419
+ * Support multiple column ordering for `find_each`, `find_in_batches` and `in_batches`.
270
420
 
271
- * Add `accepts_nested_attributes_for` support for `delegated_type`
421
+ When find_each/find_in_batches/in_batches are performed on a table with composite primary keys, ascending or descending order can be selected for each key.
272
422
 
273
423
  ```ruby
274
- class Entry < ApplicationRecord
275
- delegated_type :entryable, types: %w[ Message Comment ]
276
- accepts_nested_attributes_for :entryable
424
+ Person.find_each(order: [:desc, :asc]) do |person|
425
+ person.party_all_night!
277
426
  end
427
+ ```
428
+
429
+ *Takuya Kurimoto*
278
430
 
279
- entry = Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
280
- # => #<Entry:0x00>
281
- # id: 1
282
- # entryable_id: 1,
283
- # entryable_type: 'Message'
284
- # ...>
431
+ * Fix where on association with has_one/has_many polymorphic relations.
285
432
 
286
- entry.entryable
287
- # => #<Message:0x01>
288
- # id: 1
289
- # content: 'Hello world'
290
- # ...>
433
+ Before:
434
+ ```ruby
435
+ Treasure.where(price_estimates: PriceEstimate.all)
436
+ #=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates")
291
437
  ```
292
438
 
293
- Previously it would raise an error:
439
+ Later:
440
+ ```ruby
441
+ Treasure.where(price_estimates: PriceEstimate.all)
442
+ #=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates" WHERE "price_estimates"."estimate_of_type" = 'Treasure')
443
+ ```
444
+
445
+ *Lázaro Nixon*
446
+
447
+ * Assign auto populated columns on Active Record record creation.
448
+
449
+ Changes record creation logic to allow for the `auto_increment` column to be assigned
450
+ immediately after creation regardless of it's relation to the model's primary key.
451
+
452
+ The PostgreSQL adapter benefits the most from the change allowing for any number of auto-populated
453
+ columns to be assigned on the object immediately after row insertion utilizing the `RETURNING` statement.
454
+
455
+ *Nikita Vasilevsky*
456
+
457
+ * Use the first key in the `shards` hash from `connected_to` for the `default_shard`.
458
+
459
+ Some applications may not want to use `:default` as a shard name in their connection model. Unfortunately Active Record expects there to be a `:default` shard because it must assume a shard to get the right connection from the pool manager. Rather than force applications to manually set this, `connects_to` can infer the default shard name from the hash of shards and will now assume that the first shard is your default.
460
+
461
+ For example if your model looked like this:
294
462
 
295
463
  ```ruby
296
- Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
297
- # ArgumentError: Cannot build association `entryable'. Are you trying to build a polymorphic one-to-one association?
464
+ class ShardRecord < ApplicationRecord
465
+ self.abstract_class = true
466
+
467
+ connects_to shards: {
468
+ shard_one: { writing: :shard_one },
469
+ shard_two: { writing: :shard_two }
470
+ }
298
471
  ```
299
472
 
300
- *Sjors Baltus*
473
+ Then the `default_shard` for this class would be set to `shard_one`.
301
474
 
302
- * Use subquery for DELETE with GROUP_BY and HAVING clauses.
475
+ Fixes: #45390
303
476
 
304
- Prior to this change, deletes with GROUP_BY and HAVING were returning an error.
477
+ *Eileen M. Uchitelle*
305
478
 
306
- After this change, GROUP_BY and HAVING are valid clauses in DELETE queries, generating the following query:
479
+ * Fix mutation detection for serialized attributes backed by binary columns.
307
480
 
308
- ```sql
309
- DELETE FROM "posts" WHERE "posts"."id" IN (
310
- SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" GROUP BY "posts"."id" HAVING (count(comments.id) >= 2))
311
- ) [["flagged", "t"]]
481
+ *Jean Boussier*
482
+
483
+ * Add `ActiveRecord.disconnect_all!` method to immediately close all connections from all pools.
484
+
485
+ *Jean Boussier*
486
+
487
+ * Discard connections which may have been left in a transaction.
488
+
489
+ There are cases where, due to an error, `within_new_transaction` may unexpectedly leave a connection in an open transaction. In these cases the connection may be reused, and the following may occur:
490
+ - Writes appear to fail when they actually succeed.
491
+ - Writes appear to succeed when they actually fail.
492
+ - Reads return stale or uncommitted data.
493
+
494
+ Previously, the following case was detected:
495
+ - An error is encountered during the transaction, then another error is encountered while attempting to roll it back.
496
+
497
+ Now, the following additional cases are detected:
498
+ - An error is encountered just after successfully beginning a transaction.
499
+ - An error is encountered while committing a transaction, then another error is encountered while attempting to roll it back.
500
+ - An error is encountered while rolling back a transaction.
501
+
502
+ *Nick Dower*
503
+
504
+ * Active Record query cache now evicts least recently used entries
505
+
506
+ By default it only keeps the `100` most recently used queries.
507
+
508
+ The cache size can be configured via `database.yml`
509
+
510
+ ```yaml
511
+ development:
512
+ adapter: mysql2
513
+ query_cache: 200
312
514
  ```
313
515
 
314
- *Ignacio Chiazzo Cardarello*
516
+ It can also be entirely disabled:
315
517
 
316
- * Use subquery for UPDATE with GROUP_BY and HAVING clauses.
518
+ ```yaml
519
+ development:
520
+ adapter: mysql2
521
+ query_cache: false
522
+ ```
317
523
 
318
- Prior to this change, updates with GROUP_BY and HAVING were being ignored, generating a SQL like this:
524
+ *Jean Boussier*
319
525
 
320
- ```sql
321
- UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
322
- SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
323
- ) [["flagged", "t"]]
526
+ * Deprecate `check_pending!` in favor of `check_all_pending!`.
527
+
528
+ `check_pending!` will only check for pending migrations on the current database connection or the one passed in. This has been deprecated in favor of `check_all_pending!` which will find all pending migrations for the database configurations in a given environment.
529
+
530
+ *Eileen M. Uchitelle*
531
+
532
+ * Make `increment_counter`/`decrement_counter` accept an amount argument
533
+
534
+ ```ruby
535
+ Post.increment_counter(:comments_count, 5, by: 3)
324
536
  ```
325
537
 
326
- After this change, GROUP_BY and HAVING clauses are used as a subquery in updates, like this:
538
+ *fatkodima*
327
539
 
328
- ```sql
329
- UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
330
- SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
331
- GROUP BY posts.id HAVING (count(comments.id) >= 2)
332
- ) [["flagged", "t"]]
540
+ * Add support for `Array#intersect?` to `ActiveRecord::Relation`.
541
+
542
+ `Array#intersect?` is only available on Ruby 3.1 or later.
543
+
544
+ This allows the Rubocop `Style/ArrayIntersect` cop to work with `ActiveRecord::Relation` objects.
545
+
546
+ *John Harry Kelly*
547
+
548
+ * The deferrable foreign key can be passed to `t.references`.
549
+
550
+ *Hiroyuki Ishii*
551
+
552
+ * Deprecate `deferrable: true` option of `add_foreign_key`.
553
+
554
+ `deferrable: true` is deprecated in favor of `deferrable: :immediate`, and
555
+ will be removed in Rails 7.2.
556
+
557
+ Because `deferrable: true` and `deferrable: :deferred` are hard to understand.
558
+ Both true and :deferred are truthy values.
559
+ This behavior is the same as the deferrable option of the add_unique_key method, added in #46192.
560
+
561
+ *Hiroyuki Ishii*
562
+
563
+ * `AbstractAdapter#execute` and `#exec_query` now clear the query cache
564
+
565
+ If you need to perform a read only SQL query without clearing the query
566
+ cache, use `AbstractAdapter#select_all`.
567
+
568
+ *Jean Boussier*
569
+
570
+ * Make `.joins` / `.left_outer_joins` work with CTEs.
571
+
572
+ For example:
573
+
574
+ ```ruby
575
+ Post
576
+ .with(commented_posts: Comment.select(:post_id).distinct)
577
+ .joins(:commented_posts)
578
+ #=> WITH (...) SELECT ... INNER JOIN commented_posts on posts.id = commented_posts.post_id
333
579
  ```
334
580
 
335
- *Ignacio Chiazzo Cardarello*
581
+ *Vladimir Dementyev*
582
+
583
+ * Add a load hook for `ActiveRecord::ConnectionAdapters::Mysql2Adapter`
584
+ (named `active_record_mysql2adapter`) to allow for overriding aspects of the
585
+ `ActiveRecord::ConnectionAdapters::Mysql2Adapter` class. This makes `Mysql2Adapter`
586
+ consistent with `PostgreSQLAdapter` and `SQLite3Adapter` that already have load hooks.
587
+
588
+ *fatkodima*
336
589
 
337
- * Add support for setting the filename of the schema or structure dump in the database config.
590
+ * Introduce adapter for Trilogy database client
338
591
 
339
- Applications may now set their the filename or path of the schema / structure dump file in their database configuration.
592
+ Trilogy is a MySQL-compatible database client. Rails applications can use Trilogy
593
+ by configuring their `config/database.yml`:
340
594
 
341
595
  ```yaml
342
- production:
343
- primary:
344
- database: my_db
345
- schema_dump: my_schema_dump_filename.rb
346
- animals:
347
- database: animals_db
348
- schema_dump: false
596
+ development:
597
+ adapter: trilogy
598
+ database: blog_development
599
+ pool: 5
349
600
  ```
350
601
 
351
- The filename set in `schema_dump` will be used by the application. If set to `false` the schema will not be dumped. The database tasks are responsible for adding the database directory to the filename. If a full path is provided, the Rails tasks will use that instead of `ActiveRecord::DatabaseTasks.db_dir`.
602
+ Or by using the `DATABASE_URL` environment variable:
352
603
 
353
- *Eileen M. Uchitelle*, *Ryan Kerr*
604
+ ```ruby
605
+ ENV['DATABASE_URL'] # => "trilogy://localhost/blog_development?pool=5"
606
+ ```
354
607
 
355
- * Add `ActiveRecord::Base.prohibit_shard_swapping` to prevent attempts to change the shard within a block.
608
+ *Adrianna Chang*
356
609
 
357
- *John Crepezzi*, *Eileen M. Uchitelle*
610
+ * `after_commit` callbacks defined on models now execute in the correct order.
358
611
 
359
- * Filter unchanged attributes with default function from insert query when `partial_inserts` is disabled.
612
+ ```ruby
613
+ class User < ActiveRecord::Base
614
+ after_commit { puts("this gets called first") }
615
+ after_commit { puts("this gets called second") }
616
+ end
617
+ ```
360
618
 
361
- *Akshay Birajdar*, *Jacopo Beschi*
619
+ Previously, the callbacks executed in the reverse order. To opt in to the new behaviour:
362
620
 
363
- * Add support for FILTER clause (SQL:2003) to Arel.
621
+ ```ruby
622
+ config.active_record.run_after_transaction_callbacks_in_order_defined = true
623
+ ```
364
624
 
365
- Currently supported by PostgreSQL 9.4+ and SQLite 3.30+.
625
+ This is the default for new apps.
366
626
 
367
- *Andrey Novikov*
627
+ *Alex Ghiculescu*
368
628
 
369
- * Automatically set timestamps on record creation during bulk insert/upsert
629
+ * Infer `foreign_key` when `inverse_of` is present on `has_one` and `has_many` associations.
370
630
 
371
- Prior to this change, only updates during an upsert operation (e.g. `upsert_all`) would touch timestamps (`updated_{at,on}`). Now, record creations also touch timestamp columns (`{created,updated}_{at,on}`).
631
+ ```ruby
632
+ has_many :citations, foreign_key: "book1_id", inverse_of: :book
633
+ ```
372
634
 
373
- This behaviour is controlled by the `<model>.record_timestamps` config, matching the behaviour of `create`, `update`, etc. It can also be overridden by using the `record_timestamps:` keyword argument.
635
+ can be simplified to
374
636
 
375
- Note that this means `upsert_all` on models with `record_timestamps = false` will no longer touch `updated_{at,on}` automatically.
637
+ ```ruby
638
+ has_many :citations, inverse_of: :book
639
+ ```
376
640
 
377
- *Sam Bostock*
641
+ and the foreign_key will be read from the corresponding `belongs_to` association.
378
642
 
379
- * Don't require `role` when passing `shard` to `connected_to`.
643
+ *Daniel Whitney*
380
644
 
381
- `connected_to` can now be called with a `shard` only. Note that `role` is still inherited if `connected_to` calls are nested.
645
+ * Limit max length of auto generated index names
382
646
 
383
- *Eileen M. Uchitelle*
647
+ Auto generated index names are now limited to 62 bytes, which fits within
648
+ the default index name length limits for MySQL, Postgres and SQLite.
649
+
650
+ Any index name over the limit will fallback to the new short format.
651
+
652
+ Before (too long):
653
+ ```
654
+ index_testings_on_foo_and_bar_and_first_name_and_last_name_and_administrator
655
+ ```
656
+
657
+ After (short format):
658
+ ```
659
+ idx_on_foo_bar_first_name_last_name_administrator_5939248142
660
+ ```
384
661
 
385
- * Add option to lazily load the schema cache on the connection.
662
+ The short format includes a hash to ensure the name is unique database-wide.
386
663
 
387
- Previously, the only way to load the schema cache in Active Record was through the Railtie on boot. This option provides the ability to load the schema cache on the connection after it's been established. Loading the cache lazily on the connection can be beneficial for Rails applications that use multiple databases because it will load the cache at the time the connection is established. Currently Railties doesn't have access to the connections before boot.
664
+ *Mike Coutermarsh*
388
665
 
389
- To use the cache, set `config.active_record.lazily_load_schema_cache = true` in your application configuration. In addition a `schema_cache_path` should be set in your database configuration if you don't want to use the default "db/schema_cache.yml" path.
666
+ * Introduce a more stable and optimized Marshal serializer for Active Record models.
390
667
 
391
- *Eileen M. Uchitelle*
668
+ Can be enabled with `config.active_record.marshalling_format_version = 7.1`.
669
+
670
+ *Jean Boussier*
671
+
672
+ * Allow specifying where clauses with column-tuple syntax.
392
673
 
393
- * Allow automatic `inverse_of` detection for associations with scopes.
674
+ Querying through `#where` now accepts a new tuple-syntax which accepts, as
675
+ a key, an array of columns and, as a value, an array of corresponding tuples.
676
+ The key specifies a list of columns, while the value is an array of
677
+ ordered-tuples that conform to the column list.
394
678
 
395
- Automatic `inverse_of` detection now works for associations with scopes. For
396
- example, the `comments` association here now automatically detects
397
- `inverse_of: :post`, so we don't need to pass that option:
679
+ For instance:
398
680
 
399
681
  ```ruby
400
- class Post < ActiveRecord::Base
401
- has_many :comments, -> { visible }
402
- end
682
+ # Cpk::Book => Cpk::Book(author_id: integer, number: integer, title: string, revision: integer)
683
+ # Cpk::Book.primary_key => ["author_id", "number"]
403
684
 
404
- class Comment < ActiveRecord::Base
405
- belongs_to :post
685
+ book = Cpk::Book.create!(author_id: 1, number: 1)
686
+ Cpk::Book.where(Cpk::Book.primary_key => [[1, 2]]) # => [book]
687
+
688
+ # Topic => Topic(id: integer, title: string, author_name: string...)
689
+
690
+ Topic.where([:title, :author_name] => [["The Alchemist", "Paulo Coelho"], ["Harry Potter", "J.K Rowling"]])
691
+ ```
692
+
693
+ *Paarth Madan*
694
+
695
+ * Allow warning codes to be ignore when reporting SQL warnings.
696
+
697
+ Active Record config that can ignore warning codes
698
+
699
+ ```ruby
700
+ # Configure allowlist of warnings that should always be ignored
701
+ config.active_record.db_warnings_ignore = [
702
+ "1062", # MySQL Error 1062: Duplicate entry
703
+ ]
704
+ ```
705
+
706
+ This is supported for the MySQL and PostgreSQL adapters.
707
+
708
+ *Nick Borromeo*
709
+
710
+ * Introduce `:active_record_fixtures` lazy load hook.
711
+
712
+ Hooks defined with this name will be run whenever `TestFixtures` is included
713
+ in a class.
714
+
715
+ ```ruby
716
+ ActiveSupport.on_load(:active_record_fixtures) do
717
+ self.fixture_paths << "test/fixtures"
406
718
  end
719
+
720
+ klass = Class.new
721
+ klass.include(ActiveRecord::TestFixtures)
722
+
723
+ klass.fixture_paths # => ["test/fixtures"]
407
724
  ```
408
725
 
409
- Note that the automatic detection still won't work if the inverse
410
- association has a scope. In this example a scope on the `post` association
411
- would still prevent Rails from finding the inverse for the `comments`
412
- association.
726
+ *Andrew Novoselac*
413
727
 
414
- This will be the default for new apps in Rails 7. To opt in:
728
+ * Introduce `TestFixtures#fixture_paths`.
729
+
730
+ Multiple fixture paths can now be specified using the `#fixture_paths` accessor.
731
+ Apps will continue to have `test/fixtures` as their one fixture path by default,
732
+ but additional fixture paths can be specified.
415
733
 
416
734
  ```ruby
417
- config.active_record.automatic_scope_inversing = true
735
+ ActiveSupport::TestCase.fixture_paths << "component1/test/fixtures"
736
+ ActiveSupport::TestCase.fixture_paths << "component2/test/fixtures"
418
737
  ```
419
738
 
420
- *Daniel Colson*, *Chris Bloom*
739
+ `TestFixtures#fixture_path` is now deprecated.
421
740
 
422
- * Accept optional transaction args to `ActiveRecord::Locking::Pessimistic#with_lock`
741
+ *Andrew Novoselac*
423
742
 
424
- `#with_lock` now accepts transaction options like `requires_new:`,
425
- `isolation:`, and `joinable:`
743
+ * Adds support for deferrable exclude constraints in PostgreSQL.
426
744
 
427
- *John Mileham*
745
+ By default, exclude constraints in PostgreSQL are checked after each statement.
746
+ This works for most use cases, but becomes a major limitation when replacing
747
+ records with overlapping ranges by using multiple statements.
428
748
 
429
- * Adds support for deferrable foreign key constraints in PostgreSQL.
749
+ ```ruby
750
+ exclusion_constraint :users, "daterange(valid_from, valid_to) WITH &&", deferrable: :immediate
751
+ ```
430
752
 
431
- By default, foreign key constraints in PostgreSQL are checked after each statement. This works for most use cases,
432
- but becomes a major limitation when creating related records before the parent record is inserted into the database.
433
- One example of this is looking up / creating a person via one or more unique alias.
753
+ Passing `deferrable: :immediate` checks constraint after each statement,
754
+ but allows manually deferring the check using `SET CONSTRAINTS ALL DEFERRED`
755
+ within a transaction. This will cause the excludes to be checked after the transaction.
756
+
757
+ It's also possible to change the default behavior from an immediate check
758
+ (after the statement), to a deferred check (after the transaction):
434
759
 
435
760
  ```ruby
436
- Person.transaction do
437
- alias = Alias
438
- .create_with(user_id: SecureRandom.uuid)
439
- .create_or_find_by(name: "DHH")
761
+ exclusion_constraint :users, "daterange(valid_from, valid_to) WITH &&", deferrable: :deferred
762
+ ```
440
763
 
441
- person = Person
442
- .create_with(name: "David Heinemeier Hansson")
443
- .create_or_find_by(id: alias.user_id)
444
- end
764
+ *Hiroyuki Ishii*
765
+
766
+ * Respect `foreign_type` option to `delegated_type` for `{role}_class` method.
767
+
768
+ Usage of `delegated_type` with non-conventional `{role}_type` column names can now be specified with `foreign_type` option.
769
+ This option is the same as `foreign_type` as forwarded to the underlying `belongs_to` association that `delegated_type` wraps.
770
+
771
+ *Jason Karns*
772
+
773
+ * Add support for unique constraints (PostgreSQL-only).
774
+
775
+ ```ruby
776
+ add_unique_key :sections, [:position], deferrable: :deferred, name: "unique_section_position"
777
+ remove_unique_key :sections, name: "unique_section_position"
445
778
  ```
446
779
 
447
- Using the default behavior, the transaction would fail when executing the first `INSERT` statement.
780
+ See PostgreSQL's [Unique Constraints](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS) documentation for more on unique constraints.
781
+
782
+ By default, unique constraints in PostgreSQL are checked after each statement.
783
+ This works for most use cases, but becomes a major limitation when replacing
784
+ records with unique column by using multiple statements.
448
785
 
449
- By passing the `:deferrable` option to the `add_foreign_key` statement in migrations, it's possible to defer this
450
- check.
786
+ An example of swapping unique columns between records.
451
787
 
452
788
  ```ruby
453
- add_foreign_key :aliases, :person, deferrable: true
789
+ # position is unique column
790
+ old_item = Item.create!(position: 1)
791
+ new_item = Item.create!(position: 2)
792
+
793
+ Item.transaction do
794
+ old_item.update!(position: 2)
795
+ new_item.update!(position: 1)
796
+ end
454
797
  ```
455
798
 
456
- Passing `deferrable: true` doesn't change the default behavior, but allows manually deferring the check using
457
- `SET CONSTRAINTS ALL DEFERRED` within a transaction. This will cause the foreign keys to be checked after the
458
- transaction.
799
+ Using the default behavior, the transaction would fail when executing the
800
+ first `UPDATE` statement.
459
801
 
460
- It's also possible to adjust the default behavior from an immediate check (after the statement), to a deferred check
461
- (after the transaction):
802
+ By passing the `:deferrable` option to the `add_unique_key` statement in
803
+ migrations, it's possible to defer this check.
462
804
 
463
805
  ```ruby
464
- add_foreign_key :aliases, :person, deferrable: :deferred
806
+ add_unique_key :items, [:position], deferrable: :immediate
465
807
  ```
466
808
 
467
- *Benedikt Deicke*
809
+ Passing `deferrable: :immediate` does not change the behaviour of the previous example,
810
+ but allows manually deferring the check using `SET CONSTRAINTS ALL DEFERRED` within a transaction.
811
+ This will cause the unique constraints to be checked after the transaction.
468
812
 
469
- * Allow configuring Postgres password through the socket URL.
813
+ It's also possible to adjust the default behavior from an immediate
814
+ check (after the statement), to a deferred check (after the transaction):
470
815
 
471
- For example:
472
816
  ```ruby
473
- ActiveRecord::DatabaseConfigurations::UrlConfig.new(
474
- :production, :production, 'postgres:///?user=user&password=secret&dbname=app', {}
475
- ).configuration_hash
817
+ add_unique_key :items, [:position], deferrable: :deferred
476
818
  ```
477
819
 
478
- will now return,
820
+ If you want to change an existing unique index to deferrable, you can use :using_index
821
+ to create deferrable unique constraints.
479
822
 
480
823
  ```ruby
481
- { :user=>"user", :password=>"secret", :dbname=>"app", :adapter=>"postgresql" }
824
+ add_unique_key :items, deferrable: :deferred, using_index: "index_items_on_position"
482
825
  ```
483
826
 
484
- *Abeid Ahmed*
827
+ *Hiroyuki Ishii*
828
+
829
+ * Remove deprecated `Tasks::DatabaseTasks.schema_file_type`.
830
+
831
+ *Rafael Mendonça França*
832
+
833
+ * Remove deprecated `config.active_record.partial_writes`.
834
+
835
+ *Rafael Mendonça França*
836
+
837
+ * Remove deprecated `ActiveRecord::Base` config accessors.
838
+
839
+ *Rafael Mendonça França*
840
+
841
+ * Remove the `:include_replicas` argument from `configs_for`. Use `:include_hidden` argument instead.
842
+
843
+ *Eileen M. Uchitelle*
485
844
 
486
- * PostgreSQL: support custom enum types
845
+ * Allow applications to lookup a config via a custom hash key.
487
846
 
488
- In migrations, use `create_enum` to add a new enum type, and `t.enum` to add a column.
847
+ If you have registered a custom config or want to find configs where the hash matches a specific key, now you can pass `config_key` to `configs_for`. For example if you have a `db_config` with the key `vitess` you can look up a database configuration hash by matching that key.
489
848
 
490
849
  ```ruby
491
- def up
492
- create_enum :mood, ["happy", "sad"]
850
+ ActiveRecord::Base.configurations.configs_for(env_name: "development", name: "primary", config_key: :vitess)
851
+ ActiveRecord::Base.configurations.configs_for(env_name: "development", config_key: :vitess)
852
+ ```
853
+
854
+ *Eileen M. Uchitelle*
855
+
856
+ * Allow applications to register a custom database configuration handler.
857
+
858
+ Adds a mechanism for registering a custom handler for cases where you want database configurations to respond to custom methods. This is useful for non-Rails database adapters or tools like Vitess that you may want to configure differently from a standard `HashConfig` or `UrlConfig`.
859
+
860
+ Given the following database YAML we want the `animals` db to create a `CustomConfig` object instead while the `primary` database will be a `UrlConfig`:
861
+
862
+ ```yaml
863
+ development:
864
+ primary:
865
+ url: postgres://localhost/primary
866
+ animals:
867
+ url: postgres://localhost/animals
868
+ custom_config:
869
+ sharded: 1
870
+ ```
871
+
872
+ To register a custom handler first make a class that has your custom methods:
493
873
 
494
- change_table :cats do |t|
495
- t.enum :current_mood, enum_type: "mood", default: "happy", null: false
874
+ ```ruby
875
+ class CustomConfig < ActiveRecord::DatabaseConfigurations::UrlConfig
876
+ def sharded?
877
+ custom_config.fetch("sharded", false)
496
878
  end
879
+
880
+ private
881
+ def custom_config
882
+ configuration_hash.fetch(:custom_config)
883
+ end
884
+ end
885
+ ```
886
+
887
+ Then register the config in an initializer:
888
+
889
+ ```ruby
890
+ ActiveRecord::DatabaseConfigurations.register_db_config_handler do |env_name, name, url, config|
891
+ next unless config.key?(:custom_config)
892
+ CustomConfig.new(env_name, name, url, config)
497
893
  end
498
894
  ```
499
895
 
500
- Enums will be presented correctly in `schema.rb`. Note that this is only supported by
501
- the PostgreSQL adapter.
896
+ When the application is booted, configuration hashes with the `:custom_config` key will be `CustomConfig` objects and respond to `sharded?`. Applications must handle the condition in which Active Record should use their custom handler.
897
+
898
+ *Eileen M. Uchitelle and John Crepezzi*
899
+
900
+ * `ActiveRecord::Base.serialize` no longer uses YAML by default.
901
+
902
+ YAML isn't particularly performant and can lead to security issues
903
+ if not used carefully.
904
+
905
+ Unfortunately there isn't really any good serializers in Ruby's stdlib
906
+ to replace it.
907
+
908
+ The obvious choice would be JSON, which is a fine format for this use case,
909
+ however the JSON serializer in Ruby's stdlib isn't strict enough, as it fallback
910
+ to casting unknown types to strings, which could lead to corrupted data.
911
+
912
+ Some third party JSON libraries like `Oj` have a suitable strict mode.
913
+
914
+ So it's preferable that users choose a serializer based on their own constraints.
915
+
916
+ The original default can be restored by setting `config.active_record.default_column_serializer = YAML`.
917
+
918
+ *Jean Boussier*
919
+
920
+ * `ActiveRecord::Base.serialize` signature changed.
921
+
922
+ Rather than a single positional argument that accepts two possible
923
+ types of values, `serialize` now accepts two distinct keyword arguments.
924
+
925
+ Before:
926
+
927
+ ```ruby
928
+ serialize :content, JSON
929
+ serialize :backtrace, Array
930
+ ```
931
+
932
+ After:
933
+
934
+ ```ruby
935
+ serialize :content, coder: JSON
936
+ serialize :backtrace, type: Array
937
+ ```
938
+
939
+ *Jean Boussier*
940
+
941
+ * YAML columns use `YAML.safe_dump` if available.
942
+
943
+ As of `psych 5.1.0`, `YAML.safe_dump` can now apply the same permitted
944
+ types restrictions than `YAML.safe_load`.
945
+
946
+ It's preferable to ensure the payload only use allowed types when we first
947
+ try to serialize it, otherwise you may end up with invalid records in the
948
+ database.
949
+
950
+ *Jean Boussier*
951
+
952
+ * `ActiveRecord::QueryLogs` better handle broken encoding.
953
+
954
+ It's not uncommon when building queries with BLOB fields to contain
955
+ binary data. Unless the call carefully encode the string in ASCII-8BIT
956
+ it generally end up being encoded in `UTF-8`, and `QueryLogs` would
957
+ end up failing on it.
958
+
959
+ `ActiveRecord::QueryLogs` no longer depend on the query to be properly encoded.
960
+
961
+ *Jean Boussier*
962
+
963
+ * Fix a bug where `ActiveRecord::Generators::ModelGenerator` would not respect create_table_migration template overrides.
964
+
965
+ ```
966
+ rails g model create_books title:string content:text
967
+ ```
968
+ will now read from the create_table_migration.rb.tt template in the following locations in order:
969
+ ```
970
+ lib/templates/active_record/model/create_table_migration.rb
971
+ lib/templates/active_record/migration/create_table_migration.rb
972
+ ```
973
+
974
+ *Spencer Neste*
975
+
976
+ * `ActiveRecord::Relation#explain` now accepts options.
977
+
978
+ For databases and adapters which support them (currently PostgreSQL
979
+ and MySQL), options can be passed to `explain` to provide more
980
+ detailed query plan analysis:
981
+
982
+ ```ruby
983
+ Customer.where(id: 1).joins(:orders).explain(:analyze, :verbose)
984
+ ```
985
+
986
+ *Reid Lynch*
987
+
988
+ * Multiple `Arel::Nodes::SqlLiteral` nodes can now be added together to
989
+ form `Arel::Nodes::Fragments` nodes. This allows joining several pieces
990
+ of SQL.
991
+
992
+ *Matthew Draper*, *Ole Friis*
993
+
994
+ * `ActiveRecord::Base#signed_id` raises if called on a new record.
995
+
996
+ Previously it would return an ID that was not usable, since it was based on `id = nil`.
502
997
 
503
998
  *Alex Ghiculescu*
504
999
 
505
- * Avoid COMMENT statements in PostgreSQL structure dumps
1000
+ * Allow SQL warnings to be reported.
1001
+
1002
+ Active Record configs can be set to enable SQL warning reporting.
506
1003
 
507
- COMMENT statements are now omitted from the output of `db:structure:dump` when using PostgreSQL >= 11.
508
- This allows loading the dump without a pgsql superuser account.
1004
+ ```ruby
1005
+ # Configure action to take when SQL query produces warning
1006
+ config.active_record.db_warnings_action = :raise
509
1007
 
510
- Fixes #36816, #43107.
1008
+ # Configure allowlist of warnings that should always be ignored
1009
+ config.active_record.db_warnings_ignore = [
1010
+ /Invalid utf8mb4 character string/,
1011
+ "An exact warning message",
1012
+ ]
1013
+ ```
511
1014
 
512
- *Janosch Müller*
1015
+ This is supported for the MySQL and PostgreSQL adapters.
513
1016
 
514
- * Add support for generated columns in PostgreSQL adapter
1017
+ *Adrianna Chang*, *Paarth Madan*
515
1018
 
516
- Generated columns are supported since version 12.0 of PostgreSQL. This adds
517
- support of those to the PostgreSQL adapter.
1019
+ * Add `#regroup` query method as a short-hand for `.unscope(:group).group(fields)`
1020
+
1021
+ Example:
518
1022
 
519
1023
  ```ruby
520
- create_table :users do |t|
521
- t.string :name
522
- t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true
523
- end
1024
+ Post.group(:title).regroup(:author)
1025
+ # SELECT `posts`.`*` FROM `posts` GROUP BY `posts`.`author`
524
1026
  ```
525
1027
 
526
- *Michał Begejowicz*
1028
+ *Danielius Visockas*
527
1029
 
1030
+ * PostgreSQL adapter method `enable_extension` now allows parameter to be `[schema_name.]<extension_name>`
1031
+ if the extension must be installed on another schema.
528
1032
 
529
- ## Rails 7.0.0.alpha2 (September 15, 2021) ##
1033
+ Example: `enable_extension('heroku_ext.hstore')`
530
1034
 
531
- * No changes.
1035
+ *Leonardo Luarte*
532
1036
 
1037
+ * Add `:include` option to `add_index`.
533
1038
 
534
- ## Rails 7.0.0.alpha1 (September 15, 2021) ##
1039
+ Add support for including non-key columns in indexes for PostgreSQL
1040
+ with the `INCLUDE` parameter.
535
1041
 
536
- * Remove warning when overwriting existing scopes
1042
+ ```ruby
1043
+ add_index(:users, :email, include: [:id, :created_at])
1044
+ ```
537
1045
 
538
- Removes the following unnecessary warning message that appeared when overwriting existing scopes
1046
+ will result in:
539
1047
 
1048
+ ```sql
1049
+ CREATE INDEX index_users_on_email USING btree (email) INCLUDE (id, created_at)
540
1050
  ```
541
- Creating scope :my_scope_name. Overwriting existing method "MyClass.my_scope_name" when overwriting existing scopes
1051
+
1052
+ *Steve Abrams*
1053
+
1054
+ * `ActiveRecord::Relation`’s `#any?`, `#none?`, and `#one?` methods take an optional pattern
1055
+ argument, more closely matching their `Enumerable` equivalents.
1056
+
1057
+ *George Claghorn*
1058
+
1059
+ * Add `ActiveRecord::Base.normalizes` for declaring attribute normalizations.
1060
+
1061
+ An attribute normalization is applied when the attribute is assigned or
1062
+ updated, and the normalized value will be persisted to the database. The
1063
+ normalization is also applied to the corresponding keyword argument of query
1064
+ methods, allowing records to be queried using unnormalized values.
1065
+
1066
+ For example:
1067
+
1068
+ ```ruby
1069
+ class User < ActiveRecord::Base
1070
+ normalizes :email, with: -> email { email.strip.downcase }
1071
+ normalizes :phone, with: -> phone { phone.delete("^0-9").delete_prefix("1") }
1072
+ end
1073
+
1074
+ user = User.create(email: " CRUISE-CONTROL@EXAMPLE.COM\n")
1075
+ user.email # => "cruise-control@example.com"
1076
+
1077
+ user = User.find_by(email: "\tCRUISE-CONTROL@EXAMPLE.COM ")
1078
+ user.email # => "cruise-control@example.com"
1079
+ user.email_before_type_cast # => "cruise-control@example.com"
1080
+
1081
+ User.where(email: "\tCRUISE-CONTROL@EXAMPLE.COM ").count # => 1
1082
+ User.where(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]).count # => 0
1083
+
1084
+ User.exists?(email: "\tCRUISE-CONTROL@EXAMPLE.COM ") # => true
1085
+ User.exists?(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]) # => false
1086
+
1087
+ User.normalize_value_for(:phone, "+1 (555) 867-5309") # => "5558675309"
1088
+ ```
1089
+
1090
+ *Jonathan Hefner*
1091
+
1092
+ * Hide changes to before_committed! callback behaviour behind flag.
1093
+
1094
+ In #46525, behavior around before_committed! callbacks was changed so that callbacks
1095
+ would run on every enrolled record in a transaction, not just the first copy of a record.
1096
+ This change in behavior is now controlled by a configuration option,
1097
+ `config.active_record.before_committed_on_all_records`. It will be enabled by default on Rails 7.1.
1098
+
1099
+ *Adrianna Chang*
1100
+
1101
+ * The `namespaced_controller` Query Log tag now matches the `controller` format
1102
+
1103
+ For example, a request processed by `NameSpaced::UsersController` will now log as:
1104
+
1105
+ ```
1106
+ :controller # "users"
1107
+ :namespaced_controller # "name_spaced/users"
1108
+ ```
1109
+
1110
+ *Alex Ghiculescu*
1111
+
1112
+ * Return only unique ids from ActiveRecord::Calculations#ids
1113
+
1114
+ Updated ActiveRecord::Calculations#ids to only return the unique ids of the base model
1115
+ when using eager_load, preload and includes.
1116
+
1117
+ ```ruby
1118
+ Post.find_by(id: 1).comments.count
1119
+ # => 5
1120
+ Post.includes(:comments).where(id: 1).pluck(:id)
1121
+ # => [1, 1, 1, 1, 1]
1122
+ Post.includes(:comments).where(id: 1).ids
1123
+ # => [1]
542
1124
  ```
543
1125
 
544
- *Weston Ganger*
1126
+ *Joshua Young*
545
1127
 
546
- * Use full precision for `updated_at` in `insert_all`/`upsert_all`
1128
+ * Stop using `LOWER()` for case-insensitive queries on `citext` columns
547
1129
 
548
- `CURRENT_TIMESTAMP` provides differing precision depending on the database,
549
- and not all databases support explicitly specifying additional precision.
1130
+ Previously, `LOWER()` was added for e.g. uniqueness validations with
1131
+ `case_sensitive: false`.
1132
+ It wasn't mentioned in the documentation that the index without `LOWER()`
1133
+ wouldn't be used in this case.
550
1134
 
551
- Instead, we delegate to the new `connection.high_precision_current_timestamp`
552
- for the SQL to produce a high precision timestamp on the current database.
1135
+ *Phil Pirozhkov*
553
1136
 
554
- Fixes #42992
1137
+ * Extract `#sync_timezone_changes` method in AbstractMysqlAdapter to enable subclasses
1138
+ to sync database timezone changes without overriding `#raw_execute`.
555
1139
 
556
- *Sam Bostock*
1140
+ *Adrianna Chang*, *Paarth Madan*
1141
+
1142
+ * Do not write additional new lines when dumping sql migration versions
1143
+
1144
+ This change updates the `insert_versions_sql` function so that the database insert string containing the current database migration versions does not end with two additional new lines.
1145
+
1146
+ *Misha Schwartz*
1147
+
1148
+ * Fix `composed_of` value freezing and duplication.
1149
+
1150
+ Previously composite values exhibited two confusing behaviors:
1151
+
1152
+ - When reading a compositve value it'd _NOT_ be frozen, allowing it to get out of sync with its underlying database
1153
+ columns.
1154
+ - When writing a compositve value the argument would be frozen, potentially confusing the caller.
1155
+
1156
+ Currently, composite values instantiated based on database columns are frozen (addressing the first issue) and
1157
+ assigned compositve values are duplicated and the duplicate is frozen (addressing the second issue).
1158
+
1159
+ *Greg Navis*
1160
+
1161
+ * Fix redundant updates to the column insensitivity cache
1162
+
1163
+ Fixed redundant queries checking column capability for insensitive
1164
+ comparison.
1165
+
1166
+ *Phil Pirozhkov*
1167
+
1168
+ * Allow disabling methods generated by `ActiveRecord.enum`.
557
1169
 
558
- * Add ssl support for postgresql database tasks
1170
+ *Alfred Dominic*
559
1171
 
560
- Add `PGSSLMODE`, `PGSSLCERT`, `PGSSLKEY` and `PGSSLROOTCERT` to pg_env from database config
561
- when running postgresql database tasks.
1172
+ * Avoid validating `belongs_to` association if it has not changed.
562
1173
 
563
- ```yaml
564
- # config/database.yml
1174
+ Previously, when updating a record, Active Record will perform an extra query to check for the presence of
1175
+ `belongs_to` associations (if the presence is configured to be mandatory), even if that attribute hasn't changed.
565
1176
 
566
- production:
567
- sslmode: verify-full
568
- sslcert: client.crt
569
- sslkey: client.key
570
- sslrootcert: ca.crt
571
- ```
1177
+ Currently, only `belongs_to`-related columns are checked for presence. It is possible to have orphaned records with
1178
+ this approach. To avoid this problem, you need to use a foreign key.
572
1179
 
573
- Environment variables
1180
+ This behavior can be controlled by configuration:
574
1181
 
575
- ```
576
- PGSSLMODE=verify-full
577
- PGSSLCERT=client.crt
578
- PGSSLKEY=client.key
579
- PGSSLROOTCERT=ca.crt
1182
+ ```ruby
1183
+ config.active_record.belongs_to_required_validates_foreign_key = false
580
1184
  ```
581
1185
 
582
- Fixes #42994
1186
+ and will be disabled by default with `config.load_defaults 7.1`.
583
1187
 
584
- *Michael Bayucot*
585
-
586
- * Avoid scoping update callbacks in `ActiveRecord::Relation#update!`.
1188
+ *fatkodima*
587
1189
 
588
- Making it consistent with how scoping is applied only to the query in `ActiveRecord::Relation#update`
589
- and not also to the callbacks from the update itself.
1190
+ * `has_one` and `belongs_to` associations now define a `reset_association` method
1191
+ on the owner model (where `association` is the name of the association). This
1192
+ method unloads the cached associate record, if any, and causes the next access
1193
+ to query it from the database.
590
1194
 
591
- *Dylan Thacker-Smith*
1195
+ *George Claghorn*
592
1196
 
593
- * Fix 2 cases that inferred polymorphic class from the association's `foreign_type`
594
- using `String#constantize` instead of the model's `polymorphic_class_for`.
1197
+ * Allow per attribute setting of YAML permitted classes (safe load) and unsafe load.
595
1198
 
596
- When updating a polymorphic association, the old `foreign_type` was not inferred correctly when:
597
- 1. `touch`ing the previously associated record
598
- 2. updating the previously associated record's `counter_cache`
1199
+ *Carlos Palhares*
599
1200
 
600
- *Jimmy Bourassa*
1201
+ * Add a build persistence method
601
1202
 
602
- * Add config option for ignoring tables when dumping the schema cache.
1203
+ Provides a wrapper for `new`, to provide feature parity with `create`s
1204
+ ability to create multiple records from an array of hashes, using the
1205
+ same notation as the `build` method on associations.
603
1206
 
604
- Applications can now be configured to ignore certain tables when dumping the schema cache.
1207
+ *Sean Denny*
605
1208
 
606
- The configuration option can table an array of tables:
1209
+ * Raise on assignment to readonly attributes
607
1210
 
608
1211
  ```ruby
609
- config.active_record.schema_cache_ignored_tables = ["ignored_table", "another_ignored_table"]
1212
+ class Post < ActiveRecord::Base
1213
+ attr_readonly :content
1214
+ end
1215
+ Post.create!(content: "cannot be updated")
1216
+ post.content # "cannot be updated"
1217
+ post.content = "something else" # => ActiveRecord::ReadonlyAttributeError
610
1218
  ```
611
1219
 
612
- Or a regex:
1220
+ Previously, assignment would succeed but silently not write to the database.
1221
+
1222
+ This behavior can be controlled by configuration:
613
1223
 
614
1224
  ```ruby
615
- config.active_record.schema_cache_ignored_tables = [/^_/]
1225
+ config.active_record.raise_on_assign_to_attr_readonly = true
616
1226
  ```
617
1227
 
618
- *Eileen M. Uchitelle*
1228
+ and will be enabled by default with `config.load_defaults 7.1`.
619
1229
 
620
- * Make schema cache methods return consistent results.
1230
+ *Alex Ghiculescu*, *Hartley McGuire*
621
1231
 
622
- Previously the schema cache methods `primary_keys`, `columns`, `columns_hash`, and `indexes`
623
- would behave differently than one another when a table didn't exist and differently across
624
- database adapters. This change unifies the behavior so each method behaves the same regardless
625
- of adapter.
1232
+ * Allow unscoping of preload and eager_load associations
626
1233
 
627
- The behavior now is:
1234
+ Added the ability to unscope preload and eager_load associations just like
1235
+ includes, joins, etc. See ActiveRecord::QueryMethods::VALID_UNSCOPING_VALUES
1236
+ for the full list of supported unscopable scopes.
628
1237
 
629
- `columns`: (unchanged) raises a db error if the table does not exist.
630
- `columns_hash`: (unchanged) raises a db error if the table does not exist.
631
- `primary_keys`: (unchanged) returns `nil` if the table does not exist.
632
- `indexes`: (changed for mysql2) returns `[]` if the table does not exist.
1238
+ ```ruby
1239
+ query.unscope(:eager_load, :preload).group(:id).select(:id)
1240
+ ```
633
1241
 
634
- *Eileen M. Uchitelle*
1242
+ *David Morehouse*
635
1243
 
636
- * Reestablish connection to previous database after after running `db:schema:load:name`
1244
+ * Add automatic filtering of encrypted attributes on inspect
637
1245
 
638
- After running `db:schema:load:name` the previous connection is restored.
1246
+ This feature is enabled by default but can be disabled with
639
1247
 
640
- *Jacopo Beschi*
1248
+ ```ruby
1249
+ config.active_record.encryption.add_to_filter_parameters = false
1250
+ ```
641
1251
 
642
- * Add database config option `database_tasks`
1252
+ *Hartley McGuire*
643
1253
 
644
- If you would like to connect to an external database without any database
645
- management tasks such as schema management, migrations, seeds, etc. you can set
646
- the per database config option `database_tasks: false`
1254
+ * Clear locking column on #dup
647
1255
 
648
- ```yaml
649
- # config/database.yml
1256
+ This change fixes not to duplicate locking_column like id and timestamps.
650
1257
 
651
- production:
652
- primary:
653
- database: my_database
654
- adapter: mysql2
655
- animals:
656
- database: my_animals_database
657
- adapter: mysql2
658
- database_tasks: false
1258
+ ```
1259
+ car = Car.create!
1260
+ car.touch
1261
+ car.lock_version #=> 1
1262
+ car.dup.lock_version #=> 0
659
1263
  ```
660
1264
 
661
- *Weston Ganger*
1265
+ *Shouichi Kamiya*, *Seonggi Yang*, *Ryohei UEDA*
662
1266
 
663
- * Fix `ActiveRecord::InternalMetadata` to not be broken by `config.active_record.record_timestamps = false`
1267
+ * Invalidate transaction as early as possible
664
1268
 
665
- Since the model always create the timestamp columns, it has to set them, otherwise it breaks
666
- various DB management tasks.
1269
+ After rescuing a `TransactionRollbackError` exception Rails invalidates transactions earlier in the flow
1270
+ allowing the framework to skip issuing the `ROLLBACK` statement in more cases.
1271
+ Only affects adapters that have `savepoint_errors_invalidate_transactions?` configured as `true`,
1272
+ which at this point is only applicable to the `mysql2` adapter.
667
1273
 
668
- Fixes #42983
1274
+ *Nikita Vasilevsky*
669
1275
 
670
- * Add `ActiveRecord::QueryLogs`.
1276
+ * Allow configuring columns list to be used in SQL queries issued by an `ActiveRecord::Base` object
671
1277
 
672
- Configurable tags can be automatically added to all SQL queries generated by Active Record.
1278
+ It is now possible to configure columns list that will be used to build an SQL query clauses when
1279
+ updating, deleting or reloading an `ActiveRecord::Base` object
673
1280
 
674
1281
  ```ruby
675
- # config/application.rb
676
- module MyApp
677
- class Application < Rails::Application
678
- config.active_record.query_log_tags_enabled = true
679
- end
1282
+ class Developer < ActiveRecord::Base
1283
+ query_constraints :company_id, :id
680
1284
  end
1285
+ developer = Developer.first.update(name: "Bob")
1286
+ # => UPDATE "developers" SET "name" = 'Bob' WHERE "developers"."company_id" = 1 AND "developers"."id" = 1
681
1287
  ```
682
1288
 
683
- By default the application, controller and action details are added to the query tags:
1289
+ *Nikita Vasilevsky*
684
1290
 
685
- ```ruby
686
- class BooksController < ApplicationController
687
- def index
688
- @books = Book.all
689
- end
690
- end
691
- ```
1291
+ * Adds `validate` to foreign keys and check constraints in schema.rb
692
1292
 
693
- ```ruby
694
- GET /books
695
- # SELECT * FROM books /*application:MyApp;controller:books;action:index*/
696
- ```
1293
+ Previously, `schema.rb` would not record if `validate: false` had been used when adding a foreign key or check
1294
+ constraint, so restoring a database from the schema could result in foreign keys or check constraints being
1295
+ incorrectly validated.
697
1296
 
698
- Custom tags containing static values and Procs can be defined in the application configuration:
1297
+ *Tommy Graves*
699
1298
 
700
- ```ruby
701
- config.active_record.query_log_tags = [
702
- :application,
703
- :controller,
704
- :action,
705
- {
706
- custom_static: "foo",
707
- custom_dynamic: -> { Time.now }
708
- }
709
- ]
710
- ```
1299
+ * Adapter `#execute` methods now accept an `allow_retry` option. When set to `true`, the SQL statement will be
1300
+ retried, up to the database's configured `connection_retries` value, upon encountering connection-related errors.
711
1301
 
712
- *Keeran Raj Hawoldar*, *Eileen M. Uchitelle*, *Kasper Timm Hansen*
1302
+ *Adrianna Chang*
713
1303
 
714
- * Added support for multiple databases to `rails db:setup` and `rails db:reset`.
1304
+ * Only trigger `after_commit :destroy` callbacks when a database row is deleted.
715
1305
 
716
- *Ryan Hall*
1306
+ This prevents `after_commit :destroy` callbacks from being triggered again
1307
+ when `destroy` is called multiple times on the same record.
717
1308
 
718
- * Add `ActiveRecord::Relation#structurally_compatible?`.
1309
+ *Ben Sheldon*
719
1310
 
720
- Adds a query method by which a user can tell if the relation that they're
721
- about to use for `#or` or `#and` is structurally compatible with the
722
- receiver.
1311
+ * Fix `ciphertext_for` for yet-to-be-encrypted values.
723
1312
 
724
- *Kevin Newton*
1313
+ Previously, `ciphertext_for` returned the cleartext of values that had not
1314
+ yet been encrypted, such as with an unpersisted record:
725
1315
 
726
- * Add `ActiveRecord::QueryMethods#in_order_of`.
1316
+ ```ruby
1317
+ Post.encrypts :body
727
1318
 
728
- This allows you to specify an explicit order that you'd like records
729
- returned in based on a SQL expression. By default, this will be accomplished
730
- using a case statement, as in:
1319
+ post = Post.create!(body: "Hello")
1320
+ post.ciphertext_for(:body)
1321
+ # => "{\"p\":\"abc..."
731
1322
 
732
- ```ruby
733
- Post.in_order_of(:id, [3, 5, 1])
734
- ```
1323
+ post.body = "World"
1324
+ post.ciphertext_for(:body)
1325
+ # => "World"
1326
+ ```
735
1327
 
736
- will generate the SQL:
1328
+ Now, `ciphertext_for` will always return the ciphertext of encrypted
1329
+ attributes:
737
1330
 
738
- ```sql
739
- SELECT "posts".* FROM "posts" ORDER BY CASE "posts"."id" WHEN 3 THEN 1 WHEN 5 THEN 2 WHEN 1 THEN 3 ELSE 4 END ASC
740
- ```
1331
+ ```ruby
1332
+ Post.encrypts :body
741
1333
 
742
- However, because this functionality is built into MySQL in the form of the
743
- `FIELD` function, that connection adapter will generate the following SQL
744
- instead:
1334
+ post = Post.create!(body: "Hello")
1335
+ post.ciphertext_for(:body)
1336
+ # => "{\"p\":\"abc..."
745
1337
 
746
- ```sql
747
- SELECT "posts".* FROM "posts" ORDER BY FIELD("posts"."id", 1, 5, 3) DESC
748
- ```
1338
+ post.body = "World"
1339
+ post.ciphertext_for(:body)
1340
+ # => "{\"p\":\"xyz..."
1341
+ ```
749
1342
 
750
- *Kevin Newton*
1343
+ *Jonathan Hefner*
751
1344
 
752
- * Fix `eager_loading?` when ordering with `Symbol`.
1345
+ * Fix a bug where using groups and counts with long table names would return incorrect results.
753
1346
 
754
- `eager_loading?` is triggered correctly when using `order` with symbols.
1347
+ *Shota Toguchi*, *Yusaku Ono*
755
1348
 
756
- ```ruby
757
- scope = Post.includes(:comments).order(:"comments.label")
758
- => true
759
- ```
1349
+ * Fix encryption of column default values.
760
1350
 
761
- *Jacopo Beschi*
1351
+ Previously, encrypted attributes that used column default values appeared to
1352
+ be encrypted on create, but were not:
762
1353
 
763
- * Two change tracking methods are added for `belongs_to` associations.
1354
+ ```ruby
1355
+ Book.encrypts :name
764
1356
 
765
- The `association_changed?` method (assuming an association named `:association`) returns true
766
- if a different associated object has been assigned and the foreign key will be updated in the
767
- next save.
1357
+ book = Book.create!
1358
+ book.name
1359
+ # => "<untitled>"
1360
+ book.name_before_type_cast
1361
+ # => "{\"p\":\"abc..."
1362
+ book.reload.name_before_type_cast
1363
+ # => "<untitled>"
1364
+ ```
768
1365
 
769
- The `association_previously_changed?` method returns true if the previous save updated the
770
- association to reference a different associated object.
1366
+ Now, attributes with column default values are encrypted:
771
1367
 
772
- *George Claghorn*
1368
+ ```ruby
1369
+ Book.encrypts :name
773
1370
 
774
- * Add option to disable schema dump per-database.
1371
+ book = Book.create!
1372
+ book.name
1373
+ # => "<untitled>"
1374
+ book.name_before_type_cast
1375
+ # => "{\"p\":\"abc..."
1376
+ book.reload.name_before_type_cast
1377
+ # => "{\"p\":\"abc..."
1378
+ ```
775
1379
 
776
- Dumping the schema is on by default for all databases in an application. To turn it off for a
777
- specific database, use the `schema_dump` option:
1380
+ *Jonathan Hefner*
778
1381
 
779
- ```yaml
780
- # config/database.yml
1382
+ * Deprecate delegation from `Base` to `connection_handler`.
781
1383
 
782
- production:
783
- schema_dump: false
784
- ```
1384
+ Calling `Base.clear_all_connections!`, `Base.clear_active_connections!`, `Base.clear_reloadable_connections!` and `Base.flush_idle_connections!` is deprecated. Please call these methods on the connection handler directly. In future Rails versions, the delegation from `Base` to the `connection_handler` will be removed.
785
1385
 
786
- *Luis Vasconcellos*, *Eileen M. Uchitelle*
1386
+ *Eileen M. Uchitelle*
787
1387
 
788
- * Fix `eager_loading?` when ordering with `Hash` syntax.
1388
+ * Allow ActiveRecord::QueryMethods#reselect to receive hash values, similar to ActiveRecord::QueryMethods#select
789
1389
 
790
- `eager_loading?` is triggered correctly when using `order` with hash syntax
791
- on an outer table.
1390
+ *Sampat Badhe*
792
1391
 
793
- ```ruby
794
- Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading?
795
- # => true
796
- ```
1392
+ * Validate options when managing columns and tables in migrations.
797
1393
 
798
- *Jacopo Beschi*
1394
+ If an invalid option is passed to a migration method like `create_table` and `add_column`, an error will be raised
1395
+ instead of the option being silently ignored. Validation of the options will only be applied for new migrations
1396
+ that are created.
799
1397
 
800
- * Move the forcing of clear text encoding to the `ActiveRecord::Encryption::Encryptor`.
1398
+ *Guo Xiang Tan*, *George Wambold*
801
1399
 
802
- Fixes #42699.
1400
+ * Update query log tags to use the [SQLCommenter](https://open-telemetry.github.io/opentelemetry-sqlcommenter/) format by default. See [#46179](https://github.com/rails/rails/issues/46179)
803
1401
 
804
- *J Smith*
1402
+ To opt out of SQLCommenter-formatted query log tags, set `config.active_record.query_log_tags_format = :legacy`. By default, this is set to `:sqlcommenter`.
805
1403
 
806
- * `partial_inserts` is now disabled by default in new apps.
1404
+ *Modulitos* and *Iheanyi*
807
1405
 
808
- This will be the default for new apps in Rails 7. To opt in:
1406
+ * Allow any ERB in the database.yml when creating rake tasks.
809
1407
 
810
- ```ruby
811
- config.active_record.partial_inserts = true
812
- ```
1408
+ Any ERB can be used in `database.yml` even if it accesses environment
1409
+ configurations.
813
1410
 
814
- If a migration removes the default value of a column, this option
815
- would cause old processes to no longer be able to create new records.
1411
+ Deprecates `config.active_record.suppress_multiple_database_warning`.
816
1412
 
817
- If you need to remove a column, you should first use `ignored_columns`
818
- to stop using it.
1413
+ *Eike Send*
819
1414
 
820
- *Jean Boussier*
1415
+ * Add table to error for duplicate column definitions.
821
1416
 
822
- * Rails can now verify foreign keys after loading fixtures in tests.
1417
+ If a migration defines duplicate columns for a table, the error message
1418
+ shows which table it concerns.
823
1419
 
824
- This will be the default for new apps in Rails 7. To opt in:
1420
+ *Petrik de Heus*
825
1421
 
826
- ```ruby
827
- config.active_record.verify_foreign_keys_for_fixtures = true
828
- ```
1422
+ * Fix erroneous nil default precision on virtual datetime columns.
829
1423
 
830
- Tests will not run if there is a foreign key constraint violation in your fixture data.
1424
+ Prior to this change, virtual datetime columns did not have the same
1425
+ default precision as regular datetime columns, resulting in the following
1426
+ being erroneously equivalent:
831
1427
 
832
- The feature is supported by SQLite and PostgreSQL, other adapters can also add support for it.
1428
+ t.virtual :name, type: datetime, as: "expression"
1429
+ t.virtual :name, type: datetime, precision: nil, as: "expression"
833
1430
 
834
- *Alex Ghiculescu*
1431
+ This change fixes the default precision lookup, so virtual and regular
1432
+ datetime column default precisions match.
835
1433
 
836
- * Clear cached `has_one` association after setting `belongs_to` association to `nil`.
1434
+ *Sam Bostock*
837
1435
 
838
- After setting a `belongs_to` relation to `nil` and updating an unrelated attribute on the owner,
839
- the owner should still return `nil` on the `has_one` relation.
1436
+ * Use connection from `#with_raw_connection` in `#quote_string`.
840
1437
 
841
- Fixes #42597.
1438
+ This ensures that the string quoting is wrapped in the reconnect and retry logic
1439
+ that `#with_raw_connection` offers.
842
1440
 
843
- *Michiel de Mare*
1441
+ *Adrianna Chang*
844
1442
 
845
- * OpenSSL constants are now used for Digest computations.
1443
+ * Add `expires_at` option to `signed_id`.
846
1444
 
847
- *Dirkjan Bussink*
1445
+ *Shouichi Kamiya*
848
1446
 
849
- * Adds support for `if_not_exists` to `add_foreign_key` and `if_exists` to `remove_foreign_key`.
1447
+ * Allow applications to set retry deadline for query retries.
850
1448
 
851
- Applications can set their migrations to ignore exceptions raised when adding a foreign key
852
- that already exists or when removing a foreign key that does not exist.
1449
+ Building on the work done in #44576 and #44591, we extend the logic that automatically
1450
+ reconnects database connections to take into account a timeout limit. We won't retry
1451
+ a query if a given amount of time has elapsed since the query was first attempted. This
1452
+ value defaults to nil, meaning that all retryable queries are retried regardless of time elapsed,
1453
+ but this can be changed via the `retry_deadline` option in the database config.
853
1454
 
854
- Example Usage:
1455
+ *Adrianna Chang*
855
1456
 
856
- ```ruby
857
- class AddAuthorsForeignKeyToArticles < ActiveRecord::Migration[7.0]
858
- def change
859
- add_foreign_key :articles, :authors, if_not_exists: true
860
- end
861
- end
862
- ```
1457
+ * Fix a case where the query cache can return wrong values. See #46044
863
1458
 
864
- ```ruby
865
- class RemoveAuthorsForeignKeyFromArticles < ActiveRecord::Migration[7.0]
866
- def change
867
- remove_foreign_key :articles, :authors, if_exists: true
868
- end
869
- end
870
- ```
1459
+ *Aaron Patterson*
1460
+
1461
+ * Support MySQL's ssl-mode option for MySQLDatabaseTasks.
871
1462
 
872
- *Roberto Miranda*
1463
+ Verifying the identity of the database server requires setting the ssl-mode
1464
+ option to VERIFY_CA or VERIFY_IDENTITY. This option was previously ignored
1465
+ for MySQL database tasks like creating a database and dumping the structure.
873
1466
 
874
- * Prevent polluting ENV during postgresql structure dump/load.
1467
+ *Petrik de Heus*
875
1468
 
876
- Some configuration parameters were provided to pg_dump / psql via
877
- environment variables which persisted beyond the command being run, and may
878
- have caused subsequent commands and connections to fail. Tasks running
879
- across multiple postgresql databases like `rails db:test:prepare` may have
880
- been affected.
1469
+ * Move `ActiveRecord::InternalMetadata` to an independent object.
881
1470
 
882
- *Samuel Cochran*
1471
+ `ActiveRecord::InternalMetadata` no longer inherits from `ActiveRecord::Base` and is now an independent object that should be instantiated with a `connection`. This class is private and should not be used by applications directly. If you want to interact with the schema migrations table, please access it on the connection directly, for example: `ActiveRecord::Base.connection.schema_migration`.
883
1472
 
884
- * Set precision 6 by default for `datetime` columns.
1473
+ *Eileen M. Uchitelle*
885
1474
 
886
- By default, datetime columns will have microseconds precision instead of seconds precision.
1475
+ * Deprecate quoting `ActiveSupport::Duration` as an integer
887
1476
 
888
- *Roberto Miranda*
1477
+ Using ActiveSupport::Duration as an interpolated bind parameter in a SQL
1478
+ string template is deprecated. To avoid this warning, you should explicitly
1479
+ convert the duration to a more specific database type. For example, if you
1480
+ want to use a duration as an integer number of seconds:
1481
+ ```
1482
+ Record.where("duration = ?", 1.hour.to_i)
1483
+ ```
1484
+ If you want to use a duration as an ISO 8601 string:
1485
+ ```
1486
+ Record.where("duration = ?", 1.hour.iso8601)
1487
+ ```
889
1488
 
890
- * Allow preloading of associations with instance dependent scopes.
1489
+ *Aram Greenman*
891
1490
 
892
- *John Hawthorn*, *John Crepezzi*, *Adam Hess*, *Eileen M. Uchitelle*, *Dinah Shi*
1491
+ * Allow `QueryMethods#in_order_of` to order by a string column name.
893
1492
 
894
- * Do not try to rollback transactions that failed due to a `ActiveRecord::TransactionRollbackError`.
1493
+ ```ruby
1494
+ Post.in_order_of("id", [4,2,3,1]).to_a
1495
+ Post.joins(:author).in_order_of("authors.name", ["Bob", "Anna", "John"]).to_a
1496
+ ```
895
1497
 
896
- *Jamie McCarthy*
1498
+ *Igor Kasyanchuk*
897
1499
 
898
- * Active Record Encryption will now encode values as UTF-8 when using deterministic
899
- encryption. The encoding is part of the encrypted payload, so different encodings for
900
- different values result in different ciphertexts. This can break unique constraints and
901
- queries.
1500
+ * Move `ActiveRecord::SchemaMigration` to an independent object.
902
1501
 
903
- The new behavior is configurable via `active_record.encryption.forced_encoding_for_deterministic_encryption`
904
- that is `Encoding::UTF_8` by default. It can be disabled by setting it to `nil`.
1502
+ `ActiveRecord::SchemaMigration` no longer inherits from `ActiveRecord::Base` and is now an independent object that should be instantiated with a `connection`. This class is private and should not be used by applications directly. If you want to interact with the schema migrations table, please access it on the connection directly, for example: `ActiveRecord::Base.connection.schema_migration`.
905
1503
 
906
- *Jorge Manrubia*
1504
+ *Eileen M. Uchitelle*
907
1505
 
908
- * The MySQL adapter now cast numbers and booleans bind parameters to string for safety reasons.
1506
+ * Deprecate `all_connection_pools` and make `connection_pool_list` more explicit.
909
1507
 
910
- When comparing a string and a number in a query, MySQL converts the string to a number. So for
911
- instance `"foo" = 0`, will implicitly cast `"foo"` to `0` and will evaluate to `TRUE` which can
912
- lead to security vulnerabilities.
1508
+ Following on #45924 `all_connection_pools` is now deprecated. `connection_pool_list` will either take an explicit role or applications can opt into the new behavior by passing `:all`.
913
1509
 
914
- Active Record already protect against that vulnerability when it knows the type of the column
915
- being compared, however until now it was still vulnerable when using bind parameters:
1510
+ *Eileen M. Uchitelle*
916
1511
 
917
- ```ruby
918
- User.where("login_token = ?", 0).first
919
- ```
1512
+ * Fix connection handler methods to operate on all pools.
920
1513
 
921
- Would perform:
1514
+ `active_connections?`, `clear_active_connections!`, `clear_reloadable_connections!`, `clear_all_connections!`, and `flush_idle_connections!` now operate on all pools by default. Previously they would default to using the `current_role` or `:writing` role unless specified.
922
1515
 
923
- ```sql
924
- SELECT * FROM `users` WHERE `login_token` = 0 LIMIT 1;
925
- ```
1516
+ *Eileen M. Uchitelle*
926
1517
 
927
- Now it will perform:
928
1518
 
929
- ```sql
930
- SELECT * FROM `users` WHERE `login_token` = '0' LIMIT 1;
931
- ```
1519
+ * Allow ActiveRecord::QueryMethods#select to receive hash values.
932
1520
 
933
- *Jean Boussier*
1521
+ Currently, `select` might receive only raw sql and symbols to define columns and aliases to select.
934
1522
 
935
- * Fixture configurations (`_fixture`) are now strictly validated.
1523
+ With this change we can provide `hash` as argument, for example:
936
1524
 
937
- If an error will be raised if that entry contains unknown keys while previously it
938
- would silently have no effects.
1525
+ ```ruby
1526
+ Post.joins(:comments).select(posts: [:id, :title, :created_at], comments: [:id, :body, :author_id])
1527
+ #=> "SELECT \"posts\".\"id\", \"posts\".\"title\", \"posts\".\"created_at\", \"comments\".\"id\", \"comments\".\"body\", \"comments\".\"author_id\"
1528
+ # FROM \"posts\" INNER JOIN \"comments\" ON \"comments\".\"post_id\" = \"posts\".\"id\""
939
1529
 
940
- *Jean Boussier*
1530
+ Post.joins(:comments).select(posts: { id: :post_id, title: :post_title }, comments: { id: :comment_id, body: :comment_body })
1531
+ #=> "SELECT posts.id as post_id, posts.title as post_title, comments.id as comment_id, comments.body as comment_body
1532
+ # FROM \"posts\" INNER JOIN \"comments\" ON \"comments\".\"post_id\" = \"posts\".\"id\""
1533
+ ```
1534
+ *Oleksandr Holubenko*, *Josef Šimánek*, *Jean Boussier*
941
1535
 
942
- * Add `ActiveRecord::Base.update!` that works like `ActiveRecord::Base.update` but raises exceptions.
1536
+ * Adapts virtual attributes on `ActiveRecord::Persistence#becomes`.
943
1537
 
944
- This allows for the same behavior as the instance method `#update!` at a class level.
1538
+ When source and target classes have a different set of attributes adapts
1539
+ attributes such that the extra attributes from target are added.
945
1540
 
946
1541
  ```ruby
947
- Person.update!(:all, state: "confirmed")
1542
+ class Person < ApplicationRecord
1543
+ end
1544
+
1545
+ class WebUser < Person
1546
+ attribute :is_admin, :boolean
1547
+ after_initialize :set_admin
1548
+
1549
+ def set_admin
1550
+ write_attribute(:is_admin, email =~ /@ourcompany\.com$/)
1551
+ end
1552
+ end
1553
+
1554
+ person = Person.find_by(email: "email@ourcompany.com")
1555
+ person.respond_to? :is_admin
1556
+ # => false
1557
+ person.becomes(WebUser).is_admin?
1558
+ # => true
948
1559
  ```
949
1560
 
950
- *Dorian Marié*
1561
+ *Jacopo Beschi*, *Sampson Crowley*
1562
+
1563
+ * Fix `ActiveRecord::QueryMethods#in_order_of` to include `nil`s, to match the
1564
+ behavior of `Enumerable#in_order_of`.
951
1565
 
952
- * Add `ActiveRecord::Base#attributes_for_database`.
1566
+ For example, `Post.in_order_of(:title, [nil, "foo"])` will now include posts
1567
+ with `nil` titles, the same as `Post.all.to_a.in_order_of(:title, [nil, "foo"])`.
953
1568
 
954
- Returns attributes with values for assignment to the database.
1569
+ *fatkodima*
955
1570
 
956
- *Chris Salzberg*
1571
+ * Optimize `add_timestamps` to use a single SQL statement.
957
1572
 
958
- * Use an empty query to check if the PostgreSQL connection is still active.
1573
+ ```ruby
1574
+ add_timestamps :my_table
1575
+ ```
959
1576
 
960
- An empty query is faster than `SELECT 1`.
1577
+ Now results in the following SQL:
961
1578
 
962
- *Heinrich Lee Yu*
1579
+ ```sql
1580
+ ALTER TABLE "my_table" ADD COLUMN "created_at" datetime(6) NOT NULL, ADD COLUMN "updated_at" datetime(6) NOT NULL
1581
+ ```
963
1582
 
964
- * Add `ActiveRecord::Base#previously_persisted?`.
1583
+ *Iliana Hadzhiatanasova*
965
1584
 
966
- Returns `true` if the object has been previously persisted but now it has been deleted.
1585
+ * Add `drop_enum` migration command for PostgreSQL
967
1586
 
968
- * Deprecate `partial_writes` in favor of `partial_inserts` and `partial_updates`.
1587
+ This does the inverse of `create_enum`. Before dropping an enum, ensure you have
1588
+ dropped columns that depend on it.
969
1589
 
970
- This allows to have a different behavior on update and create.
1590
+ *Alex Ghiculescu*
971
1591
 
972
- *Jean Boussier*
1592
+ * Adds support for `if_exists` option when removing a check constraint.
973
1593
 
974
- * Fix compatibility with `psych >= 4`.
1594
+ The `remove_check_constraint` method now accepts an `if_exists` option. If set
1595
+ to true an error won't be raised if the check constraint doesn't exist.
975
1596
 
976
- Starting in Psych 4.0.0 `YAML.load` behaves like `YAML.safe_load`. To preserve compatibility,
977
- Active Record's schema cache loader and `YAMLColumn` now uses `YAML.unsafe_load` if available.
1597
+ *Margaret Parsa* and *Aditya Bhutani*
978
1598
 
979
- *Jean Boussier*
1599
+ * `find_or_create_by` now try to find a second time if it hits a unicity constraint.
980
1600
 
981
- * `ActiveRecord::Base.logger` is now a `class_attribute`.
1601
+ `find_or_create_by` always has been inherently racy, either creating multiple
1602
+ duplicate records or failing with `ActiveRecord::RecordNotUnique` depending on
1603
+ whether a proper unicity constraint was set.
982
1604
 
983
- This means it can no longer be accessed directly through `@@logger`, and that setting `logger =`
984
- on a subclass won't change the parent's logger.
1605
+ `create_or_find_by` was introduced for this use case, however it's quite wasteful
1606
+ when the record is expected to exist most of the time, as INSERT require to send
1607
+ more data than SELECT and require more work from the database. Also on some
1608
+ databases it can actually consume a primary key increment which is undesirable.
985
1609
 
986
- *Jean Boussier*
1610
+ So for case where most of the time the record is expected to exist, `find_or_create_by`
1611
+ can be made race-condition free by re-trying the `find` if the `create` failed
1612
+ with `ActiveRecord::RecordNotUnique`. This assumes that the table has the proper
1613
+ unicity constraints, if not, `find_or_create_by` will still lead to duplicated records.
987
1614
 
988
- * Add `.asc.nulls_first` for all databases. Unfortunately MySQL still doesn't like `nulls_last`.
1615
+ *Jean Boussier*, *Alex Kitchens*
989
1616
 
990
- *Keenan Brock*
1617
+ * Introduce a simpler constructor API for ActiveRecord database adapters.
991
1618
 
992
- * Improve performance of `one?` and `many?` by limiting the generated count query to 2 results.
1619
+ Previously the adapter had to know how to build a new raw connection to
1620
+ support reconnect, but also expected to be passed an initial already-
1621
+ established connection.
993
1622
 
994
- *Gonzalo Riestra*
1623
+ When manually creating an adapter instance, it will now accept a single
1624
+ config hash, and only establish the real connection on demand.
995
1625
 
996
- * Don't check type when using `if_not_exists` on `add_column`.
1626
+ *Matthew Draper*
997
1627
 
998
- Previously, if a migration called `add_column` with the `if_not_exists` option set to true
999
- the `column_exists?` check would look for a column with the same name and type as the migration.
1628
+ * Avoid redundant `SELECT 1` connection-validation query during DB pool
1629
+ checkout when possible.
1000
1630
 
1001
- Recently it was discovered that the type passed to the migration is not always the same type
1002
- as the column after migration. For example a column set to `:mediumblob` in the migration will
1003
- be casted to `binary` when calling `column.type`. Since there is no straightforward way to cast
1004
- the type to the database type without running the migration, we opted to drop the type check from
1005
- `add_column`. This means that migrations adding a duplicate column with a different type will no
1006
- longer raise an error.
1631
+ If the first query run during a request is known to be idempotent, it can be
1632
+ used directly to validate the connection, saving a network round-trip.
1007
1633
 
1008
- *Eileen M. Uchitelle*
1634
+ *Matthew Draper*
1009
1635
 
1010
- * Log a warning message when running SQLite in production.
1636
+ * Automatically reconnect broken database connections when safe, even
1637
+ mid-request.
1011
1638
 
1012
- Using SQLite in production ENV is generally discouraged. SQLite is also the default adapter
1013
- in a new Rails application.
1014
- For the above reasons log a warning message when running SQLite in production.
1639
+ When an error occurs while attempting to run a known-idempotent query, and
1640
+ not inside a transaction, it is safe to immediately reconnect to the
1641
+ database server and try again, so this is now the default behavior.
1015
1642
 
1016
- The warning can be disabled by setting `config.active_record.sqlite3_production_warning=false`.
1643
+ This new default should always be safe -- to support that, it's consciously
1644
+ conservative about which queries are considered idempotent -- but if
1645
+ necessary it can be disabled by setting the `connection_retries` connection
1646
+ option to `0`.
1017
1647
 
1018
- *Jacopo Beschi*
1648
+ *Matthew Draper*
1019
1649
 
1020
- * Add option to disable joins for `has_one` associations.
1650
+ * Avoid removing a PostgreSQL extension when there are dependent objects.
1021
1651
 
1022
- In a multiple database application, associations can't join across
1023
- databases. When set, this option instructs Rails to generate 2 or
1024
- more queries rather than generating joins for `has_one` associations.
1652
+ Previously, removing an extension also implicitly removed dependent objects. Now, this will raise an error.
1025
1653
 
1026
- Set the option on a has one through association:
1654
+ You can force removing the extension:
1027
1655
 
1028
1656
  ```ruby
1029
- class Person
1030
- has_one :dog
1031
- has_one :veterinarian, through: :dog, disable_joins: true
1032
- end
1657
+ disable_extension :citext, force: :cascade
1033
1658
  ```
1034
1659
 
1035
- Then instead of generating join SQL, two queries are used for `@person.veterinarian`:
1660
+ Fixes #29091.
1036
1661
 
1037
- ```
1038
- SELECT "dogs"."id" FROM "dogs" WHERE "dogs"."person_id" = ? [["person_id", 1]]
1039
- SELECT "veterinarians".* FROM "veterinarians" WHERE "veterinarians"."dog_id" = ? [["dog_id", 1]]
1040
- ```
1662
+ *fatkodima*
1041
1663
 
1042
- *Sarah Vessels*, *Eileen M. Uchitelle*
1664
+ * Allow nested functions as safe SQL string
1043
1665
 
1044
- * `Arel::Visitors::Dot` now renders a complete set of properties when visiting
1045
- `Arel::Nodes::SelectCore`, `SelectStatement`, `InsertStatement`, `UpdateStatement`, and
1046
- `DeleteStatement`, which fixes #42026. Previously, some properties were omitted.
1666
+ *Michael Siegfried*
1047
1667
 
1048
- *Mike Dalessio*
1668
+ * Allow `destroy_association_async_job=` to be configured with a class string instead of a constant.
1049
1669
 
1050
- * `Arel::Visitors::Dot` now supports `Arel::Nodes::Bin`, `Case`, `CurrentRow`, `Distinct`,
1051
- `DistinctOn`, `Else`, `Except`, `InfixOperation`, `Intersect`, `Lock`, `NotRegexp`, `Quoted`,
1052
- `Regexp`, `UnaryOperation`, `Union`, `UnionAll`, `When`, and `With`. Previously, these node
1053
- types caused an exception to be raised by `Arel::Visitors::Dot#accept`.
1670
+ Defers an autoloading dependency between `ActiveRecord::Base` and `ActiveJob::Base`
1671
+ and moves the configuration of `ActiveRecord::DestroyAssociationAsyncJob`
1672
+ from ActiveJob to ActiveRecord.
1054
1673
 
1055
- *Mike Dalessio*
1674
+ Deprecates `ActiveRecord::ActiveJobRequiredError` and now raises a `NameError`
1675
+ if the job class is unloadable or an `ActiveRecord::ConfigurationError` if
1676
+ `dependent: :destroy_async` is declared on an association but there is no job
1677
+ class configured.
1056
1678
 
1057
- * Optimize `remove_columns` to use a single SQL statement.
1679
+ *Ben Sheldon*
1058
1680
 
1059
- ```ruby
1060
- remove_columns :my_table, :col_one, :col_two
1061
- ```
1681
+ * Fix `ActiveRecord::Store` to serialize as a regular Hash
1062
1682
 
1063
- Now results in the following SQL:
1683
+ Previously it would serialize as an `ActiveSupport::HashWithIndifferentAccess`
1684
+ which is wasteful and cause problem with YAML safe_load.
1064
1685
 
1065
- ```sql
1066
- ALTER TABLE "my_table" DROP COLUMN "col_one", DROP COLUMN "col_two"
1067
- ```
1686
+ *Jean Boussier*
1068
1687
 
1069
- *Jon Dufresne*
1688
+ * Add `timestamptz` as a time zone aware type for PostgreSQL
1070
1689
 
1071
- * Ensure `has_one` autosave association callbacks get called once.
1690
+ This is required for correctly parsing `timestamp with time zone` values in your database.
1072
1691
 
1073
- Change the `has_one` autosave callback to be non cyclic as well.
1074
- By doing this the autosave callback are made more consistent for
1075
- all 3 cases: `has_many`, `has_one`, and `belongs_to`.
1692
+ If you don't want this, you can opt out by adding this initializer:
1076
1693
 
1077
- *Petrik de Heus*
1694
+ ```ruby
1695
+ ActiveRecord::Base.time_zone_aware_types -= [:timestamptz]
1696
+ ```
1078
1697
 
1079
- * Add option to disable joins for associations.
1698
+ *Alex Ghiculescu*
1699
+
1700
+ * Add new `ActiveRecord::Base.generates_token_for` API.
1080
1701
 
1081
- In a multiple database application, associations can't join across
1082
- databases. When set, this option instructs Rails to generate 2 or
1083
- more queries rather than generating joins for associations.
1702
+ Currently, `signed_id` fulfills the role of generating tokens for e.g.
1703
+ resetting a password. However, signed IDs cannot reflect record state, so
1704
+ if a token is intended to be single-use, it must be tracked in a database at
1705
+ least until it expires.
1084
1706
 
1085
- Set the option on a has many through association:
1707
+ With `generates_token_for`, a token can embed data from a record. When
1708
+ using the token to fetch the record, the data from the token and the current
1709
+ data from the record will be compared. If the two do not match, the token
1710
+ will be treated as invalid, the same as if it had expired. For example:
1086
1711
 
1087
1712
  ```ruby
1088
- class Dog
1089
- has_many :treats, through: :humans, disable_joins: true
1090
- has_many :humans
1713
+ class User < ActiveRecord::Base
1714
+ has_secure_password
1715
+
1716
+ generates_token_for :password_reset, expires_in: 15.minutes do
1717
+ # A password's BCrypt salt changes when the password is updated.
1718
+ # By embedding (part of) the salt in a token, the token will
1719
+ # expire when the password is updated.
1720
+ BCrypt::Password.new(password_digest).salt[-10..]
1721
+ end
1091
1722
  end
1092
- ```
1093
1723
 
1094
- Then instead of generating join SQL, two queries are used for `@dog.treats`:
1724
+ user = User.first
1725
+ token = user.generate_token_for(:password_reset)
1726
+
1727
+ User.find_by_token_for(:password_reset, token) # => user
1095
1728
 
1096
- ```
1097
- SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ? [["dog_id", 1]]
1098
- SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?) [["human_id", 1], ["human_id", 2], ["human_id", 3]]
1729
+ user.update!(password: "new password")
1730
+ User.find_by_token_for(:password_reset, token) # => nil
1099
1731
  ```
1100
1732
 
1101
- *Eileen M. Uchitelle*, *Aaron Patterson*, *Lee Quarella*
1733
+ *Jonathan Hefner*
1102
1734
 
1103
- * Add setting for enumerating column names in SELECT statements.
1735
+ * Optimize Active Record batching for whole table iterations.
1104
1736
 
1105
- Adding a column to a PostgreSQL database, for example, while the application is running can
1106
- change the result of wildcard `SELECT *` queries, which invalidates the result
1107
- of cached prepared statements and raises a `PreparedStatementCacheExpired` error.
1737
+ Previously, `in_batches` got all the ids and constructed an `IN`-based query for each batch.
1738
+ When iterating over the whole tables, this approach is not optimal as it loads unneeded ids and
1739
+ `IN` queries with lots of items are slow.
1108
1740
 
1109
- When enabled, Active Record will avoid wildcards and always include column names
1110
- in `SELECT` queries, which will return consistent results and avoid prepared
1111
- statement errors.
1741
+ Now, whole table iterations use range iteration (`id >= x AND id <= y`) by default which can make iteration
1742
+ several times faster. E.g., tested on a PostgreSQL table with 10 million records: querying (`253s` vs `30s`),
1743
+ updating (`288s` vs `124s`), deleting (`268s` vs `83s`).
1112
1744
 
1113
- Before:
1745
+ Only whole table iterations use this style of iteration by default. You can disable this behavior by passing `use_ranges: false`.
1746
+ If you iterate over the table and the only condition is, e.g., `archived_at: nil` (and only a tiny fraction
1747
+ of the records are archived), it makes sense to opt in to this approach:
1114
1748
 
1115
1749
  ```ruby
1116
- Book.limit(5)
1117
- # SELECT * FROM books LIMIT 5
1750
+ Project.where(archived_at: nil).in_batches(use_ranges: true) do |relation|
1751
+ # do something
1752
+ end
1118
1753
  ```
1119
1754
 
1120
- After:
1755
+ See #45414 for more details.
1121
1756
 
1122
- ```ruby
1123
- # config/application.rb
1124
- module MyApp
1125
- class Application < Rails::Application
1126
- config.active_record.enumerate_columns_in_select_statements = true
1127
- end
1128
- end
1757
+ *fatkodima*
1129
1758
 
1130
- # or, configure per-model
1131
- class Book < ApplicationRecord
1132
- self.enumerate_columns_in_select_statements = true
1133
- end
1134
- ```
1759
+ * `.with` query method added. Construct common table expressions with ease and get `ActiveRecord::Relation` back.
1135
1760
 
1136
1761
  ```ruby
1137
- Book.limit(5)
1138
- # SELECT id, author_id, name, format, status, language, etc FROM books LIMIT 5
1762
+ Post.with(posts_with_comments: Post.where("comments_count > ?", 0))
1763
+ # => ActiveRecord::Relation
1764
+ # WITH posts_with_comments AS (SELECT * FROM posts WHERE (comments_count > 0)) SELECT * FROM posts
1139
1765
  ```
1140
1766
 
1141
- *Matt Duszynski*
1767
+ *Vlado Cingel*
1142
1768
 
1143
- * Allow passing SQL as `on_duplicate` value to `#upsert_all` to make it possible to use raw SQL to update columns on conflict:
1769
+ * Don't establish a new connection if an identical pool exists already.
1144
1770
 
1145
- ```ruby
1146
- Book.upsert_all(
1147
- [{ id: 1, status: 1 }, { id: 2, status: 1 }],
1148
- on_duplicate: Arel.sql("status = GREATEST(books.status, EXCLUDED.status)")
1149
- )
1150
- ```
1771
+ Previously, if `establish_connection` was called on a class that already had an established connection, the existing connection would be removed regardless of whether it was the same config. Now if a pool is found with the same values as the new connection, the existing connection will be returned instead of creating a new one.
1151
1772
 
1152
- *Vladimir Dementyev*
1773
+ This has a slight change in behavior if application code is depending on a new connection being established regardless of whether it's identical to an existing connection. If the old behavior is desirable, applications should call `ActiveRecord::Base#remove_connection` before establishing a new one. Calling `establish_connection` with a different config works the same way as it did previously.
1774
+
1775
+ *Eileen M. Uchitelle*
1153
1776
 
1154
- * Allow passing SQL as `returning` statement to `#upsert_all`:
1777
+ * Update `db:prepare` task to load schema when an uninitialized database exists, and dump schema after migrations.
1778
+
1779
+ *Ben Sheldon*
1780
+
1781
+ * Fix supporting timezone awareness for `tsrange` and `tstzrange` array columns.
1155
1782
 
1156
1783
  ```ruby
1157
- Article.insert_all(
1158
- [
1159
- { title: "Article 1", slug: "article-1", published: false },
1160
- { title: "Article 2", slug: "article-2", published: false }
1161
- ],
1162
- returning: Arel.sql("id, (xmax = '0') as inserted, name as new_name")
1163
- )
1784
+ # In database migrations
1785
+ add_column :shops, :open_hours, :tsrange, array: true
1786
+ # In app config
1787
+ ActiveRecord::Base.time_zone_aware_types += [:tsrange]
1788
+ # In the code times are properly converted to app time zone
1789
+ Shop.create!(open_hours: [Time.current..8.hour.from_now])
1164
1790
  ```
1165
1791
 
1166
- *Vladimir Dementyev*
1792
+ *Wojciech Wnętrzak*
1167
1793
 
1168
- * Deprecate `legacy_connection_handling`.
1794
+ * Introduce strategy pattern for executing migrations.
1169
1795
 
1170
- *Eileen M. Uchitelle*
1796
+ By default, migrations will use a strategy object that delegates the method
1797
+ to the connection adapter. Consumers can implement custom strategy objects
1798
+ to change how their migrations run.
1171
1799
 
1172
- * Add attribute encryption support.
1800
+ *Adrianna Chang*
1173
1801
 
1174
- Encrypted attributes are declared at the model level. These
1175
- are regular Active Record attributes backed by a column with
1176
- the same name. The system will transparently encrypt these
1177
- attributes before saving them into the database and will
1178
- decrypt them when retrieving their values.
1802
+ * Add adapter option disallowing foreign keys
1179
1803
 
1804
+ This adds a new option to be added to `database.yml` which enables skipping
1805
+ foreign key constraints usage even if the underlying database supports them.
1180
1806
 
1181
- ```ruby
1182
- class Person < ApplicationRecord
1183
- encrypts :name
1184
- encrypts :email_address, deterministic: true
1185
- end
1807
+ Usage:
1808
+ ```yaml
1809
+ development:
1810
+ <<: *default
1811
+ database: storage/development.sqlite3
1812
+ foreign_keys: false
1186
1813
  ```
1187
1814
 
1188
- You can learn more in the [Active Record Encryption
1189
- guide](https://edgeguides.rubyonrails.org/active_record_encryption.html).
1815
+ *Paulo Barros*
1190
1816
 
1191
- *Jorge Manrubia*
1817
+ * Add configurable deprecation warning for singular associations
1192
1818
 
1193
- * Changed Arel predications `contains` and `overlaps` to use
1194
- `quoted_node` so that PostgreSQL arrays are quoted properly.
1819
+ This adds a deprecation warning when using the plural name of a singular associations in `where`.
1820
+ It is possible to opt into the new more performant behavior with `config.active_record.allow_deprecated_singular_associations_name = false`
1195
1821
 
1196
- *Bradley Priest*
1822
+ *Adam Hess*
1197
1823
 
1198
- * Add mode argument to record level `strict_loading!`.
1824
+ * Run transactional callbacks on the freshest instance to save a given
1825
+ record within a transaction.
1199
1826
 
1200
- This argument can be used when enabling strict loading for a single record
1201
- to specify that we only want to raise on n plus one queries.
1827
+ When multiple Active Record instances change the same record within a
1828
+ transaction, Rails runs `after_commit` or `after_rollback` callbacks for
1829
+ only one of them. `config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction`
1830
+ was added to specify how Rails chooses which instance receives the
1831
+ callbacks. The framework defaults were changed to use the new logic.
1202
1832
 
1203
- ```ruby
1204
- developer.strict_loading!(mode: :n_plus_one_only)
1833
+ When `config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction`
1834
+ is `true`, transactional callbacks are run on the first instance to save,
1835
+ even though its instance state may be stale.
1205
1836
 
1206
- developer.projects.to_a # Does not raise
1207
- developer.projects.first.client # Raises StrictLoadingViolationError
1208
- ```
1837
+ When it is `false`, which is the new framework default starting with version
1838
+ 7.1, transactional callbacks are run on the instances with the freshest
1839
+ instance state. Those instances are chosen as follows:
1209
1840
 
1210
- Previously, enabling strict loading would cause any lazily loaded
1211
- association to raise an error. Using `n_plus_one_only` mode allows us to
1212
- lazily load belongs_to, has_many, and other associations that are fetched
1213
- through a single query.
1841
+ - In general, run transactional callbacks on the last instance to save a
1842
+ given record within the transaction.
1843
+ - There are two exceptions:
1844
+ - If the record is created within the transaction, then updated by
1845
+ another instance, `after_create_commit` callbacks will be run on the
1846
+ second instance. This is instead of the `after_update_commit`
1847
+ callbacks that would naively be run based on that instance’s state.
1848
+ - If the record is destroyed within the transaction, then
1849
+ `after_destroy_commit` callbacks will be fired on the last destroyed
1850
+ instance, even if a stale instance subsequently performed an update
1851
+ (which will have affected 0 rows).
1214
1852
 
1215
- *Dinah Shi*
1853
+ *Cameron Bothner and Mitch Vollebregt*
1216
1854
 
1217
- * Fix Float::INFINITY assignment to datetime column with postgresql adapter.
1855
+ * Enable strict strings mode for `SQLite3Adapter`.
1218
1856
 
1219
- Before:
1857
+ Configures SQLite with a strict strings mode, which disables double-quoted string literals.
1220
1858
 
1221
- ```ruby
1222
- # With this config
1223
- ActiveRecord::Base.time_zone_aware_attributes = true
1859
+ SQLite has some quirks around double-quoted string literals.
1860
+ It first tries to consider double-quoted strings as identifier names, but if they don't exist
1861
+ it then considers them as string literals. Because of this, typos can silently go unnoticed.
1862
+ For example, it is possible to create an index for a non existing column.
1863
+ See [SQLite documentation](https://www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted) for more details.
1224
1864
 
1225
- # and the following schema:
1226
- create_table "postgresql_infinities" do |t|
1227
- t.datetime "datetime"
1228
- end
1865
+ If you don't want this behavior, you can disable it via:
1229
1866
 
1230
- # This test fails
1231
- record = PostgresqlInfinity.create!(datetime: Float::INFINITY)
1232
- assert_equal Float::INFINITY, record.datetime # record.datetime gets nil
1867
+ ```ruby
1868
+ # config/application.rb
1869
+ config.active_record.sqlite3_adapter_strict_strings_by_default = false
1233
1870
  ```
1234
1871
 
1235
- After this commit, `record.datetime` gets `Float::INFINITY` as expected.
1872
+ Fixes #27782.
1873
+
1874
+ *fatkodima*, *Jean Boussier*
1236
1875
 
1237
- *Shunichi Ikegami*
1876
+ * Resolve issue where a relation cache_version could be left stale.
1238
1877
 
1239
- * Type cast enum values by the original attribute type.
1878
+ Previously, when `reset` was called on a relation object it did not reset the cache_versions
1879
+ ivar. This led to a confusing situation where despite having the correct data the relation
1880
+ still reported a stale cache_version.
1240
1881
 
1241
- The notable thing about this change is that unknown labels will no longer match 0 on MySQL.
1882
+ Usage:
1242
1883
 
1243
1884
  ```ruby
1244
- class Book < ActiveRecord::Base
1245
- enum :status, { proposed: 0, written: 1, published: 2 }
1246
- end
1247
- ```
1885
+ developers = Developer.all
1886
+ developers.cache_version
1248
1887
 
1249
- Before:
1888
+ Developer.update_all(updated_at: Time.now.utc + 1.second)
1250
1889
 
1251
- ```ruby
1252
- # SELECT `books`.* FROM `books` WHERE `books`.`status` = 'prohibited' LIMIT 1
1253
- Book.find_by(status: :prohibited)
1254
- # => #<Book id: 1, status: "proposed", ...> (for mysql2 adapter)
1255
- # => ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for type integer: "prohibited" (for postgresql adapter)
1256
- # => nil (for sqlite3 adapter)
1890
+ developers.cache_version # Stale cache_version
1891
+ developers.reset
1892
+ developers.cache_version # Returns the current correct cache_version
1257
1893
  ```
1258
1894
 
1259
- After:
1895
+ Fixes #45341.
1896
+
1897
+ *Austen Madden*
1898
+
1899
+ * Add support for exclusion constraints (PostgreSQL-only).
1260
1900
 
1261
1901
  ```ruby
1262
- # SELECT `books`.* FROM `books` WHERE `books`.`status` IS NULL LIMIT 1
1263
- Book.find_by(status: :prohibited)
1264
- # => nil (for all adapters)
1902
+ add_exclusion_constraint :invoices, "daterange(start_date, end_date) WITH &&", using: :gist, name: "invoices_date_overlap"
1903
+ remove_exclusion_constraint :invoices, name: "invoices_date_overlap"
1265
1904
  ```
1266
1905
 
1267
- *Ryuta Kamizono*
1906
+ See PostgreSQL's [`CREATE TABLE ... EXCLUDE ...`](https://www.postgresql.org/docs/12/sql-createtable.html#SQL-CREATETABLE-EXCLUDE) documentation for more on exclusion constraints.
1268
1907
 
1269
- * Fixtures for `has_many :through` associations now load timestamps on join tables.
1908
+ *Alex Robbin*
1270
1909
 
1271
- Given this fixture:
1910
+ * `change_column_null` raises if a non-boolean argument is provided
1272
1911
 
1273
- ```yml
1274
- ### monkeys.yml
1275
- george:
1276
- name: George the Monkey
1277
- fruits: apple
1912
+ Previously if you provided a non-boolean argument, `change_column_null` would
1913
+ treat it as truthy and make your column nullable. This could be surprising, so now
1914
+ the input must be either `true` or `false`.
1278
1915
 
1279
- ### fruits.yml
1280
- apple:
1281
- name: apple
1916
+ ```ruby
1917
+ change_column_null :table, :column, true # good
1918
+ change_column_null :table, :column, false # good
1919
+ change_column_null :table, :column, from: true, to: false # raises (previously this made the column nullable)
1282
1920
  ```
1283
1921
 
1284
- If the join table (`fruit_monkeys`) contains `created_at` or `updated_at` columns,
1285
- these will now be populated when loading the fixture. Previously, fixture loading
1286
- would crash if these columns were required, and leave them as null otherwise.
1287
-
1288
1922
  *Alex Ghiculescu*
1289
1923
 
1290
- * Allow applications to configure the thread pool for async queries.
1924
+ * Enforce limit on table names length.
1291
1925
 
1292
- Some applications may want one thread pool per database whereas others want to use
1293
- a single global thread pool for all queries. By default, Rails will set `async_query_executor`
1294
- to `nil` which will not initialize any executor. If `load_async` is called and no executor
1295
- has been configured, the query will be executed in the foreground.
1926
+ Fixes #45130.
1296
1927
 
1297
- To create one thread pool for all database connections to use applications can set
1298
- `config.active_record.async_query_executor` to `:global_thread_pool` and optionally define
1299
- `config.active_record.global_executor_concurrency`. This defaults to 4. For applications that want
1300
- to have a thread pool for each database connection, `config.active_record.async_query_executor` can
1301
- be set to `:multi_thread_pool`. The configuration for each thread pool is set in the database
1302
- configuration.
1928
+ *fatkodima*
1303
1929
 
1304
- *Eileen M. Uchitelle*
1930
+ * Adjust the minimum MariaDB version for check constraints support.
1305
1931
 
1306
- * Allow new syntax for `enum` to avoid leading `_` from reserved options.
1932
+ *Eddie Lebow*
1307
1933
 
1308
- Before:
1934
+ * Fix Hstore deserialize regression.
1309
1935
 
1310
- ```ruby
1311
- class Book < ActiveRecord::Base
1312
- enum status: [ :proposed, :written ], _prefix: true, _scopes: false
1313
- enum cover: [ :hard, :soft ], _suffix: true, _default: :hard
1314
- end
1315
- ```
1936
+ *edsharp*
1316
1937
 
1317
- After:
1938
+ * Add validity for PostgreSQL indexes.
1318
1939
 
1319
1940
  ```ruby
1320
- class Book < ActiveRecord::Base
1321
- enum :status, [ :proposed, :written ], prefix: true, scopes: false
1322
- enum :cover, [ :hard, :soft ], suffix: true, default: :hard
1323
- end
1941
+ connection.index_exists?(:users, :email, valid: true)
1942
+ connection.indexes(:users).select(&:valid?)
1324
1943
  ```
1325
1944
 
1326
- *Ryuta Kamizono*
1945
+ *fatkodima*
1327
1946
 
1328
- * Add `ActiveRecord::Relation#load_async`.
1947
+ * Fix eager loading for models without primary keys.
1329
1948
 
1330
- This method schedules the query to be performed asynchronously from a thread pool.
1949
+ *Anmol Chopra*, *Matt Lawrence*, and *Jonathan Hefner*
1331
1950
 
1332
- If the result is accessed before a background thread had the opportunity to perform
1333
- the query, it will be performed in the foreground.
1951
+ * Avoid validating a unique field if it has not changed and is backed by a unique index.
1334
1952
 
1335
- This is useful for queries that can be performed long enough before their result will be
1336
- needed, or for controllers which need to perform several independent queries.
1953
+ Previously, when saving a record, Active Record will perform an extra query to check for the
1954
+ uniqueness of each attribute having a `uniqueness` validation, even if that attribute hasn't changed.
1955
+ If the database has the corresponding unique index, then this validation can never fail for persisted
1956
+ records, and we could safely skip it.
1337
1957
 
1338
- ```ruby
1339
- def index
1340
- @categories = Category.some_complex_scope.load_async
1341
- @posts = Post.some_complex_scope.load_async
1342
- end
1343
- ```
1958
+ *fatkodima*
1344
1959
 
1345
- Active Record logs will also include timing info for the duration of how long
1346
- the main thread had to wait to access the result. This timing is useful to know
1347
- whether or not it's worth to load the query asynchronously.
1960
+ * Stop setting `sql_auto_is_null`
1348
1961
 
1349
- ```
1350
- DEBUG -- : Category Load (62.1ms) SELECT * FROM `categories` LIMIT 50
1351
- DEBUG -- : ASYNC Post Load (64ms) (db time 126.1ms) SELECT * FROM `posts` LIMIT 100
1352
- ```
1962
+ Since version 5.5 the default has been off, we no longer have to manually turn it off.
1353
1963
 
1354
- The duration in the first set of parens is how long the main thread was blocked
1355
- waiting for the results, and the second set of parens with "db time" is how long
1356
- the entire query took to execute.
1964
+ *Adam Hess*
1357
1965
 
1358
- *Jean Boussier*
1966
+ * Fix `touch` to raise an error for readonly columns.
1359
1967
 
1360
- * Implemented `ActiveRecord::Relation#excluding` method.
1968
+ *fatkodima*
1361
1969
 
1362
- This method excludes the specified record (or collection of records) from
1363
- the resulting relation:
1970
+ * Add ability to ignore tables by regexp for SQL schema dumps.
1364
1971
 
1365
1972
  ```ruby
1366
- Post.excluding(post)
1367
- Post.excluding(post_one, post_two)
1973
+ ActiveRecord::SchemaDumper.ignore_tables = [/^_/]
1368
1974
  ```
1369
1975
 
1370
- Also works on associations:
1371
-
1372
- ```ruby
1373
- post.comments.excluding(comment)
1374
- post.comments.excluding(comment_one, comment_two)
1375
- ```
1976
+ *fatkodima*
1376
1977
 
1377
- This is short-hand for `Post.where.not(id: post.id)` (for a single record)
1378
- and `Post.where.not(id: [post_one.id, post_two.id])` (for a collection).
1978
+ * Avoid queries when performing calculations on contradictory relations.
1379
1979
 
1380
- *Glen Crawford*
1980
+ Previously calculations would make a query even when passed a
1981
+ contradiction, such as `User.where(id: []).count`. We no longer perform a
1982
+ query in that scenario.
1381
1983
 
1382
- * Skip optimised #exist? query when #include? is called on a relation
1383
- with a having clause.
1984
+ This applies to the following calculations: `count`, `sum`, `average`,
1985
+ `minimum` and `maximum`
1384
1986
 
1385
- Relations that have aliased select values AND a having clause that
1386
- references an aliased select value would generate an error when
1387
- #include? was called, due to an optimisation that would generate
1388
- call #exists? on the relation instead, which effectively alters
1389
- the select values of the query (and thus removes the aliased select
1390
- values), but leaves the having clause intact. Because the having
1391
- clause is then referencing an aliased column that is no longer
1392
- present in the simplified query, an ActiveRecord::InvalidStatement
1393
- error was raised.
1987
+ *Luan Vieira, John Hawthorn and Daniel Colson*
1394
1988
 
1395
- A sample query affected by this problem:
1989
+ * Allow using aliased attributes with `insert_all`/`upsert_all`.
1396
1990
 
1397
1991
  ```ruby
1398
- Author.select('COUNT(*) as total_posts', 'authors.*')
1399
- .joins(:posts)
1400
- .group(:id)
1401
- .having('total_posts > 2')
1402
- .include?(Author.first)
1992
+ class Book < ApplicationRecord
1993
+ alias_attribute :title, :name
1994
+ end
1995
+
1996
+ Book.insert_all [{ title: "Remote", author_id: 1 }], returning: :title
1403
1997
  ```
1404
1998
 
1405
- This change adds an addition check to the condition that skips the
1406
- simplified #exists? query, which simply checks for the presence of
1407
- a having clause.
1999
+ *fatkodima*
1408
2000
 
1409
- Fixes #41417.
2001
+ * Support encrypted attributes on columns with default db values.
1410
2002
 
1411
- *Michael Smart*
2003
+ This adds support for encrypted attributes defined on columns with default values.
2004
+ It will encrypt those values at creation time. Before, it would raise an
2005
+ error unless `config.active_record.encryption.support_unencrypted_data` was true.
1412
2006
 
1413
- * Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
1414
- without Rails knowledge (e.g., if app gets killed during long-running query or due to Rack::Timeout), app won't end
1415
- up in perpetual crash state for being inconsistent with PostgreSQL.
2007
+ *Jorge Manrubia* and *Dima Fatko*
1416
2008
 
1417
- *wbharding*, *Martin Tepper*
2009
+ * Allow overriding `reading_request?` in `DatabaseSelector::Resolver`
1418
2010
 
1419
- * Add ability to apply `scoping` to `all_queries`.
2011
+ The default implementation checks if a request is a `get?` or `head?`,
2012
+ but you can now change it to anything you like. If the method returns true,
2013
+ `Resolver#read` gets called meaning the request could be served by the
2014
+ replica database.
1420
2015
 
1421
- Some applications may want to use the `scoping` method but previously it only
1422
- worked on certain types of queries. This change allows the `scoping` method to apply
1423
- to all queries for a model in a block.
2016
+ *Alex Ghiculescu*
1424
2017
 
1425
- ```ruby
1426
- Post.where(blog_id: post.blog_id).scoping(all_queries: true) do
1427
- post.update(title: "a post title") # adds `posts.blog_id = 1` to the query
1428
- end
1429
- ```
2018
+ * Remove `ActiveRecord.legacy_connection_handling`.
1430
2019
 
1431
2020
  *Eileen M. Uchitelle*
1432
2021
 
1433
- * `ActiveRecord::Calculations.calculate` called with `:average`
1434
- (aliased as `ActiveRecord::Calculations.average`) will now use column-based
1435
- type casting. This means that floating-point number columns will now be
1436
- aggregated as `Float` and decimal columns will be aggregated as `BigDecimal`.
2022
+ * `rails db:schema:{dump,load}` now checks `ENV["SCHEMA_FORMAT"]` before config
1437
2023
 
1438
- Integers are handled as a special case returning `BigDecimal` always
1439
- (this was the case before already).
2024
+ Since `rails db:structure:{dump,load}` was deprecated there wasn't a simple
2025
+ way to dump a schema to both SQL and Ruby formats. You can now do this with
2026
+ an environment variable. For example:
1440
2027
 
1441
- ```ruby
1442
- # With the following schema:
1443
- create_table "measurements" do |t|
1444
- t.float "temperature"
1445
- end
2028
+ ```
2029
+ SCHEMA_FORMAT=sql rake db:schema:dump
2030
+ ```
1446
2031
 
1447
- # Before:
1448
- Measurement.average(:temperature).class
1449
- # => BigDecimal
2032
+ *Alex Ghiculescu*
1450
2033
 
1451
- # After:
1452
- Measurement.average(:temperature).class
1453
- # => Float
1454
- ```
2034
+ * Fixed MariaDB default function support.
1455
2035
 
1456
- Before this change, Rails just called `to_d` on average aggregates from the
1457
- database adapter. This is not the case anymore. If you relied on that kind
1458
- of magic, you now need to register your own `ActiveRecord::Type`
1459
- (see `ActiveRecord::Attributes::ClassMethods` for documentation).
2036
+ Defaults would be written wrong in "db/schema.rb" and not work correctly
2037
+ if using `db:schema:load`. Further more the function name would be
2038
+ added as string content when saving new records.
1460
2039
 
1461
- *Josua Schmid*
2040
+ *kaspernj*
1462
2041
 
1463
- * PostgreSQL: introduce `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type`.
2042
+ * Add `active_record.destroy_association_async_batch_size` configuration
1464
2043
 
1465
- This setting controls what native type Active Record should use when you call `datetime` in
1466
- a migration or schema. It takes a symbol which must correspond to one of the configured
1467
- `NATIVE_DATABASE_TYPES`. The default is `:timestamp`, meaning `t.datetime` in a migration
1468
- will create a "timestamp without time zone" column. To use "timestamp with time zone",
1469
- change this to `:timestamptz` in an initializer.
2044
+ This allows applications to specify the maximum number of records that will
2045
+ be destroyed in a single background job by the `dependent: :destroy_async`
2046
+ association option. By default, the current behavior will remain the same:
2047
+ when a parent record is destroyed, all dependent records will be destroyed
2048
+ in a single background job. If the number of dependent records is greater
2049
+ than this configuration, the records will be destroyed in multiple
2050
+ background jobs.
1470
2051
 
1471
- You should run `bin/rails db:migrate` to rebuild your schema.rb if you change this.
2052
+ *Nick Holden*
1472
2053
 
1473
- *Alex Ghiculescu*
2054
+ * Fix `remove_foreign_key` with `:if_exists` option when foreign key actually exists.
2055
+
2056
+ *fatkodima*
2057
+
2058
+ * Remove `--no-comments` flag in structure dumps for PostgreSQL
1474
2059
 
1475
- * PostgreSQL: handle `timestamp with time zone` columns correctly in `schema.rb`.
2060
+ This broke some apps that used custom schema comments. If you don't want
2061
+ comments in your structure dump, you can use:
1476
2062
 
1477
- Previously they dumped as `t.datetime :column_name`, now they dump as `t.timestamptz :column_name`,
1478
- and are created as `timestamptz` columns when the schema is loaded.
2063
+ ```ruby
2064
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-comments']
2065
+ ```
1479
2066
 
1480
2067
  *Alex Ghiculescu*
1481
2068
 
1482
- * Removing trailing whitespace when matching columns in
1483
- `ActiveRecord::Sanitization.disallow_raw_sql!`.
2069
+ * Reduce the memory footprint of fixtures accessors.
1484
2070
 
1485
- *Gannon McGibbon*, *Adrian Hirt*
2071
+ Until now fixtures accessors were eagerly defined using `define_method`.
2072
+ So the memory usage was directly dependent of the number of fixtures and
2073
+ test suites.
1486
2074
 
1487
- * Expose a way for applications to set a `primary_abstract_class`.
2075
+ Instead fixtures accessors are now implemented with `method_missing`,
2076
+ so they incur much less memory and CPU overhead.
1488
2077
 
1489
- Multiple database applications that use a primary abstract class that is not
1490
- named `ApplicationRecord` can now set a specific class to be the `primary_abstract_class`.
2078
+ *Jean Boussier*
1491
2079
 
1492
- ```ruby
1493
- class PrimaryApplicationRecord
1494
- self.primary_abstract_class
1495
- end
1496
- ```
2080
+ * Fix `config.active_record.destroy_association_async_job` configuration
1497
2081
 
1498
- When an application boots it automatically connects to the primary or first database in the
1499
- database configuration file. In a multiple database application that then call `connects_to`
1500
- needs to know that the default connection is the same as the `ApplicationRecord` connection.
1501
- However, some applications have a differently named `ApplicationRecord`. This prevents Active
1502
- Record from opening duplicate connections to the same database.
2082
+ `config.active_record.destroy_association_async_job` should allow
2083
+ applications to specify the job that will be used to destroy associated
2084
+ records in the background for `has_many` associations with the
2085
+ `dependent: :destroy_async` option. Previously, that was ignored, which
2086
+ meant the default `ActiveRecord::DestroyAssociationAsyncJob` always
2087
+ destroyed records in the background.
1503
2088
 
1504
- *Eileen M. Uchitelle*, *John Crepezzi*
2089
+ *Nick Holden*
1505
2090
 
1506
- * Support hash config for `structure_dump_flags` and `structure_load_flags` flags.
1507
- Now that Active Record supports multiple databases configuration,
1508
- we need a way to pass specific flags for dump/load databases since
1509
- the options are not the same for different adapters.
1510
- We can use in the original way:
2091
+ * Fix `change_column_comment` to preserve column's AUTO_INCREMENT in the MySQL adapter
1511
2092
 
1512
- ```ruby
1513
- ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-defaults', '--skip-add-drop-table']
1514
- # or
1515
- ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table'
1516
- ```
2093
+ *fatkodima*
1517
2094
 
1518
- And also use it passing a hash, with one or more keys, where the key
1519
- is the adapter
2095
+ * Fix quoting of `ActiveSupport::Duration` and `Rational` numbers in the MySQL adapter.
1520
2096
 
1521
- ```ruby
1522
- ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = {
1523
- mysql2: ['--no-defaults', '--skip-add-drop-table'],
1524
- postgres: '--no-tablespaces'
1525
- }
1526
- ```
2097
+ *Kevin McPhillips*
1527
2098
 
1528
- *Gustavo Gonzalez*
2099
+ * Allow column name with COLLATE (e.g., title COLLATE "C") as safe SQL string
1529
2100
 
1530
- * Connection specification now passes the "url" key as a configuration for the
1531
- adapter if the "url" protocol is "jdbc", "http", or "https". Previously only
1532
- urls with the "jdbc" prefix were passed to the Active Record Adapter, others
1533
- are assumed to be adapter specification urls.
2101
+ *Shugo Maeda*
1534
2102
 
1535
- Fixes #41137.
2103
+ * Permit underscores in the VERSION argument to database rake tasks.
1536
2104
 
1537
- *Jonathan Bracy*
2105
+ *Eddie Lebow*
1538
2106
 
1539
- * Allow to opt-out of `strict_loading` mode on a per-record base.
2107
+ * Reversed the order of `INSERT` statements in `structure.sql` dumps
1540
2108
 
1541
- This is useful when strict loading is enabled application wide or on a
1542
- model level.
2109
+ This should decrease the likelihood of merge conflicts. New migrations
2110
+ will now be added at the top of the list.
1543
2111
 
1544
- ```ruby
1545
- class User < ApplicationRecord
1546
- has_many :bookmarks
1547
- has_many :articles, strict_loading: true
1548
- end
2112
+ For existing apps, there will be a large diff the next time `structure.sql`
2113
+ is generated.
1549
2114
 
1550
- user = User.first
1551
- user.articles # => ActiveRecord::StrictLoadingViolationError
1552
- user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy>
2115
+ *Alex Ghiculescu*, *Matt Larraz*
1553
2116
 
1554
- user.strict_loading!(true) # => true
1555
- user.bookmarks # => ActiveRecord::StrictLoadingViolationError
2117
+ * Fix PG.connect keyword arguments deprecation warning on ruby 2.7
1556
2118
 
1557
- user.strict_loading!(false) # => false
1558
- user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy>
1559
- user.articles.strict_loading!(false) # => #<ActiveRecord::Associations::CollectionProxy>
1560
- ```
2119
+ Fixes #44307.
1561
2120
 
1562
- *Ayrton De Craene*
2121
+ *Nikita Vasilevsky*
1563
2122
 
1564
- * Add `FinderMethods#sole` and `#find_sole_by` to find and assert the
1565
- presence of exactly one record.
2123
+ * Fix dropping DB connections after serialization failures and deadlocks.
1566
2124
 
1567
- Used when you need a single row, but also want to assert that there aren't
1568
- multiple rows matching the condition; especially for when database
1569
- constraints aren't enough or are impractical.
2125
+ Prior to 6.1.4, serialization failures and deadlocks caused rollbacks to be
2126
+ issued for both real transactions and savepoints. This breaks MySQL which
2127
+ disallows rollbacks of savepoints following a deadlock.
1570
2128
 
1571
- ```ruby
1572
- Product.where(["price = %?", price]).sole
1573
- # => ActiveRecord::RecordNotFound (if no Product with given price)
1574
- # => #<Product ...> (if one Product with given price)
1575
- # => ActiveRecord::SoleRecordExceeded (if more than one Product with given price)
2129
+ 6.1.4 removed these rollbacks, for both transactions and savepoints, causing
2130
+ the DB connection to be left in an unknown state and thus discarded.
1576
2131
 
1577
- user.api_keys.find_sole_by(key: key)
1578
- # as above
1579
- ```
2132
+ These rollbacks are now restored, except for savepoints on MySQL.
1580
2133
 
1581
- *Asherah Connor*
2134
+ *Thomas Morgan*
1582
2135
 
1583
- * Makes `ActiveRecord::AttributeMethods::Query` respect the getter overrides defined in the model.
2136
+ * Make `ActiveRecord::ConnectionPool` Fiber-safe
1584
2137
 
1585
- Before:
2138
+ When `ActiveSupport::IsolatedExecutionState.isolation_level` is set to `:fiber`,
2139
+ the connection pool now supports multiple Fibers from the same Thread checking
2140
+ out connections from the pool.
2141
+
2142
+ *Alex Matchneer*
2143
+
2144
+ * Add `update_attribute!` to `ActiveRecord::Persistence`
2145
+
2146
+ Similar to `update_attribute`, but raises `ActiveRecord::RecordNotSaved` when a `before_*` callback throws `:abort`.
1586
2147
 
1587
2148
  ```ruby
1588
- class User
1589
- def admin
1590
- false # Overriding the getter to always return false
2149
+ class Topic < ActiveRecord::Base
2150
+ before_save :check_title
2151
+
2152
+ def check_title
2153
+ throw(:abort) if title == "abort"
1591
2154
  end
1592
2155
  end
1593
2156
 
1594
- user = User.first
1595
- user.update(admin: true)
1596
-
1597
- user.admin # false (as expected, due to the getter overwrite)
1598
- user.admin? # true (not expected, returned the DB column value)
2157
+ topic = Topic.create(title: "Test Title")
2158
+ # #=> #<Topic title: "Test Title">
2159
+ topic.update_attribute!(:title, "Another Title")
2160
+ # #=> #<Topic title: "Another Title">
2161
+ topic.update_attribute!(:title, "abort")
2162
+ # raises ActiveRecord::RecordNotSaved
1599
2163
  ```
1600
2164
 
1601
- After this commit, `user.admin?` above returns false, as expected.
2165
+ *Drew Tempelmeyer*
1602
2166
 
1603
- Fixes #40771.
2167
+ * Avoid loading every record in `ActiveRecord::Relation#pretty_print`
1604
2168
 
1605
- *Felipe*
2169
+ ```ruby
2170
+ # Before
2171
+ pp Foo.all # Loads the whole table.
1606
2172
 
1607
- * Allow delegated_type to be specified primary_key and foreign_key.
2173
+ # After
2174
+ pp Foo.all # Shows 10 items and an ellipsis.
2175
+ ```
1608
2176
 
1609
- Since delegated_type assumes that the foreign_key ends with `_id`,
1610
- `singular_id` defined by it does not work when the foreign_key does
1611
- not end with `id`. This change fixes it by taking into account
1612
- `primary_key` and `foreign_key` in the options.
2177
+ *Ulysse Buonomo*
1613
2178
 
1614
- *Ryota Egusa*
2179
+ * Change `QueryMethods#in_order_of` to drop records not listed in values.
1615
2180
 
1616
- * Expose an `invert_where` method that will invert all scope conditions.
2181
+ `in_order_of` now filters down to the values provided, to match the behavior of the `Enumerable` version.
1617
2182
 
1618
- ```ruby
1619
- class User
1620
- scope :active, -> { where(accepted: true, locked: false) }
1621
- end
2183
+ *Kevin Newton*
1622
2184
 
1623
- User.active
1624
- # ... WHERE `accepted` = 1 AND `locked` = 0
2185
+ * Allow named expression indexes to be revertible.
1625
2186
 
1626
- User.active.invert_where
1627
- # ... WHERE NOT (`accepted` = 1 AND `locked` = 0)
2187
+ Previously, the following code would raise an error in a reversible migration executed while rolling back, due to the index name not being used in the index removal.
2188
+
2189
+ ```ruby
2190
+ add_index(:settings, "(data->'property')", using: :gin, name: :index_settings_data_property)
1628
2191
  ```
1629
2192
 
1630
- *Kevin Deisz*
2193
+ Fixes #43331.
1631
2194
 
1632
- * Restore possibility of passing `false` to :polymorphic option of `belongs_to`.
2195
+ *Oliver Günther*
1633
2196
 
1634
- Previously, passing `false` would trigger the option validation logic
1635
- to throw an error saying :polymorphic would not be a valid option.
2197
+ * Fix incorrect argument in PostgreSQL structure dump tasks.
1636
2198
 
1637
- *glaszig*
2199
+ Updating the `--no-comment` argument added in Rails 7 to the correct `--no-comments` argument.
1638
2200
 
1639
- * Remove deprecated `database` kwarg from `connected_to`.
2201
+ *Alex Dent*
1640
2202
 
1641
- *Eileen M. Uchitelle*, *John Crepezzi*
2203
+ * Fix migration compatibility to create SQLite references/belongs_to column as integer when migration version is 6.0.
1642
2204
 
1643
- * Allow adding nonnamed expression indexes to be revertible.
2205
+ Reference/belongs_to in migrations with version 6.0 were creating columns as
2206
+ bigint instead of integer for the SQLite Adapter.
1644
2207
 
1645
- Previously, the following code would raise an error, when executed while rolling back,
1646
- and the index name should be specified explicitly. Now, the index name is inferred
1647
- automatically.
2208
+ *Marcelo Lauxen*
2209
+
2210
+ * Fix `QueryMethods#in_order_of` to handle empty order list.
1648
2211
 
1649
2212
  ```ruby
1650
- add_index(:items, "to_tsvector('english', description)")
2213
+ Post.in_order_of(:id, []).to_a
1651
2214
  ```
1652
2215
 
1653
- Fixes #40732.
1654
-
1655
- *fatkodima*
1656
-
1657
- * Only warn about negative enums if a positive form that would cause conflicts exists.
1658
-
1659
- Fixes #39065.
1660
-
1661
- *Alex Ghiculescu*
2216
+ Also more explicitly set the column as secondary order, so that any other
2217
+ value is still ordered.
1662
2218
 
1663
- * Add option to run `default_scope` on all queries.
2219
+ *Jean Boussier*
1664
2220
 
1665
- Previously, a `default_scope` would only run on select or insert queries. In some cases, like non-Rails tenant sharding solutions, it may be desirable to run `default_scope` on all queries in order to ensure queries are including a foreign key for the shard (i.e. `blog_id`).
2221
+ * Fix quoting of column aliases generated by calculation methods.
1666
2222
 
1667
- Now applications can add an option to run on all queries including select, insert, delete, and update by adding an `all_queries` option to the default scope definition.
2223
+ Since the alias is derived from the table name, we can't assume the result
2224
+ is a valid identifier.
1668
2225
 
1669
2226
  ```ruby
1670
- class Article < ApplicationRecord
1671
- default_scope -> { where(blog_id: Current.blog.id) }, all_queries: true
2227
+ class Test < ActiveRecord::Base
2228
+ self.table_name = '1abc'
1672
2229
  end
2230
+ Test.group(:id).count
2231
+ # syntax error at or near "1" (ActiveRecord::StatementInvalid)
2232
+ # LINE 1: SELECT COUNT(*) AS count_all, "1abc"."id" AS 1abc_id FROM "1...
1673
2233
  ```
1674
2234
 
1675
- *Eileen M. Uchitelle*
2235
+ *Jean Boussier*
1676
2236
 
1677
- * Add `where.associated` to check for the presence of an association.
2237
+ * Add `authenticate_by` when using `has_secure_password`.
1678
2238
 
1679
- ```ruby
1680
- # Before:
1681
- account.users.joins(:contact).where.not(contact_id: nil)
2239
+ `authenticate_by` is intended to replace code like the following, which
2240
+ returns early when a user with a matching email is not found:
1682
2241
 
1683
- # After:
1684
- account.users.where.associated(:contact)
2242
+ ```ruby
2243
+ User.find_by(email: "...")&.authenticate("...")
1685
2244
  ```
1686
2245
 
1687
- Also mirrors `where.missing`.
2246
+ Such code is vulnerable to timing-based enumeration attacks, wherein an
2247
+ attacker can determine if a user account with a given email exists. After
2248
+ confirming that an account exists, the attacker can try passwords associated
2249
+ with that email address from other leaked databases, in case the user
2250
+ re-used a password across multiple sites (a common practice). Additionally,
2251
+ knowing an account email address allows the attacker to attempt a targeted
2252
+ phishing ("spear phishing") attack.
1688
2253
 
1689
- *Kasper Timm Hansen*
2254
+ `authenticate_by` addresses the vulnerability by taking the same amount of
2255
+ time regardless of whether a user with a matching email is found:
1690
2256
 
1691
- * Allow constructors (`build_association` and `create_association`) on
1692
- `has_one :through` associations.
2257
+ ```ruby
2258
+ User.authenticate_by(email: "...", password: "...")
2259
+ ```
1693
2260
 
1694
- *Santiago Perez Perret*
2261
+ *Jonathan Hefner*
1695
2262
 
1696
2263
 
1697
- Please check [6-1-stable](https://github.com/rails/rails/blob/6-1-stable/activerecord/CHANGELOG.md) for previous changes.
2264
+ Please check [7-0-stable](https://github.com/rails/rails/blob/7-0-stable/activerecord/CHANGELOG.md) for previous changes.