activerecord 6.1.7.4 → 7.0.8

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