activerecord 6.1.3.2 → 7.0.0.alpha2

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

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