activerecord 5.2.8 → 7.0.2

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 (364) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +1393 -587
  3. data/MIT-LICENSE +3 -1
  4. data/README.rdoc +7 -5
  5. data/examples/performance.rb +1 -1
  6. data/lib/active_record/aggregations.rb +10 -9
  7. data/lib/active_record/association_relation.rb +22 -12
  8. data/lib/active_record/associations/alias_tracker.rb +19 -16
  9. data/lib/active_record/associations/association.rb +122 -47
  10. data/lib/active_record/associations/association_scope.rb +24 -24
  11. data/lib/active_record/associations/belongs_to_association.rb +67 -49
  12. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +16 -7
  13. data/lib/active_record/associations/builder/association.rb +52 -23
  14. data/lib/active_record/associations/builder/belongs_to.rb +44 -61
  15. data/lib/active_record/associations/builder/collection_association.rb +17 -19
  16. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +17 -41
  17. data/lib/active_record/associations/builder/has_many.rb +10 -3
  18. data/lib/active_record/associations/builder/has_one.rb +35 -3
  19. data/lib/active_record/associations/builder/singular_association.rb +5 -3
  20. data/lib/active_record/associations/collection_association.rb +59 -50
  21. data/lib/active_record/associations/collection_proxy.rb +32 -23
  22. data/lib/active_record/associations/disable_joins_association_scope.rb +59 -0
  23. data/lib/active_record/associations/foreign_association.rb +20 -0
  24. data/lib/active_record/associations/has_many_association.rb +27 -14
  25. data/lib/active_record/associations/has_many_through_association.rb +26 -19
  26. data/lib/active_record/associations/has_one_association.rb +52 -37
  27. data/lib/active_record/associations/has_one_through_association.rb +6 -6
  28. data/lib/active_record/associations/join_dependency/join_association.rb +44 -22
  29. data/lib/active_record/associations/join_dependency/join_part.rb +5 -5
  30. data/lib/active_record/associations/join_dependency.rb +97 -62
  31. data/lib/active_record/associations/preloader/association.rb +220 -60
  32. data/lib/active_record/associations/preloader/batch.rb +48 -0
  33. data/lib/active_record/associations/preloader/branch.rb +147 -0
  34. data/lib/active_record/associations/preloader/through_association.rb +85 -40
  35. data/lib/active_record/associations/preloader.rb +44 -105
  36. data/lib/active_record/associations/singular_association.rb +9 -17
  37. data/lib/active_record/associations/through_association.rb +4 -4
  38. data/lib/active_record/associations.rb +207 -66
  39. data/lib/active_record/asynchronous_queries_tracker.rb +60 -0
  40. data/lib/active_record/attribute_assignment.rb +17 -19
  41. data/lib/active_record/attribute_methods/before_type_cast.rb +19 -8
  42. data/lib/active_record/attribute_methods/dirty.rb +141 -47
  43. data/lib/active_record/attribute_methods/primary_key.rb +22 -27
  44. data/lib/active_record/attribute_methods/query.rb +6 -10
  45. data/lib/active_record/attribute_methods/read.rb +15 -55
  46. data/lib/active_record/attribute_methods/serialization.rb +77 -18
  47. data/lib/active_record/attribute_methods/time_zone_conversion.rb +16 -18
  48. data/lib/active_record/attribute_methods/write.rb +18 -37
  49. data/lib/active_record/attribute_methods.rb +90 -153
  50. data/lib/active_record/attributes.rb +38 -12
  51. data/lib/active_record/autosave_association.rb +50 -50
  52. data/lib/active_record/base.rb +23 -18
  53. data/lib/active_record/callbacks.rb +159 -44
  54. data/lib/active_record/coders/yaml_column.rb +12 -3
  55. data/lib/active_record/connection_adapters/abstract/connection_handler.rb +292 -0
  56. data/lib/active_record/connection_adapters/abstract/connection_pool/queue.rb +209 -0
  57. data/lib/active_record/connection_adapters/abstract/connection_pool/reaper.rb +76 -0
  58. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +92 -464
  59. data/lib/active_record/connection_adapters/abstract/database_limits.rb +5 -51
  60. data/lib/active_record/connection_adapters/abstract/database_statements.rb +209 -164
  61. data/lib/active_record/connection_adapters/abstract/query_cache.rb +38 -22
  62. data/lib/active_record/connection_adapters/abstract/quoting.rb +103 -82
  63. data/lib/active_record/connection_adapters/abstract/savepoints.rb +3 -3
  64. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +140 -110
  65. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +236 -94
  66. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +16 -5
  67. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +456 -159
  68. data/lib/active_record/connection_adapters/abstract/transaction.rb +169 -78
  69. data/lib/active_record/connection_adapters/abstract_adapter.rb +367 -162
  70. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +311 -327
  71. data/lib/active_record/connection_adapters/column.rb +33 -11
  72. data/lib/active_record/connection_adapters/deduplicable.rb +29 -0
  73. data/lib/active_record/connection_adapters/legacy_pool_manager.rb +35 -0
  74. data/lib/active_record/connection_adapters/mysql/column.rb +1 -1
  75. data/lib/active_record/connection_adapters/mysql/database_statements.rb +113 -45
  76. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +1 -2
  77. data/lib/active_record/connection_adapters/mysql/quoting.rb +71 -5
  78. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +34 -10
  79. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +48 -32
  80. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +25 -8
  81. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +143 -19
  82. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +14 -9
  83. data/lib/active_record/connection_adapters/mysql2_adapter.rb +63 -22
  84. data/lib/active_record/connection_adapters/pool_config.rb +73 -0
  85. data/lib/active_record/connection_adapters/pool_manager.rb +47 -0
  86. data/lib/active_record/connection_adapters/postgresql/column.rb +53 -28
  87. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +56 -63
  88. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +1 -2
  89. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +1 -4
  90. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +3 -5
  91. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +10 -2
  92. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +15 -2
  93. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +0 -1
  94. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +54 -16
  95. data/lib/active_record/connection_adapters/postgresql/oid/interval.rb +49 -0
  96. data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +3 -4
  97. data/lib/active_record/connection_adapters/postgresql/oid/macaddr.rb +25 -0
  98. data/lib/active_record/connection_adapters/postgresql/oid/oid.rb +1 -1
  99. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +3 -4
  100. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +25 -7
  101. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +1 -1
  102. data/lib/active_record/connection_adapters/postgresql/oid/timestamp.rb +15 -0
  103. data/lib/active_record/connection_adapters/postgresql/oid/timestamp_with_time_zone.rb +30 -0
  104. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +26 -12
  105. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +15 -3
  106. data/lib/active_record/connection_adapters/postgresql/oid.rb +4 -0
  107. data/lib/active_record/connection_adapters/postgresql/quoting.rb +89 -52
  108. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +34 -2
  109. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +39 -4
  110. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +128 -91
  111. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +25 -1
  112. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +149 -113
  113. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +31 -26
  114. data/lib/active_record/connection_adapters/postgresql/utils.rb +0 -1
  115. data/lib/active_record/connection_adapters/postgresql_adapter.rb +386 -182
  116. data/lib/active_record/connection_adapters/schema_cache.rb +161 -22
  117. data/lib/active_record/connection_adapters/sql_type_metadata.rb +17 -6
  118. data/lib/active_record/connection_adapters/sqlite3/database_statements.rb +152 -0
  119. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +65 -18
  120. data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +5 -1
  121. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +92 -26
  122. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +251 -204
  123. data/lib/active_record/connection_adapters/statement_pool.rb +0 -1
  124. data/lib/active_record/connection_adapters.rb +53 -0
  125. data/lib/active_record/connection_handling.rb +292 -38
  126. data/lib/active_record/core.rb +385 -158
  127. data/lib/active_record/counter_cache.rb +8 -30
  128. data/lib/active_record/database_configurations/connection_url_resolver.rb +100 -0
  129. data/lib/active_record/database_configurations/database_config.rb +83 -0
  130. data/lib/active_record/database_configurations/hash_config.rb +154 -0
  131. data/lib/active_record/database_configurations/url_config.rb +53 -0
  132. data/lib/active_record/database_configurations.rb +256 -0
  133. data/lib/active_record/delegated_type.rb +250 -0
  134. data/lib/active_record/destroy_association_async_job.rb +36 -0
  135. data/lib/active_record/disable_joins_association_relation.rb +39 -0
  136. data/lib/active_record/dynamic_matchers.rb +4 -5
  137. data/lib/active_record/encryption/cipher/aes256_gcm.rb +98 -0
  138. data/lib/active_record/encryption/cipher.rb +53 -0
  139. data/lib/active_record/encryption/config.rb +44 -0
  140. data/lib/active_record/encryption/configurable.rb +61 -0
  141. data/lib/active_record/encryption/context.rb +35 -0
  142. data/lib/active_record/encryption/contexts.rb +72 -0
  143. data/lib/active_record/encryption/derived_secret_key_provider.rb +12 -0
  144. data/lib/active_record/encryption/deterministic_key_provider.rb +14 -0
  145. data/lib/active_record/encryption/encryptable_record.rb +208 -0
  146. data/lib/active_record/encryption/encrypted_attribute_type.rb +140 -0
  147. data/lib/active_record/encryption/encrypted_fixtures.rb +38 -0
  148. data/lib/active_record/encryption/encrypting_only_encryptor.rb +12 -0
  149. data/lib/active_record/encryption/encryptor.rb +155 -0
  150. data/lib/active_record/encryption/envelope_encryption_key_provider.rb +55 -0
  151. data/lib/active_record/encryption/errors.rb +15 -0
  152. data/lib/active_record/encryption/extended_deterministic_queries.rb +160 -0
  153. data/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb +28 -0
  154. data/lib/active_record/encryption/key.rb +28 -0
  155. data/lib/active_record/encryption/key_generator.rb +42 -0
  156. data/lib/active_record/encryption/key_provider.rb +46 -0
  157. data/lib/active_record/encryption/message.rb +33 -0
  158. data/lib/active_record/encryption/message_serializer.rb +90 -0
  159. data/lib/active_record/encryption/null_encryptor.rb +21 -0
  160. data/lib/active_record/encryption/properties.rb +76 -0
  161. data/lib/active_record/encryption/read_only_null_encryptor.rb +24 -0
  162. data/lib/active_record/encryption/scheme.rb +99 -0
  163. data/lib/active_record/encryption.rb +55 -0
  164. data/lib/active_record/enum.rb +130 -51
  165. data/lib/active_record/errors.rb +129 -23
  166. data/lib/active_record/explain.rb +10 -6
  167. data/lib/active_record/explain_registry.rb +11 -6
  168. data/lib/active_record/explain_subscriber.rb +1 -1
  169. data/lib/active_record/fixture_set/file.rb +22 -15
  170. data/lib/active_record/fixture_set/model_metadata.rb +32 -0
  171. data/lib/active_record/fixture_set/render_context.rb +17 -0
  172. data/lib/active_record/fixture_set/table_row.rb +187 -0
  173. data/lib/active_record/fixture_set/table_rows.rb +46 -0
  174. data/lib/active_record/fixtures.rb +206 -490
  175. data/lib/active_record/future_result.rb +139 -0
  176. data/lib/active_record/gem_version.rb +3 -3
  177. data/lib/active_record/inheritance.rb +104 -37
  178. data/lib/active_record/insert_all.rb +278 -0
  179. data/lib/active_record/integration.rb +69 -18
  180. data/lib/active_record/internal_metadata.rb +24 -9
  181. data/lib/active_record/legacy_yaml_adapter.rb +3 -36
  182. data/lib/active_record/locking/optimistic.rb +41 -26
  183. data/lib/active_record/locking/pessimistic.rb +18 -8
  184. data/lib/active_record/log_subscriber.rb +46 -35
  185. data/lib/active_record/middleware/database_selector/resolver/session.rb +48 -0
  186. data/lib/active_record/middleware/database_selector/resolver.rb +88 -0
  187. data/lib/active_record/middleware/database_selector.rb +82 -0
  188. data/lib/active_record/middleware/shard_selector.rb +60 -0
  189. data/lib/active_record/migration/command_recorder.rb +96 -44
  190. data/lib/active_record/migration/compatibility.rb +246 -64
  191. data/lib/active_record/migration/join_table.rb +1 -2
  192. data/lib/active_record/migration.rb +266 -187
  193. data/lib/active_record/model_schema.rb +165 -52
  194. data/lib/active_record/nested_attributes.rb +17 -19
  195. data/lib/active_record/no_touching.rb +11 -4
  196. data/lib/active_record/null_relation.rb +2 -7
  197. data/lib/active_record/persistence.rb +467 -92
  198. data/lib/active_record/query_cache.rb +21 -4
  199. data/lib/active_record/query_logs.rb +138 -0
  200. data/lib/active_record/querying.rb +51 -24
  201. data/lib/active_record/railtie.rb +224 -57
  202. data/lib/active_record/railties/console_sandbox.rb +2 -4
  203. data/lib/active_record/railties/controller_runtime.rb +31 -36
  204. data/lib/active_record/railties/databases.rake +369 -101
  205. data/lib/active_record/readonly_attributes.rb +15 -0
  206. data/lib/active_record/reflection.rb +170 -137
  207. data/lib/active_record/relation/batches/batch_enumerator.rb +44 -14
  208. data/lib/active_record/relation/batches.rb +46 -37
  209. data/lib/active_record/relation/calculations.rb +168 -96
  210. data/lib/active_record/relation/delegation.rb +37 -52
  211. data/lib/active_record/relation/finder_methods.rb +79 -58
  212. data/lib/active_record/relation/from_clause.rb +5 -1
  213. data/lib/active_record/relation/merger.rb +50 -51
  214. data/lib/active_record/relation/predicate_builder/array_handler.rb +13 -13
  215. data/lib/active_record/relation/predicate_builder/association_query_value.rb +5 -9
  216. data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +1 -2
  217. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +11 -10
  218. data/lib/active_record/relation/predicate_builder/range_handler.rb +3 -23
  219. data/lib/active_record/relation/predicate_builder/relation_handler.rb +1 -1
  220. data/lib/active_record/relation/predicate_builder.rb +58 -46
  221. data/lib/active_record/relation/query_attribute.rb +9 -10
  222. data/lib/active_record/relation/query_methods.rb +685 -208
  223. data/lib/active_record/relation/record_fetch_warning.rb +9 -11
  224. data/lib/active_record/relation/spawn_methods.rb +10 -10
  225. data/lib/active_record/relation/where_clause.rb +108 -64
  226. data/lib/active_record/relation.rb +515 -151
  227. data/lib/active_record/result.rb +78 -42
  228. data/lib/active_record/runtime_registry.rb +9 -13
  229. data/lib/active_record/sanitization.rb +29 -44
  230. data/lib/active_record/schema.rb +37 -31
  231. data/lib/active_record/schema_dumper.rb +74 -23
  232. data/lib/active_record/schema_migration.rb +7 -9
  233. data/lib/active_record/scoping/default.rb +62 -17
  234. data/lib/active_record/scoping/named.rb +17 -32
  235. data/lib/active_record/scoping.rb +70 -41
  236. data/lib/active_record/secure_token.rb +16 -8
  237. data/lib/active_record/serialization.rb +6 -4
  238. data/lib/active_record/signed_id.rb +116 -0
  239. data/lib/active_record/statement_cache.rb +49 -6
  240. data/lib/active_record/store.rb +88 -9
  241. data/lib/active_record/suppressor.rb +13 -17
  242. data/lib/active_record/table_metadata.rb +42 -43
  243. data/lib/active_record/tasks/database_tasks.rb +352 -94
  244. data/lib/active_record/tasks/mysql_database_tasks.rb +37 -39
  245. data/lib/active_record/tasks/postgresql_database_tasks.rb +41 -39
  246. data/lib/active_record/tasks/sqlite_database_tasks.rb +14 -17
  247. data/lib/active_record/test_databases.rb +24 -0
  248. data/lib/active_record/test_fixtures.rb +287 -0
  249. data/lib/active_record/timestamp.rb +44 -34
  250. data/lib/active_record/touch_later.rb +23 -22
  251. data/lib/active_record/transactions.rb +67 -128
  252. data/lib/active_record/translation.rb +3 -3
  253. data/lib/active_record/type/adapter_specific_registry.rb +34 -19
  254. data/lib/active_record/type/hash_lookup_type_map.rb +34 -2
  255. data/lib/active_record/type/internal/timezone.rb +2 -2
  256. data/lib/active_record/type/serialized.rb +7 -4
  257. data/lib/active_record/type/time.rb +10 -0
  258. data/lib/active_record/type/type_map.rb +17 -21
  259. data/lib/active_record/type/unsigned_integer.rb +0 -1
  260. data/lib/active_record/type.rb +9 -5
  261. data/lib/active_record/type_caster/connection.rb +15 -15
  262. data/lib/active_record/type_caster/map.rb +8 -8
  263. data/lib/active_record/validations/associated.rb +2 -3
  264. data/lib/active_record/validations/numericality.rb +35 -0
  265. data/lib/active_record/validations/uniqueness.rb +39 -31
  266. data/lib/active_record/validations.rb +4 -3
  267. data/lib/active_record.rb +209 -32
  268. data/lib/arel/alias_predication.rb +9 -0
  269. data/lib/arel/attributes/attribute.rb +33 -0
  270. data/lib/arel/collectors/bind.rb +29 -0
  271. data/lib/arel/collectors/composite.rb +39 -0
  272. data/lib/arel/collectors/plain_string.rb +20 -0
  273. data/lib/arel/collectors/sql_string.rb +27 -0
  274. data/lib/arel/collectors/substitute_binds.rb +35 -0
  275. data/lib/arel/crud.rb +48 -0
  276. data/lib/arel/delete_manager.rb +32 -0
  277. data/lib/arel/errors.rb +9 -0
  278. data/lib/arel/expressions.rb +29 -0
  279. data/lib/arel/factory_methods.rb +49 -0
  280. data/lib/arel/filter_predications.rb +9 -0
  281. data/lib/arel/insert_manager.rb +48 -0
  282. data/lib/arel/math.rb +45 -0
  283. data/lib/arel/nodes/and.rb +32 -0
  284. data/lib/arel/nodes/ascending.rb +23 -0
  285. data/lib/arel/nodes/binary.rb +126 -0
  286. data/lib/arel/nodes/bind_param.rb +44 -0
  287. data/lib/arel/nodes/case.rb +55 -0
  288. data/lib/arel/nodes/casted.rb +62 -0
  289. data/lib/arel/nodes/comment.rb +29 -0
  290. data/lib/arel/nodes/count.rb +12 -0
  291. data/lib/arel/nodes/delete_statement.rb +44 -0
  292. data/lib/arel/nodes/descending.rb +23 -0
  293. data/lib/arel/nodes/equality.rb +15 -0
  294. data/lib/arel/nodes/extract.rb +24 -0
  295. data/lib/arel/nodes/false.rb +16 -0
  296. data/lib/arel/nodes/filter.rb +10 -0
  297. data/lib/arel/nodes/full_outer_join.rb +8 -0
  298. data/lib/arel/nodes/function.rb +45 -0
  299. data/lib/arel/nodes/grouping.rb +11 -0
  300. data/lib/arel/nodes/homogeneous_in.rb +76 -0
  301. data/lib/arel/nodes/in.rb +15 -0
  302. data/lib/arel/nodes/infix_operation.rb +92 -0
  303. data/lib/arel/nodes/inner_join.rb +8 -0
  304. data/lib/arel/nodes/insert_statement.rb +37 -0
  305. data/lib/arel/nodes/join_source.rb +20 -0
  306. data/lib/arel/nodes/matches.rb +18 -0
  307. data/lib/arel/nodes/named_function.rb +23 -0
  308. data/lib/arel/nodes/node.rb +51 -0
  309. data/lib/arel/nodes/node_expression.rb +13 -0
  310. data/lib/arel/nodes/ordering.rb +27 -0
  311. data/lib/arel/nodes/outer_join.rb +8 -0
  312. data/lib/arel/nodes/over.rb +15 -0
  313. data/lib/arel/nodes/regexp.rb +16 -0
  314. data/lib/arel/nodes/right_outer_join.rb +8 -0
  315. data/lib/arel/nodes/select_core.rb +67 -0
  316. data/lib/arel/nodes/select_statement.rb +41 -0
  317. data/lib/arel/nodes/sql_literal.rb +19 -0
  318. data/lib/arel/nodes/string_join.rb +11 -0
  319. data/lib/arel/nodes/table_alias.rb +31 -0
  320. data/lib/arel/nodes/terminal.rb +16 -0
  321. data/lib/arel/nodes/true.rb +16 -0
  322. data/lib/arel/nodes/unary.rb +44 -0
  323. data/lib/arel/nodes/unary_operation.rb +20 -0
  324. data/lib/arel/nodes/unqualified_column.rb +22 -0
  325. data/lib/arel/nodes/update_statement.rb +46 -0
  326. data/lib/arel/nodes/values_list.rb +9 -0
  327. data/lib/arel/nodes/window.rb +126 -0
  328. data/lib/arel/nodes/with.rb +11 -0
  329. data/lib/arel/nodes.rb +71 -0
  330. data/lib/arel/order_predications.rb +13 -0
  331. data/lib/arel/predications.rb +258 -0
  332. data/lib/arel/select_manager.rb +276 -0
  333. data/lib/arel/table.rb +117 -0
  334. data/lib/arel/tree_manager.rb +60 -0
  335. data/lib/arel/update_manager.rb +48 -0
  336. data/lib/arel/visitors/dot.rb +298 -0
  337. data/lib/arel/visitors/mysql.rb +99 -0
  338. data/lib/arel/visitors/postgresql.rb +110 -0
  339. data/lib/arel/visitors/sqlite.rb +38 -0
  340. data/lib/arel/visitors/to_sql.rb +955 -0
  341. data/lib/arel/visitors/visitor.rb +45 -0
  342. data/lib/arel/visitors.rb +13 -0
  343. data/lib/arel/window_predications.rb +9 -0
  344. data/lib/arel.rb +55 -0
  345. data/lib/rails/generators/active_record/application_record/application_record_generator.rb +0 -1
  346. data/lib/rails/generators/active_record/application_record/templates/application_record.rb.tt +1 -1
  347. data/lib/rails/generators/active_record/migration/migration_generator.rb +3 -5
  348. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +3 -1
  349. data/lib/rails/generators/active_record/migration/templates/migration.rb.tt +7 -5
  350. data/lib/rails/generators/active_record/migration.rb +19 -2
  351. data/lib/rails/generators/active_record/model/model_generator.rb +39 -2
  352. data/lib/rails/generators/active_record/model/templates/abstract_base_class.rb.tt +7 -0
  353. data/lib/rails/generators/active_record/model/templates/model.rb.tt +10 -1
  354. data/lib/rails/generators/active_record/model/templates/module.rb.tt +2 -2
  355. data/lib/rails/generators/active_record/multi_db/multi_db_generator.rb +16 -0
  356. data/lib/rails/generators/active_record/multi_db/templates/multi_db.rb.tt +44 -0
  357. metadata +162 -32
  358. data/lib/active_record/attribute_decorators.rb +0 -90
  359. data/lib/active_record/collection_cache_key.rb +0 -53
  360. data/lib/active_record/connection_adapters/connection_specification.rb +0 -287
  361. data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +0 -33
  362. data/lib/active_record/define_callbacks.rb +0 -22
  363. data/lib/active_record/relation/predicate_builder/base_handler.rb +0 -19
  364. data/lib/active_record/relation/where_clause_factory.rb +0 -34
data/CHANGELOG.md CHANGED
@@ -1,1056 +1,1862 @@
1
- ## Rails 5.2.8 (May 09, 2022) ##
1
+ ## Rails 7.0.2 (February 08, 2022) ##
2
2
 
3
- * No changes.
3
+ * Fix `PG.connect` keyword arguments deprecation warning on ruby 2.7.
4
4
 
5
+ *Nikita Vasilevsky*
5
6
 
6
- ## Rails 5.2.7.1 (April 26, 2022) ##
7
+ * Fix the ability to exclude encryption params from being autofiltered.
7
8
 
8
- * No changes.
9
+ *Mark Gangl*
9
10
 
11
+ * Dump the precision for datetime columns following the new defaults.
10
12
 
11
- ## Rails 5.2.7 (March 10, 2022) ##
13
+ *Rafael Mendonça França*
12
14
 
13
- * No changes.
15
+ * Make sure encrypted attributes are not being filtered twice.
14
16
 
17
+ *Nikita Vasilevsky*
15
18
 
16
- ## Rails 5.2.6.3 (March 08, 2022) ##
19
+ * Dump the database schema containing the current Rails version.
17
20
 
18
- * No changes.
21
+ Since https://github.com/rails/rails/pull/42297, Rails now generate datetime columns
22
+ with a default precision of 6. This means that users upgrading to Rails 7.0 from 6.1,
23
+ when loading the database schema, would get the new precision value, which would not match
24
+ the production schema.
19
25
 
26
+ To avoid this the schema dumper will generate the new format which will include the Rails
27
+ version and will look like this:
20
28
 
21
- ## Rails 5.2.6.2 (February 11, 2022) ##
29
+ ```
30
+ ActiveRecord::Schema[7.0].define
31
+ ```
22
32
 
23
- * No changes.
33
+ When upgrading from Rails 6.1 to Rails 7.0, you can run the `rails app:update` task that will
34
+ set the current schema version to 6.1.
24
35
 
36
+ *Rafael Mendonça França*
25
37
 
26
- ## Rails 5.2.6.1 (February 11, 2022) ##
38
+ * Fix parsing expression for PostgreSQL generated column.
27
39
 
28
- * No changes.
40
+ *fatkodima*
29
41
 
42
+ * Fix `Mysql2::Error: Commands out of sync; you can't run this command now`
43
+ when bulk-inserting fixtures that exceed `max_allowed_packet` configuration.
30
44
 
31
- ## Rails 5.2.6 (May 05, 2021) ##
45
+ *Nikita Vasilevsky*
32
46
 
33
- * No changes.
47
+ * Fix error when saving an association with a relation named `record`.
34
48
 
49
+ *Dorian Marié*
35
50
 
36
- ## Rails 5.2.5 (March 26, 2021) ##
51
+ * Fix `MySQL::SchemaDumper` behavior about datetime precision value.
37
52
 
38
- * No changes.
53
+ *y0t4*
39
54
 
55
+ * Improve associated with no reflection error.
40
56
 
41
- ## Rails 5.2.4.6 (May 05, 2021) ##
57
+ *Nikolai*
42
58
 
43
- * No changes.
59
+ * Fix PG.connect keyword arguments deprecation warning on ruby 2.7.
44
60
 
61
+ Fixes #44307.
45
62
 
46
- ## Rails 5.2.4.5 (February 10, 2021) ##
63
+ *Nikita Vasilevsky*
47
64
 
48
- * Fix possible DoS vector in PostgreSQL money type
65
+ * Fix passing options to `check_constraint` from `change_table`.
49
66
 
50
- Carefully crafted input can cause a DoS via the regular expressions used
51
- for validating the money format in the PostgreSQL adapter. This patch
52
- fixes the regexp.
67
+ *Frederick Cheung*
53
68
 
54
- Thanks to @dee-see from Hackerone for this patch!
55
69
 
56
- [CVE-2021-22880]
70
+ ## Rails 7.0.1 (January 06, 2022) ##
57
71
 
58
- *Aaron Patterson*
59
72
 
73
+ * Change `QueryMethods#in_order_of` to drop records not listed in values.
60
74
 
61
- ## Rails 5.2.4.4 (September 09, 2020) ##
75
+ `in_order_of` now filters down to the values provided, to match the behavior of the `Enumerable` version.
62
76
 
63
- * No changes.
77
+ *Kevin Newton*
64
78
 
79
+ * Allow named expression indexes to be revertible.
65
80
 
66
- ## Rails 5.2.4.3 (May 18, 2020) ##
81
+ Previously, the following code would raise an error in a reversible migration executed while rolling back, due to the index name not being used in the index removal.
67
82
 
68
- * No changes.
83
+ ```ruby
84
+ add_index(:settings, "(data->'property')", using: :gin, name: :index_settings_data_property)
85
+ ```
69
86
 
70
- ## Rails 5.2.4.2 (March 19, 2020) ##
87
+ Fixes #43331.
71
88
 
72
- * No changes.
89
+ *Oliver Günther*
73
90
 
91
+ * Better error messages when association name is invalid in the argument of `ActiveRecord::QueryMethods::WhereChain#missing`.
74
92
 
75
- ## Rails 5.2.4.1 (December 18, 2019) ##
93
+ *ykpythemind*
76
94
 
77
- * No changes.
95
+ * Fix ordered migrations for single db in multi db environment.
78
96
 
97
+ *Himanshu*
79
98
 
80
- ## Rails 5.2.4 (November 27, 2019) ##
99
+ * Extract `on update CURRENT_TIMESTAMP` for mysql2 adapter.
81
100
 
82
- * Fix circular `autosave: true` causes invalid records to be saved.
101
+ *Kazuhiro Masuda*
83
102
 
84
- Prior to the fix, when there was a circular series of `autosave: true`
85
- associations, the callback for a `has_many` association was run while
86
- another instance of the same callback on the same association hadn't
87
- finished running. When control returned to the first instance of the
88
- callback, the instance variable had changed, and subsequent associated
89
- records weren't saved correctly. Specifically, the ID field for the
90
- `belongs_to` corresponding to the `has_many` was `nil`.
103
+ * Fix incorrect argument in PostgreSQL structure dump tasks.
91
104
 
92
- Fixes #28080.
105
+ Updating the `--no-comment` argument added in Rails 7 to the correct `--no-comments` argument.
93
106
 
94
- *Larry Reid*
107
+ *Alex Dent*
95
108
 
96
- * PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
109
+ * Fix schema dumping column default SQL values for sqlite3.
97
110
 
98
- Fixes #36022.
111
+ *fatkodima*
99
112
 
100
- *Ryuta Kamizono*
113
+ * Correctly parse complex check constraint expressions for PostgreSQL.
101
114
 
102
- * Fix sqlite3 collation parsing when using decimal columns.
115
+ *fatkodima*
103
116
 
104
- *Martin R. Schuster*
117
+ * Fix `timestamptz` attributes on PostgreSQL handle blank inputs.
105
118
 
106
- * Make ActiveRecord `ConnectionPool.connections` method thread-safe.
119
+ *Alex Ghiculescu*
107
120
 
108
- Fixes #36465.
121
+ * Fix migration compatibility to create SQLite references/belongs_to column as integer when migration version is 6.0.
109
122
 
110
- *Jeff Doering*
123
+ Reference/belongs_to in migrations with version 6.0 were creating columns as
124
+ bigint instead of integer for the SQLite Adapter.
111
125
 
112
- * Assign all attributes before calling `build` to ensure the child record is visible in
113
- `before_add` and `after_add` callbacks for `has_many :through` associations.
126
+ *Marcelo Lauxen*
114
127
 
115
- Fixes #33249.
128
+ * Fix joining through a polymorphic association.
116
129
 
117
- *Ryan H. Kerr*
130
+ *Alexandre Ruban*
118
131
 
132
+ * Fix `QueryMethods#in_order_of` to handle empty order list.
119
133
 
120
- ## Rails 5.2.3 (March 27, 2019) ##
134
+ ```ruby
135
+ Post.in_order_of(:id, []).to_a
136
+ ```
121
137
 
122
- * Fix different `count` calculation when using `size` with manual `select` with DISTINCT.
138
+ Also more explicitly set the column as secondary order, so that any other
139
+ value is still ordered.
123
140
 
124
- Fixes #35214.
141
+ *Jean Boussier*
125
142
 
126
- *Juani Villarejo*
143
+ * Fix `rails dbconsole` for 3-tier config.
127
144
 
128
- * Fix prepared statements caching to be enabled even when query caching is enabled.
145
+ *Eileen M. Uchitelle*
129
146
 
130
- *Ryuta Kamizono*
147
+ * Fix quoting of column aliases generated by calculation methods.
131
148
 
132
- * Don't allow `where` with invalid value matches to nil values.
149
+ Since the alias is derived from the table name, we can't assume the result
150
+ is a valid identifier.
133
151
 
134
- Fixes #33624.
152
+ ```ruby
153
+ class Test < ActiveRecord::Base
154
+ self.table_name = '1abc'
155
+ end
156
+ Test.group(:id).count
157
+ # syntax error at or near "1" (ActiveRecord::StatementInvalid)
158
+ # LINE 1: SELECT COUNT(*) AS count_all, "1abc"."id" AS 1abc_id FROM "1...
159
+ ```
135
160
 
136
- *Ryuta Kamizono*
161
+ *Jean Boussier*
137
162
 
138
- * Restore an ability that class level `update` without giving ids.
139
163
 
140
- Fixes #34743.
164
+ ## Rails 7.0.0 (December 15, 2021) ##
141
165
 
142
- *Ryuta Kamizono*
166
+ * Better handle SQL queries with invalid encoding.
143
167
 
144
- * Fix join table column quoting with SQLite.
168
+ ```ruby
169
+ Post.create(name: "broken \xC8 UTF-8")
170
+ ```
145
171
 
146
- *Gannon McGibbon*
172
+ Would cause all adapters to fail in a non controlled way in the code
173
+ responsible to detect write queries.
147
174
 
148
- * Ensure that `delete_all` on collection proxy returns affected count.
175
+ The query is now properly passed to the database connection, which might or might
176
+ not be able to handle it, but will either succeed or failed in a more correct way.
149
177
 
150
- *Ryuta Kamizono*
178
+ *Jean Boussier*
151
179
 
152
- * Reset scope after delete on collection association to clear stale offsets of removed records.
180
+ * Move database and shard selection config options to a generator.
153
181
 
154
- *Gannon McGibbon*
182
+ Rather than generating the config options in `production.rb` when applications are created, applications can now run a generator to create an initializer and uncomment / update options as needed. All multi-db configuration can be implemented in this initializer.
183
+
184
+ *Eileen M. Uchitelle*
155
185
 
156
186
 
157
- ## Rails 5.2.2.1 (March 11, 2019) ##
187
+ ## Rails 7.0.0.rc3 (December 14, 2021) ##
158
188
 
159
189
  * No changes.
160
190
 
161
191
 
162
- ## Rails 5.2.2 (December 04, 2018) ##
192
+ ## Rails 7.0.0.rc2 (December 14, 2021) ##
193
+
194
+ * No changes.
163
195
 
164
- * Do not ignore the scoping with query methods in the scope block.
165
196
 
166
- *Ryuta Kamizono*
197
+ ## Rails 7.0.0.rc1 (December 06, 2021) ##
167
198
 
168
- * Allow aliased attributes to be used in `#update_columns` and `#update`.
199
+ * Remove deprecated `ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name`.
169
200
 
170
- *Gannon McGibbon*
201
+ *Rafael Mendonça França*
171
202
 
172
- * Allow spaces in postgres table names.
203
+ * Remove deprecated `ActiveRecord::Connection#in_clause_length`.
173
204
 
174
- Fixes issue where "user post" is misinterpreted as "\"user\".\"post\"" when quoting table names with the postgres
175
- adapter.
205
+ *Rafael Mendonça França*
176
206
 
177
- *Gannon McGibbon*
207
+ * Remove deprecated `ActiveRecord::Connection#allowed_index_name_length`.
178
208
 
179
- * Cached columns_hash fields should be excluded from ResultSet#column_types
209
+ *Rafael Mendonça França*
180
210
 
181
- PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test
182
- was passing for SQLite and MySQL, but failed for PostgreSQL:
211
+ * Remove deprecated `ActiveRecord::Base#remove_connection`.
212
+
213
+ *Rafael Mendonça França*
214
+
215
+ * Load STI Models in fixtures
216
+
217
+ Data from Fixtures now loads based on the specific class for models with
218
+ Single Table Inheritance. This affects enums defined in subclasses, previously
219
+ the value of these fields was not parsed and remained `nil`
220
+
221
+ *Andres Howard*
222
+
223
+ * `#authenticate` returns false when the password is blank instead of raising an error.
224
+
225
+ *Muhammad Muhammad Ibrahim*
226
+
227
+ * Fix `ActiveRecord::QueryMethods#in_order_of` behavior for integer enums.
228
+
229
+ `ActiveRecord::QueryMethods#in_order_of` didn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.
230
+
231
+ The following example now works as expected:
183
232
 
184
233
  ```ruby
185
- class DeveloperName < ActiveRecord::Type::String
186
- def deserialize(value)
187
- "Developer: #{value}"
188
- end
234
+ class Book < ApplicationRecord
235
+ enum status: [:proposed, :written, :published]
189
236
  end
190
237
 
191
- class AttributedDeveloper < ActiveRecord::Base
192
- self.table_name = "developers"
238
+ Book.in_order_of(:status, %w[written published proposed])
239
+ ```
193
240
 
194
- attribute :name, DeveloperName.new
241
+ *Alexandre Ruban*
195
242
 
196
- self.ignored_columns += ["name"]
197
- end
243
+ * Ignore persisted in-memory records when merging target lists.
198
244
 
199
- developer = AttributedDeveloper.create
200
- developer.update_column :name, "name"
245
+ *Kevin Sjöberg*
201
246
 
202
- loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first
203
- puts loaded_developer.name # should be "Developer: name" but it's just "name"
247
+ * Add a new option `:update_only` to `upsert_all` to configure the list of columns to update in case of conflict.
248
+
249
+ Before, you could only customize the update SQL sentence via `:on_duplicate`. There is now a new option `:update_only` that lets you provide a list of columns to update in case of conflict:
250
+
251
+ ```ruby
252
+ Commodity.upsert_all(
253
+ [
254
+ { id: 2, name: "Copper", price: 4.84 },
255
+ { id: 4, name: "Gold", price: 1380.87 },
256
+ { id: 6, name: "Aluminium", price: 0.35 }
257
+ ],
258
+ update_only: [:price] # Only prices will be updated
259
+ )
204
260
  ```
205
261
 
206
- *Dmitry Tsepelev*
262
+ *Jorge Manrubia*
207
263
 
208
- * Values of enum are frozen, raising an error when attempting to modify them.
264
+ * Remove deprecated `ActiveRecord::Result#map!` and `ActiveRecord::Result#collect!`.
209
265
 
210
- *Emmanuel Byrd*
266
+ *Rafael Mendonça França*
211
267
 
212
- * `update_columns` now correctly raises `ActiveModel::MissingAttributeError`
213
- if the attribute does not exist.
268
+ * Remove deprecated `ActiveRecord::Base.configurations.to_h`.
214
269
 
215
- *Sean Griffin*
270
+ *Rafael Mendonça França*
216
271
 
217
- * Do not use prepared statement in queries that have a large number of binds.
272
+ * Remove deprecated `ActiveRecord::Base.configurations.default_hash`.
218
273
 
219
- *Ryuta Kamizono*
274
+ *Rafael Mendonça França*
220
275
 
221
- * Fix query cache to load before first request.
276
+ * Remove deprecated `ActiveRecord::Base.arel_attribute`.
222
277
 
223
- *Eileen M. Uchitelle*
278
+ *Rafael Mendonça França*
224
279
 
225
- * Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.
280
+ * Remove deprecated `ActiveRecord::Base.connection_config`.
226
281
 
227
- Fixes #33056.
282
+ *Rafael Mendonça França*
228
283
 
229
- *Federico Martinez*
284
+ * Filter attributes in SQL logs
230
285
 
231
- * Fix duplicated record creation when using nested attributes with `create_with`.
286
+ Previously, SQL queries in logs containing `ActiveRecord::Base.filter_attributes` were not filtered.
232
287
 
233
- *Darwin Wu*
288
+ Now, the filter attributes will be masked `[FILTERED]` in the logs when `prepared_statement` is enabled.
234
289
 
235
- * Fix regression setting children record in parent `before_save` callback.
290
+ ```
291
+ # Before:
292
+ Foo Load (0.2ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "hello"], ["LIMIT", 1]]
236
293
 
237
- *Guo Xiang Tan*
294
+ # After:
295
+ Foo Load (0.5ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "[FILTERED]"], ["LIMIT", 1]]
296
+ ```
238
297
 
239
- * Prevent leaking of user's DB credentials on `rails db:create` failure.
298
+ *Aishwarya Subramanian*
240
299
 
241
- *bogdanvlviv*
300
+ * Remove deprecated `Tasks::DatabaseTasks.spec`.
242
301
 
243
- * Clear mutation tracker before continuing the around callbacks.
302
+ *Rafael Mendonça França*
244
303
 
245
- *Yuya Tanaka*
304
+ * Remove deprecated `Tasks::DatabaseTasks.current_config`.
246
305
 
247
- * Prevent deadlocks when waiting for connection from pool.
306
+ *Rafael Mendonça França*
248
307
 
249
- *Brent Wheeldon*
308
+ * Deprecate `Tasks::DatabaseTasks.schema_file_type`.
250
309
 
251
- * Avoid extra scoping when using `Relation#update` that was causing this method to change the current scope.
310
+ *Rafael Mendonça França*
252
311
 
253
- *Ryuta Kamizono*
312
+ * Remove deprecated `Tasks::DatabaseTasks.dump_filename`.
254
313
 
255
- * Fix numericality validator not to be affected by custom getter.
314
+ *Rafael Mendonça França*
256
315
 
257
- *Ryuta Kamizono*
316
+ * Remove deprecated `Tasks::DatabaseTasks.schema_file`.
258
317
 
259
- * Fix bulk change table ignores comment option on PostgreSQL.
318
+ *Rafael Mendonça França*
260
319
 
261
- *Yoshiyuki Kinjo*
320
+ * Remove deprecated `environment` and `name` arguments from `Tasks::DatabaseTasks.schema_up_to_date?`.
262
321
 
322
+ *Rafael Mendonça França*
263
323
 
264
- ## Rails 5.2.1.1 (November 27, 2018) ##
324
+ * Merging conditions on the same column no longer maintain both conditions,
325
+ and will be consistently replaced by the latter condition.
265
326
 
266
- * No changes.
327
+ ```ruby
328
+ # Rails 6.1 (IN clause is replaced by merger side equality condition)
329
+ Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
330
+ # Rails 6.1 (both conflict conditions exists, deprecated)
331
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
332
+ # Rails 6.1 with rewhere to migrate to Rails 7.0's behavior
333
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
334
+ # Rails 7.0 (same behavior with IN clause, mergee side condition is consistently replaced)
335
+ Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
336
+ Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
267
337
 
338
+ *Rafael Mendonça França*
268
339
 
269
- ## Rails 5.2.1 (August 07, 2018) ##
340
+ * Remove deprecated support to `Model.reorder(nil).first` to search using non-deterministic order.
270
341
 
271
- * PostgreSQL: Support new relkind for partitioned tables.
342
+ *Rafael Mendonça França*
272
343
 
273
- Fixes #33008.
344
+ * Remove deprecated rake tasks:
274
345
 
275
- *Yannick Schutz*
346
+ * `db:schema:load_if_ruby`
347
+ * `db:structure:dump`
348
+ * `db:structure:load`
349
+ * `db:structure:load_if_sql`
350
+ * `db:structure:dump:#{name}`
351
+ * `db:structure:load:#{name}`
352
+ * `db:test:load_structure`
353
+ * `db:test:load_structure:#{name}`
276
354
 
277
- * Rollback parent transaction when children fails to update.
355
+ *Rafael Mendonça França*
278
356
 
279
- *Guillaume Malette*
357
+ * Remove deprecated `DatabaseConfig#config` method.
280
358
 
281
- * Fix default value for MySQL time types with specified precision.
359
+ *Rafael Mendonça França*
282
360
 
283
- *Nikolay Kondratyev*
361
+ * Rollback transactions when the block returns earlier than expected.
284
362
 
285
- * Fix `touch` option to behave consistently with `Persistence#touch` method.
363
+ Before this change, when a transaction block returned early, the transaction would be committed.
286
364
 
287
- *Ryuta Kamizono*
365
+ The problem is that timeouts triggered inside the transaction block was also making the incomplete transaction
366
+ to be committed, so in order to avoid this mistake, the transaction block is rolled back.
288
367
 
289
- * Fix `save` in `after_create_commit` won't invoke extra `after_create_commit`.
368
+ *Rafael Mendonça França*
290
369
 
291
- Fixes #32831.
370
+ * Add middleware for automatic shard swapping.
292
371
 
293
- *Ryuta Kamizono*
372
+ Provides a basic middleware to perform automatic shard swapping. Applications will provide a resolver which will determine for an individual request which shard should be used. Example:
294
373
 
295
- * Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur.
374
+ ```ruby
375
+ config.active_record.shard_resolver = ->(request) {
376
+ subdomain = request.subdomain
377
+ tenant = Tenant.find_by_subdomain!(subdomain)
378
+ tenant.shard
379
+ }
380
+ ```
296
381
 
297
- *Brian Durand*
382
+ See guides for more details.
298
383
 
299
- * Fix parent record should not get saved with duplicate children records.
384
+ *Eileen M. Uchitelle*, *John Crepezzi*
300
385
 
301
- Fixes #32940.
386
+ * Remove deprecated support to pass a column to `type_cast`.
302
387
 
303
- *Santosh Wadghule*
388
+ *Rafael Mendonça França*
304
389
 
305
- * Fix that association's after_touch is not called with counter cache.
390
+ * Remove deprecated support to type cast to database values `ActiveRecord::Base` objects.
306
391
 
307
- Fixes #31559.
392
+ *Rafael Mendonça França*
308
393
 
309
- *Ryuta Kamizono*
394
+ * Remove deprecated support to quote `ActiveRecord::Base` objects.
310
395
 
311
- * `becomes` should clear the mutation tracker which is created in `after_initialize`.
396
+ *Rafael Mendonça França*
312
397
 
313
- Fixes #32867.
398
+ * Remove deprecacated support to resolve connection using `"primary"` as connection specification name.
314
399
 
315
- *Ryuta Kamizono*
400
+ *Rafael Mendonça França*
316
401
 
317
- * Allow a belonging to parent object to be created from a new record.
402
+ * Remove deprecation warning when using `:interval` column is used in PostgreSQL database.
318
403
 
319
- *Jolyon Pawlyn*
404
+ Now, interval columns will return `ActiveSupport::Duration` objects instead of strings.
320
405
 
321
- * Fix that building record with assigning multiple has_one associations
322
- wrongly persists through record.
406
+ To keep the old behavior, you can add this line to your model:
323
407
 
324
- Fixes #32511.
408
+ ```ruby
409
+ attribute :column, :string
410
+ ```
325
411
 
326
- *Sam DeCesare*
412
+ *Rafael Mendonça França*
327
413
 
328
- * Fix relation merging when one of the relations is going to skip the
329
- query cache.
414
+ * Remove deprecated support to YAML load `ActiveRecord::Base` instance in the Rails 4.2 and 4.1 formats.
330
415
 
331
- *James Williams*
416
+ *Rafael Mendonça França*
332
417
 
418
+ * Remove deprecated option `:spec_name` in the `configs_for` method.
333
419
 
334
- ## Rails 5.2.0 (April 09, 2018) ##
420
+ *Rafael Mendonça França*
335
421
 
336
- * MySQL: Support mysql2 0.5.x.
422
+ * Remove deprecated `ActiveRecord::Base.allow_unsafe_raw_sql`.
337
423
 
338
- *Aaron Stone*
424
+ *Rafael Mendonça França*
339
425
 
340
- * Apply time column precision on assignment.
426
+ * Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations.
341
427
 
342
- PR #20317 changed the behavior of datetime columns so that when they
343
- have a specified precision then on assignment the value is rounded to
344
- that precision. This behavior is now applied to time columns as well.
428
+ Fixes #43132
345
429
 
346
- Fixes #30301.
430
+ *Alexander Pauly*
347
431
 
348
- *Andrew White*
432
+ * Fix `has_many` inversing recursion on models with recursive associations.
349
433
 
350
- * Normalize time column values for SQLite database.
434
+ *Gannon McGibbon*
351
435
 
352
- For legacy reasons, time columns in SQLite are stored as full datetimes
353
- because until #24542 the quoting for time columns didn't remove the date
354
- component. To ensure that values are consistent we now normalize the
355
- date component to 2001-01-01 on reading and writing.
436
+ * Add `accepts_nested_attributes_for` support for `delegated_type`
356
437
 
357
- *Andrew White*
438
+ ```ruby
439
+ class Entry < ApplicationRecord
440
+ delegated_type :entryable, types: %w[ Message Comment ]
441
+ accepts_nested_attributes_for :entryable
442
+ end
358
443
 
359
- * Ensure that the date component is removed when quoting times.
444
+ entry = Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
445
+ # => #<Entry:0x00>
446
+ # id: 1
447
+ # entryable_id: 1,
448
+ # entryable_type: 'Message'
449
+ # ...>
450
+
451
+ entry.entryable
452
+ # => #<Message:0x01>
453
+ # id: 1
454
+ # content: 'Hello world'
455
+ # ...>
456
+ ```
360
457
 
361
- PR #24542 altered the quoting for time columns so that the date component
362
- was removed however it only removed it when it was 2001-01-01. Now the
363
- date component is removed irrespective of what the date is.
458
+ Previously it would raise an error:
364
459
 
365
- *Andrew White*
460
+ ```ruby
461
+ Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
462
+ # ArgumentError: Cannot build association `entryable'. Are you trying to build a polymorphic one-to-one association?
463
+ ```
366
464
 
367
- * Fix `dependent: :destroy` issue for has_one/belongs_to relationship where
368
- the parent class was getting deleted when the child was not.
465
+ *Sjors Baltus*
369
466
 
370
- Fixes #32022.
467
+ * Use subquery for DELETE with GROUP_BY and HAVING clauses.
371
468
 
372
- *Fernando Gorodscy*
469
+ Prior to this change, deletes with GROUP_BY and HAVING were returning an error.
373
470
 
374
- * Whitelist `NULLS FIRST` and `NULLS LAST` in order clauses too.
471
+ After this change, GROUP_BY and HAVING are valid clauses in DELETE queries, generating the following query:
375
472
 
376
- *Xavier Noria*
473
+ ```sql
474
+ DELETE FROM "posts" WHERE "posts"."id" IN (
475
+ SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" GROUP BY "posts"."id" HAVING (count(comments.id) >= 2))
476
+ ) [["flagged", "t"]]
477
+ ```
377
478
 
378
- * Fix that after commit callbacks on update does not triggered when optimistic locking is enabled.
479
+ *Ignacio Chiazzo Cardarello*
379
480
 
380
- *Ryuta Kamizono*
481
+ * Use subquery for UPDATE with GROUP_BY and HAVING clauses.
381
482
 
382
- * Fix `#columns_for_distinct` of MySQL and PostgreSQL to make
383
- `ActiveRecord::FinderMethods#limited_ids_for` use correct primary key values
384
- even if `ORDER BY` columns include other table's primary key.
483
+ Prior to this change, updates with GROUP_BY and HAVING were being ignored, generating a SQL like this:
385
484
 
386
- Fixes #28364.
485
+ ```sql
486
+ UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
487
+ SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
488
+ ) [["flagged", "t"]]
489
+ ```
490
+
491
+ After this change, GROUP_BY and HAVING clauses are used as a subquery in updates, like this:
387
492
 
388
- *Takumi Kagiyama*
493
+ ```sql
494
+ UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
495
+ SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
496
+ GROUP BY posts.id HAVING (count(comments.id) >= 2)
497
+ ) [["flagged", "t"]]
498
+ ```
389
499
 
390
- * Make `reflection.klass` raise if `polymorphic?` not to be misused.
500
+ *Ignacio Chiazzo Cardarello*
391
501
 
392
- Fixes #31876.
502
+ * Add support for setting the filename of the schema or structure dump in the database config.
393
503
 
394
- *Ryuta Kamizono*
504
+ Applications may now set their the filename or path of the schema / structure dump file in their database configuration.
395
505
 
396
- * PostgreSQL: Allow pg-1.0 gem to be used with Active Record.
506
+ ```yaml
507
+ production:
508
+ primary:
509
+ database: my_db
510
+ schema_dump: my_schema_dump_filename.rb
511
+ animals:
512
+ database: animals_db
513
+ schema_dump: false
514
+ ```
397
515
 
398
- *Lars Kanis*
516
+ The filename set in `schema_dump` will be used by the application. If set to `false` the schema will not be dumped. The database tasks are responsible for adding the database directory to the filename. If a full path is provided, the Rails tasks will use that instead of `ActiveRecord::DatabaseTasks.db_dir`.
399
517
 
400
- * Deprecate `expand_hash_conditions_for_aggregates` without replacement.
401
- Using a `Relation` for performing queries is the prefered API.
518
+ *Eileen M. Uchitelle*, *Ryan Kerr*
402
519
 
403
- *Ryuta Kamizono*
520
+ * Add `ActiveRecord::Base.prohibit_shard_swapping` to prevent attempts to change the shard within a block.
521
+
522
+ *John Crepezzi*, *Eileen M. Uchitelle*
523
+
524
+ * Filter unchanged attributes with default function from insert query when `partial_inserts` is disabled.
525
+
526
+ *Akshay Birajdar*, *Jacopo Beschi*
527
+
528
+ * Add support for FILTER clause (SQL:2003) to Arel.
529
+
530
+ Currently supported by PostgreSQL 9.4+ and SQLite 3.30+.
531
+
532
+ *Andrey Novikov*
533
+
534
+ * Automatically set timestamps on record creation during bulk insert/upsert
535
+
536
+ Prior to this change, only updates during an upsert operation (e.g. `upsert_all`) would touch timestamps (`updated_{at,on}`). Now, record creations also touch timestamp columns (`{created,updated}_{at,on}`).
537
+
538
+ This behaviour is controlled by the `<model>.record_timestamps` config, matching the behaviour of `create`, `update`, etc. It can also be overridden by using the `record_timestamps:` keyword argument.
404
539
 
405
- * Fix not expanded problem when passing an Array object as argument to the where method using `composed_of` column.
540
+ Note that this means `upsert_all` on models with `record_timestamps = false` will no longer touch `updated_{at,on}` automatically.
406
541
 
542
+ *Sam Bostock*
543
+
544
+ * Don't require `role` when passing `shard` to `connected_to`.
545
+
546
+ `connected_to` can now be called with a `shard` only. Note that `role` is still inherited if `connected_to` calls are nested.
547
+
548
+ *Eileen M. Uchitelle*
549
+
550
+ * Add option to lazily load the schema cache on the connection.
551
+
552
+ Previously, the only way to load the schema cache in Active Record was through the Railtie on boot. This option provides the ability to load the schema cache on the connection after it's been established. Loading the cache lazily on the connection can be beneficial for Rails applications that use multiple databases because it will load the cache at the time the connection is established. Currently Railties doesn't have access to the connections before boot.
553
+
554
+ To use the cache, set `config.active_record.lazily_load_schema_cache = true` in your application configuration. In addition a `schema_cache_path` should be set in your database configuration if you don't want to use the default "db/schema_cache.yml" path.
555
+
556
+ *Eileen M. Uchitelle*
557
+
558
+ * Allow automatic `inverse_of` detection for associations with scopes.
559
+
560
+ Automatic `inverse_of` detection now works for associations with scopes. For
561
+ example, the `comments` association here now automatically detects
562
+ `inverse_of: :post`, so we don't need to pass that option:
563
+
564
+ ```ruby
565
+ class Post < ActiveRecord::Base
566
+ has_many :comments, -> { visible }
567
+ end
568
+
569
+ class Comment < ActiveRecord::Base
570
+ belongs_to :post
571
+ end
407
572
  ```
408
- david_balance = customers(:david).balance
409
- Customer.where(balance: [david_balance]).to_sql
410
573
 
411
- # Before: WHERE `customers`.`balance` = NULL
412
- # After : WHERE `customers`.`balance` = 50
574
+ Note that the automatic detection still won't work if the inverse
575
+ association has a scope. In this example a scope on the `post` association
576
+ would still prevent Rails from finding the inverse for the `comments`
577
+ association.
578
+
579
+ This will be the default for new apps in Rails 7. To opt in:
580
+
581
+ ```ruby
582
+ config.active_record.automatic_scope_inversing = true
413
583
  ```
414
584
 
415
- Fixes #31723.
585
+ *Daniel Colson*, *Chris Bloom*
416
586
 
417
- *Yutaro Kanagawa*
587
+ * Accept optional transaction args to `ActiveRecord::Locking::Pessimistic#with_lock`
418
588
 
419
- * Fix `count(:all)` with eager loading and having an order other than the driving table.
589
+ `#with_lock` now accepts transaction options like `requires_new:`,
590
+ `isolation:`, and `joinable:`
420
591
 
421
- Fixes #31783.
592
+ *John Mileham*
422
593
 
423
- *Ryuta Kamizono*
594
+ * Adds support for deferrable foreign key constraints in PostgreSQL.
424
595
 
425
- * Clear the transaction state when an Active Record object is duped.
596
+ By default, foreign key constraints in PostgreSQL are checked after each statement. This works for most use cases,
597
+ but becomes a major limitation when creating related records before the parent record is inserted into the database.
598
+ One example of this is looking up / creating a person via one or more unique alias.
426
599
 
427
- Fixes #31670.
600
+ ```ruby
601
+ Person.transaction do
602
+ alias = Alias
603
+ .create_with(user_id: SecureRandom.uuid)
604
+ .create_or_find_by(name: "DHH")
605
+
606
+ person = Person
607
+ .create_with(name: "David Heinemeier Hansson")
608
+ .create_or_find_by(id: alias.user_id)
609
+ end
610
+ ```
428
611
 
429
- *Yuriy Ustushenko*
612
+ Using the default behavior, the transaction would fail when executing the first `INSERT` statement.
430
613
 
431
- * Support for PostgreSQL foreign tables.
614
+ By passing the `:deferrable` option to the `add_foreign_key` statement in migrations, it's possible to defer this
615
+ check.
432
616
 
433
- *fatkodima*
617
+ ```ruby
618
+ add_foreign_key :aliases, :person, deferrable: true
619
+ ```
434
620
 
435
- * Fix relation merger issue with `left_outer_joins`.
621
+ Passing `deferrable: true` doesn't change the default behavior, but allows manually deferring the check using
622
+ `SET CONSTRAINTS ALL DEFERRED` within a transaction. This will cause the foreign keys to be checked after the
623
+ transaction.
436
624
 
437
- *Mehmet Emin İNAÇ*
625
+ It's also possible to adjust the default behavior from an immediate check (after the statement), to a deferred check
626
+ (after the transaction):
438
627
 
439
- * Don't allow destroyed object mutation after `save` or `save!` is called.
628
+ ```ruby
629
+ add_foreign_key :aliases, :person, deferrable: :deferred
630
+ ```
440
631
 
441
- *Ryuta Kamizono*
632
+ *Benedikt Deicke*
442
633
 
443
- * Take into account association conditions when deleting through records.
634
+ * Allow configuring Postgres password through the socket URL.
444
635
 
445
- Fixes #18424.
636
+ For example:
637
+ ```ruby
638
+ ActiveRecord::DatabaseConfigurations::UrlConfig.new(
639
+ :production, :production, 'postgres:///?user=user&password=secret&dbname=app', {}
640
+ ).configuration_hash
641
+ ```
446
642
 
447
- *Piotr Jakubowski*
643
+ will now return,
448
644
 
449
- * Fix nested `has_many :through` associations on unpersisted parent instances.
645
+ ```ruby
646
+ { :user=>"user", :password=>"secret", :dbname=>"app", :adapter=>"postgresql" }
647
+ ```
450
648
 
451
- For example, if you have
649
+ *Abeid Ahmed*
452
650
 
453
- class Post < ActiveRecord::Base
454
- belongs_to :author
455
- has_many :books, through: :author
456
- has_many :subscriptions, through: :books
457
- end
651
+ * PostgreSQL: support custom enum types
458
652
 
459
- class Author < ActiveRecord::Base
460
- has_one :post
461
- has_many :books
462
- has_many :subscriptions, through: :books
463
- end
653
+ In migrations, use `create_enum` to add a new enum type, and `t.enum` to add a column.
464
654
 
465
- class Book < ActiveRecord::Base
466
- belongs_to :author
467
- has_many :subscriptions
468
- end
655
+ ```ruby
656
+ def up
657
+ create_enum :mood, ["happy", "sad"]
469
658
 
470
- class Subscription < ActiveRecord::Base
471
- belongs_to :book
472
- end
659
+ change_table :cats do |t|
660
+ t.enum :current_mood, enum_type: "mood", default: "happy", null: false
661
+ end
662
+ end
663
+ ```
473
664
 
474
- Before:
665
+ Enums will be presented correctly in `schema.rb`. Note that this is only supported by
666
+ the PostgreSQL adapter.
475
667
 
476
- If `post` is not persisted, then `post.subscriptions` will be empty.
668
+ *Alex Ghiculescu*
477
669
 
478
- After:
670
+ * Avoid COMMENT statements in PostgreSQL structure dumps
479
671
 
480
- If `post` is not persisted, then `post.subscriptions` can be set and used
481
- just like it would if `post` were persisted.
672
+ COMMENT statements are now omitted from the output of `db:structure:dump` when using PostgreSQL >= 11.
673
+ This allows loading the dump without a pgsql superuser account.
482
674
 
483
- Fixes #16313.
675
+ Fixes #36816, #43107.
484
676
 
485
- *Zoltan Kiss*
677
+ *Janosch Müller*
486
678
 
487
- * Fixed inconsistency with `first(n)` when used with `limit()`.
488
- The `first(n)` finder now respects the `limit()`, making it consistent
489
- with `relation.to_a.first(n)`, and also with the behavior of `last(n)`.
679
+ * Add support for generated columns in PostgreSQL adapter
490
680
 
491
- Fixes #23979.
681
+ Generated columns are supported since version 12.0 of PostgreSQL. This adds
682
+ support of those to the PostgreSQL adapter.
492
683
 
493
- *Brian Christian*
684
+ ```ruby
685
+ create_table :users do |t|
686
+ t.string :name
687
+ t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true
688
+ end
689
+ ```
494
690
 
495
- * Use `count(:all)` in `HasManyAssociation#count_records` to prevent invalid
496
- SQL queries for association counting.
691
+ *Michał Begejowicz*
497
692
 
498
- *Klas Eskilson*
499
693
 
500
- * Fix to invoke callbacks when using `update_attribute`.
694
+ ## Rails 7.0.0.alpha2 (September 15, 2021) ##
501
695
 
502
- *Mike Busch*
696
+ * No changes.
503
697
 
504
- * Fix `count(:all)` to correctly work `distinct` with custom SELECT list.
505
698
 
506
- *Ryuta Kamizono*
699
+ ## Rails 7.0.0.alpha1 (September 15, 2021) ##
507
700
 
508
- * Using subselect for `delete_all` with `limit` or `offset`.
701
+ * Remove warning when overwriting existing scopes
509
702
 
510
- *Ryuta Kamizono*
703
+ Removes the following unnecessary warning message that appeared when overwriting existing scopes
511
704
 
512
- * Undefine attribute methods on descendants when resetting column
513
- information.
705
+ ```
706
+ Creating scope :my_scope_name. Overwriting existing method "MyClass.my_scope_name" when overwriting existing scopes
707
+ ```
514
708
 
515
- *Chris Salzberg*
709
+ *Weston Ganger*
710
+
711
+ * Use full precision for `updated_at` in `insert_all`/`upsert_all`
712
+
713
+ `CURRENT_TIMESTAMP` provides differing precision depending on the database,
714
+ and not all databases support explicitly specifying additional precision.
715
+
716
+ Instead, we delegate to the new `connection.high_precision_current_timestamp`
717
+ for the SQL to produce a high precision timestamp on the current database.
718
+
719
+ Fixes #42992
720
+
721
+ *Sam Bostock*
722
+
723
+ * Add ssl support for postgresql database tasks
724
+
725
+ Add `PGSSLMODE`, `PGSSLCERT`, `PGSSLKEY` and `PGSSLROOTCERT` to pg_env from database config
726
+ when running postgresql database tasks.
727
+
728
+ ```yaml
729
+ # config/database.yml
730
+
731
+ production:
732
+ sslmode: verify-full
733
+ sslcert: client.crt
734
+ sslkey: client.key
735
+ sslrootcert: ca.crt
736
+ ```
737
+
738
+ Environment variables
739
+
740
+ ```
741
+ PGSSLMODE=verify-full
742
+ PGSSLCERT=client.crt
743
+ PGSSLKEY=client.key
744
+ PGSSLROOTCERT=ca.crt
745
+ ```
746
+
747
+ Fixes #42994
516
748
 
517
- * Log database query callers.
749
+ *Michael Bayucot*
518
750
 
519
- Add `verbose_query_logs` configuration option to display the caller
520
- of database queries in the log to facilitate N+1 query resolution
521
- and other debugging.
751
+ * Avoid scoping update callbacks in `ActiveRecord::Relation#update!`.
522
752
 
523
- Enabled in development only for new and upgraded applications. Not
524
- recommended for use in the production environment since it relies
525
- on Ruby's `Kernel#caller_locations` which is fairly slow.
753
+ Making it consistent with how scoping is applied only to the query in `ActiveRecord::Relation#update`
754
+ and not also to the callbacks from the update itself.
526
755
 
527
- *Olivier Lacan*
756
+ *Dylan Thacker-Smith*
528
757
 
529
- * Fix conflicts `counter_cache` with `touch: true` by optimistic locking.
758
+ * Fix 2 cases that inferred polymorphic class from the association's `foreign_type`
759
+ using `String#constantize` instead of the model's `polymorphic_class_for`.
530
760
 
761
+ When updating a polymorphic association, the old `foreign_type` was not inferred correctly when:
762
+ 1. `touch`ing the previously associated record
763
+ 2. updating the previously associated record's `counter_cache`
764
+
765
+ *Jimmy Bourassa*
766
+
767
+ * Add config option for ignoring tables when dumping the schema cache.
768
+
769
+ Applications can now be configured to ignore certain tables when dumping the schema cache.
770
+
771
+ The configuration option can table an array of tables:
772
+
773
+ ```ruby
774
+ config.active_record.schema_cache_ignored_tables = ["ignored_table", "another_ignored_table"]
775
+ ```
776
+
777
+ Or a regex:
778
+
779
+ ```ruby
780
+ config.active_record.schema_cache_ignored_tables = [/^_/]
781
+ ```
782
+
783
+ *Eileen M. Uchitelle*
784
+
785
+ * Make schema cache methods return consistent results.
786
+
787
+ Previously the schema cache methods `primary_keys`, `columns`, `columns_hash`, and `indexes`
788
+ would behave differently than one another when a table didn't exist and differently across
789
+ database adapters. This change unifies the behavior so each method behaves the same regardless
790
+ of adapter.
791
+
792
+ The behavior now is:
793
+
794
+ `columns`: (unchanged) raises a db error if the table does not exist.
795
+ `columns_hash`: (unchanged) raises a db error if the table does not exist.
796
+ `primary_keys`: (unchanged) returns `nil` if the table does not exist.
797
+ `indexes`: (changed for mysql2) returns `[]` if the table does not exist.
798
+
799
+ *Eileen M. Uchitelle*
800
+
801
+ * Reestablish connection to previous database after after running `db:schema:load:name`
802
+
803
+ After running `db:schema:load:name` the previous connection is restored.
804
+
805
+ *Jacopo Beschi*
806
+
807
+ * Add database config option `database_tasks`
808
+
809
+ If you would like to connect to an external database without any database
810
+ management tasks such as schema management, migrations, seeds, etc. you can set
811
+ the per database config option `database_tasks: false`
812
+
813
+ ```yaml
814
+ # config/database.yml
815
+
816
+ production:
817
+ primary:
818
+ database: my_database
819
+ adapter: mysql2
820
+ animals:
821
+ database: my_animals_database
822
+ adapter: mysql2
823
+ database_tasks: false
531
824
  ```
532
- # create_table :posts do |t|
533
- # t.integer :comments_count, default: 0
534
- # t.integer :lock_version
535
- # t.timestamps
536
- # end
537
- class Post < ApplicationRecord
825
+
826
+ *Weston Ganger*
827
+
828
+ * Fix `ActiveRecord::InternalMetadata` to not be broken by `config.active_record.record_timestamps = false`
829
+
830
+ Since the model always create the timestamp columns, it has to set them, otherwise it breaks
831
+ various DB management tasks.
832
+
833
+ Fixes #42983
834
+
835
+ * Add `ActiveRecord::QueryLogs`.
836
+
837
+ Configurable tags can be automatically added to all SQL queries generated by Active Record.
838
+
839
+ ```ruby
840
+ # config/application.rb
841
+ module MyApp
842
+ class Application < Rails::Application
843
+ config.active_record.query_log_tags_enabled = true
844
+ end
538
845
  end
846
+ ```
539
847
 
540
- # create_table :comments do |t|
541
- # t.belongs_to :post
542
- # end
543
- class Comment < ApplicationRecord
544
- belongs_to :post, touch: true, counter_cache: true
848
+ By default the application, controller and action details are added to the query tags:
849
+
850
+ ```ruby
851
+ class BooksController < ApplicationController
852
+ def index
853
+ @books = Book.all
854
+ end
545
855
  end
546
856
  ```
547
857
 
548
- Before:
858
+ ```ruby
859
+ GET /books
860
+ # SELECT * FROM books /*application:MyApp;controller:books;action:index*/
861
+ ```
862
+
863
+ Custom tags containing static values and Procs can be defined in the application configuration:
864
+
865
+ ```ruby
866
+ config.active_record.query_log_tags = [
867
+ :application,
868
+ :controller,
869
+ :action,
870
+ {
871
+ custom_static: "foo",
872
+ custom_dynamic: -> { Time.now }
873
+ }
874
+ ]
549
875
  ```
550
- post = Post.create!
551
- # => begin transaction
552
- INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
553
- VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0)
554
- commit transaction
555
876
 
556
- comment = Comment.create!(post: post)
557
- # => begin transaction
558
- INSERT INTO "comments" ("post_id") VALUES (1)
877
+ *Keeran Raj Hawoldar*, *Eileen M. Uchitelle*, *Kasper Timm Hansen*
878
+
879
+ * Added support for multiple databases to `rails db:setup` and `rails db:reset`.
880
+
881
+ *Ryan Hall*
882
+
883
+ * Add `ActiveRecord::Relation#structurally_compatible?`.
559
884
 
560
- UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1,
561
- "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1
885
+ Adds a query method by which a user can tell if the relation that they're
886
+ about to use for `#or` or `#and` is structurally compatible with the
887
+ receiver.
562
888
 
563
- UPDATE "posts" SET "updated_at" = '2017-12-11 21:27:11.398330',
564
- "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0
565
- rollback transaction
566
- # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post.
889
+ *Kevin Newton*
567
890
 
568
- Comment.take.destroy!
569
- # => begin transaction
570
- DELETE FROM "comments" WHERE "comments"."id" = 1
891
+ * Add `ActiveRecord::QueryMethods#in_order_of`.
571
892
 
572
- UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1,
573
- "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1
893
+ This allows you to specify an explicit order that you'd like records
894
+ returned in based on a SQL expression. By default, this will be accomplished
895
+ using a case statement, as in:
574
896
 
575
- UPDATE "posts" SET "updated_at" = '2017-12-11 21:42:47.785901',
576
- "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0
577
- rollback transaction
578
- # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post.
897
+ ```ruby
898
+ Post.in_order_of(:id, [3, 5, 1])
579
899
  ```
580
900
 
581
- After:
901
+ will generate the SQL:
902
+
903
+ ```sql
904
+ 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
905
+ ```
906
+
907
+ However, because this functionality is built into MySQL in the form of the
908
+ `FIELD` function, that connection adapter will generate the following SQL
909
+ instead:
910
+
911
+ ```sql
912
+ SELECT "posts".* FROM "posts" ORDER BY FIELD("posts"."id", 1, 5, 3) DESC
582
913
  ```
583
- post = Post.create!
584
- # => begin transaction
585
- INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
586
- VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0)
587
- commit transaction
588
914
 
589
- comment = Comment.create!(post: post)
590
- # => begin transaction
591
- INSERT INTO "comments" ("post_id") VALUES (1)
915
+ *Kevin Newton*
592
916
 
593
- UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1,
594
- "lock_version" = COALESCE("lock_version", 0) + 1,
595
- "updated_at" = '2017-12-11 21:37:09.802642' WHERE "posts"."id" = 1
596
- commit transaction
917
+ * Fix `eager_loading?` when ordering with `Symbol`.
597
918
 
598
- comment.destroy!
599
- # => begin transaction
600
- DELETE FROM "comments" WHERE "comments"."id" = 1
919
+ `eager_loading?` is triggered correctly when using `order` with symbols.
601
920
 
602
- UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1,
603
- "lock_version" = COALESCE("lock_version", 0) + 1,
604
- "updated_at" = '2017-12-11 21:39:02.685520' WHERE "posts"."id" = 1
605
- commit transaction
921
+ ```ruby
922
+ scope = Post.includes(:comments).order(:"comments.label")
923
+ => true
606
924
  ```
607
925
 
608
- Fixes #31199.
926
+ *Jacopo Beschi*
609
927
 
610
- *bogdanvlviv*
928
+ * Two change tracking methods are added for `belongs_to` associations.
611
929
 
612
- * Add support for PostgreSQL operator classes to `add_index`.
930
+ The `association_changed?` method (assuming an association named `:association`) returns true
931
+ if a different associated object has been assigned and the foreign key will be updated in the
932
+ next save.
613
933
 
614
- Example:
934
+ The `association_previously_changed?` method returns true if the previous save updated the
935
+ association to reference a different associated object.
615
936
 
616
- add_index :users, :name, using: :gist, opclass: { name: :gist_trgm_ops }
937
+ *George Claghorn*
617
938
 
618
- *Greg Navis*
939
+ * Add option to disable schema dump per-database.
619
940
 
620
- * Don't allow scopes to be defined which conflict with instance methods on `Relation`.
941
+ Dumping the schema is on by default for all databases in an application. To turn it off for a
942
+ specific database, use the `schema_dump` option:
621
943
 
622
- Fixes #31120.
944
+ ```yaml
945
+ # config/database.yml
623
946
 
624
- *kinnrot*
947
+ production:
948
+ schema_dump: false
949
+ ```
625
950
 
626
- * Add new error class `QueryCanceled` which will be raised
627
- when canceling statement due to user request.
951
+ *Luis Vasconcellos*, *Eileen M. Uchitelle*
628
952
 
629
- *Ryuta Kamizono*
953
+ * Fix `eager_loading?` when ordering with `Hash` syntax.
630
954
 
631
- * Add `#up_only` to database migrations for code that is only relevant when
632
- migrating up, e.g. populating a new column.
955
+ `eager_loading?` is triggered correctly when using `order` with hash syntax
956
+ on an outer table.
633
957
 
634
- *Rich Daley*
958
+ ```ruby
959
+ Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading?
960
+ # => true
961
+ ```
635
962
 
636
- * Require raw SQL fragments to be explicitly marked when used in
637
- relation query methods.
963
+ *Jacopo Beschi*
638
964
 
639
- Before:
965
+ * Move the forcing of clear text encoding to the `ActiveRecord::Encryption::Encryptor`.
966
+
967
+ Fixes #42699.
968
+
969
+ *J Smith*
970
+
971
+ * `partial_inserts` is now disabled by default in new apps.
972
+
973
+ This will be the default for new apps in Rails 7. To opt in:
974
+
975
+ ```ruby
976
+ config.active_record.partial_inserts = true
640
977
  ```
641
- Article.order("LENGTH(title)")
978
+
979
+ If a migration removes the default value of a column, this option
980
+ would cause old processes to no longer be able to create new records.
981
+
982
+ If you need to remove a column, you should first use `ignored_columns`
983
+ to stop using it.
984
+
985
+ *Jean Boussier*
986
+
987
+ * Rails can now verify foreign keys after loading fixtures in tests.
988
+
989
+ This will be the default for new apps in Rails 7. To opt in:
990
+
991
+ ```ruby
992
+ config.active_record.verify_foreign_keys_for_fixtures = true
642
993
  ```
643
994
 
644
- After:
995
+ Tests will not run if there is a foreign key constraint violation in your fixture data.
996
+
997
+ The feature is supported by SQLite and PostgreSQL, other adapters can also add support for it.
998
+
999
+ *Alex Ghiculescu*
1000
+
1001
+ * Clear cached `has_one` association after setting `belongs_to` association to `nil`.
1002
+
1003
+ After setting a `belongs_to` relation to `nil` and updating an unrelated attribute on the owner,
1004
+ the owner should still return `nil` on the `has_one` relation.
1005
+
1006
+ Fixes #42597.
1007
+
1008
+ *Michiel de Mare*
1009
+
1010
+ * OpenSSL constants are now used for Digest computations.
1011
+
1012
+ *Dirkjan Bussink*
1013
+
1014
+ * Adds support for `if_not_exists` to `add_foreign_key` and `if_exists` to `remove_foreign_key`.
1015
+
1016
+ Applications can set their migrations to ignore exceptions raised when adding a foreign key
1017
+ that already exists or when removing a foreign key that does not exist.
1018
+
1019
+ Example Usage:
1020
+
1021
+ ```ruby
1022
+ class AddAuthorsForeignKeyToArticles < ActiveRecord::Migration[7.0]
1023
+ def change
1024
+ add_foreign_key :articles, :authors, if_not_exists: true
1025
+ end
1026
+ end
645
1027
  ```
646
- Article.order(Arel.sql("LENGTH(title)"))
1028
+
1029
+ ```ruby
1030
+ class RemoveAuthorsForeignKeyFromArticles < ActiveRecord::Migration[7.0]
1031
+ def change
1032
+ remove_foreign_key :articles, :authors, if_exists: true
1033
+ end
1034
+ end
647
1035
  ```
648
1036
 
649
- This prevents SQL injection if applications use the [strongly
650
- discouraged] form `Article.order(params[:my_order])`, under the
651
- mistaken belief that only column names will be accepted.
1037
+ *Roberto Miranda*
1038
+
1039
+ * Prevent polluting ENV during postgresql structure dump/load.
1040
+
1041
+ Some configuration parameters were provided to pg_dump / psql via
1042
+ environment variables which persisted beyond the command being run, and may
1043
+ have caused subsequent commands and connections to fail. Tasks running
1044
+ across multiple postgresql databases like `rails db:test:prepare` may have
1045
+ been affected.
652
1046
 
653
- Raw SQL strings will now cause a deprecation warning, which will
654
- become an UnknownAttributeReference error in Rails 6.0. Applications
655
- can opt in to the future behavior by setting `allow_unsafe_raw_sql`
656
- to `:disabled`.
1047
+ *Samuel Cochran*
657
1048
 
658
- Common and judged-safe string values (such as simple column
659
- references) are unaffected:
1049
+ * Set precision 6 by default for `datetime` columns.
1050
+
1051
+ By default, datetime columns will have microseconds precision instead of seconds precision.
1052
+
1053
+ *Roberto Miranda*
1054
+
1055
+ * Allow preloading of associations with instance dependent scopes.
1056
+
1057
+ *John Hawthorn*, *John Crepezzi*, *Adam Hess*, *Eileen M. Uchitelle*, *Dinah Shi*
1058
+
1059
+ * Do not try to rollback transactions that failed due to a `ActiveRecord::TransactionRollbackError`.
1060
+
1061
+ *Jamie McCarthy*
1062
+
1063
+ * Active Record Encryption will now encode values as UTF-8 when using deterministic
1064
+ encryption. The encoding is part of the encrypted payload, so different encodings for
1065
+ different values result in different ciphertexts. This can break unique constraints and
1066
+ queries.
1067
+
1068
+ The new behavior is configurable via `active_record.encryption.forced_encoding_for_deterministic_encryption`
1069
+ that is `Encoding::UTF_8` by default. It can be disabled by setting it to `nil`.
1070
+
1071
+ *Jorge Manrubia*
1072
+
1073
+ * The MySQL adapter now cast numbers and booleans bind parameters to string for safety reasons.
1074
+
1075
+ When comparing a string and a number in a query, MySQL converts the string to a number. So for
1076
+ instance `"foo" = 0`, will implicitly cast `"foo"` to `0` and will evaluate to `TRUE` which can
1077
+ lead to security vulnerabilities.
1078
+
1079
+ Active Record already protect against that vulnerability when it knows the type of the column
1080
+ being compared, however until now it was still vulnerable when using bind parameters:
1081
+
1082
+ ```ruby
1083
+ User.where("login_token = ?", 0).first
660
1084
  ```
661
- Article.order("title DESC")
1085
+
1086
+ Would perform:
1087
+
1088
+ ```sql
1089
+ SELECT * FROM `users` WHERE `login_token` = 0 LIMIT 1;
662
1090
  ```
663
1091
 
664
- *Ben Toews*
1092
+ Now it will perform:
665
1093
 
666
- * `update_all` will now pass its values to `Type#cast` before passing them to
667
- `Type#serialize`. This means that `update_all(foo: 'true')` will properly
668
- persist a boolean.
1094
+ ```sql
1095
+ SELECT * FROM `users` WHERE `login_token` = '0' LIMIT 1;
1096
+ ```
669
1097
 
670
- *Sean Griffin*
1098
+ *Jean Boussier*
671
1099
 
672
- * Add new error class `StatementTimeout` which will be raised
673
- when statement timeout exceeded.
1100
+ * Fixture configurations (`_fixture`) are now strictly validated.
674
1101
 
675
- *Ryuta Kamizono*
1102
+ If an error will be raised if that entry contains unknown keys while previously it
1103
+ would silently have no effects.
676
1104
 
677
- * Fix `bin/rails db:migrate` with specified `VERSION`.
678
- `bin/rails db:migrate` with empty VERSION behaves as without `VERSION`.
679
- Check a format of `VERSION`: Allow a migration version number
680
- or name of a migration file. Raise error if format of `VERSION` is invalid.
681
- Raise error if target migration doesn't exist.
1105
+ *Jean Boussier*
682
1106
 
683
- *bogdanvlviv*
1107
+ * Add `ActiveRecord::Base.update!` that works like `ActiveRecord::Base.update` but raises exceptions.
684
1108
 
685
- * Fixed a bug where column orders for an index weren't written to
686
- `db/schema.rb` when using the sqlite adapter.
1109
+ This allows for the same behavior as the instance method `#update!` at a class level.
687
1110
 
688
- Fixes #30902.
1111
+ ```ruby
1112
+ Person.update!(:all, state: "confirmed")
1113
+ ```
689
1114
 
690
- *Paul Kuruvilla*
1115
+ *Dorian Marié*
691
1116
 
692
- * Remove deprecated method `#sanitize_conditions`.
1117
+ * Add `ActiveRecord::Base#attributes_for_database`.
693
1118
 
694
- *Rafael Mendonça França*
1119
+ Returns attributes with values for assignment to the database.
695
1120
 
696
- * Remove deprecated method `#scope_chain`.
1121
+ *Chris Salzberg*
697
1122
 
698
- *Rafael Mendonça França*
1123
+ * Use an empty query to check if the PostgreSQL connection is still active.
699
1124
 
700
- * Remove deprecated configuration `.error_on_ignored_order_or_limit`.
1125
+ An empty query is faster than `SELECT 1`.
701
1126
 
702
- *Rafael Mendonça França*
1127
+ *Heinrich Lee Yu*
703
1128
 
704
- * Remove deprecated arguments from `#verify!`.
1129
+ * Add `ActiveRecord::Base#previously_persisted?`.
705
1130
 
706
- *Rafael Mendonça França*
1131
+ Returns `true` if the object has been previously persisted but now it has been deleted.
707
1132
 
708
- * Remove deprecated argument `name` from `#indexes`.
1133
+ * Deprecate `partial_writes` in favor of `partial_inserts` and `partial_updates`.
709
1134
 
710
- *Rafael Mendonça França*
1135
+ This allows to have a different behavior on update and create.
711
1136
 
712
- * Remove deprecated method `ActiveRecord::Migrator.schema_migrations_table_name`.
1137
+ *Jean Boussier*
713
1138
 
714
- *Rafael Mendonça França*
1139
+ * Fix compatibility with `psych >= 4`.
715
1140
 
716
- * Remove deprecated method `supports_primary_key?`.
1141
+ Starting in Psych 4.0.0 `YAML.load` behaves like `YAML.safe_load`. To preserve compatibility,
1142
+ Active Record's schema cache loader and `YAMLColumn` now uses `YAML.unsafe_load` if available.
717
1143
 
718
- *Rafael Mendonça França*
1144
+ *Jean Boussier*
719
1145
 
720
- * Remove deprecated method `supports_migrations?`.
1146
+ * `ActiveRecord::Base.logger` is now a `class_attribute`.
721
1147
 
722
- *Rafael Mendonça França*
1148
+ This means it can no longer be accessed directly through `@@logger`, and that setting `logger =`
1149
+ on a subclass won't change the parent's logger.
723
1150
 
724
- * Remove deprecated methods `initialize_schema_migrations_table` and `initialize_internal_metadata_table`.
1151
+ *Jean Boussier*
725
1152
 
726
- *Rafael Mendonça França*
1153
+ * Add `.asc.nulls_first` for all databases. Unfortunately MySQL still doesn't like `nulls_last`.
727
1154
 
728
- * Raises when calling `lock!` in a dirty record.
1155
+ *Keenan Brock*
729
1156
 
730
- *Rafael Mendonça França*
1157
+ * Improve performance of `one?` and `many?` by limiting the generated count query to 2 results.
731
1158
 
732
- * Remove deprecated support to passing a class to `:class_name` on associations.
1159
+ *Gonzalo Riestra*
733
1160
 
734
- *Rafael Mendonça França*
1161
+ * Don't check type when using `if_not_exists` on `add_column`.
735
1162
 
736
- * Remove deprecated argument `default` from `index_name_exists?`.
1163
+ Previously, if a migration called `add_column` with the `if_not_exists` option set to true
1164
+ the `column_exists?` check would look for a column with the same name and type as the migration.
737
1165
 
738
- *Rafael Mendonça França*
1166
+ Recently it was discovered that the type passed to the migration is not always the same type
1167
+ as the column after migration. For example a column set to `:mediumblob` in the migration will
1168
+ be casted to `binary` when calling `column.type`. Since there is no straightforward way to cast
1169
+ the type to the database type without running the migration, we opted to drop the type check from
1170
+ `add_column`. This means that migrations adding a duplicate column with a different type will no
1171
+ longer raise an error.
739
1172
 
740
- * Remove deprecated support to `quoted_id` when typecasting an Active Record object.
1173
+ *Eileen M. Uchitelle*
741
1174
 
742
- *Rafael Mendonça França*
1175
+ * Log a warning message when running SQLite in production.
743
1176
 
744
- * Fix `bin/rails db:setup` and `bin/rails db:test:prepare` create wrong
745
- ar_internal_metadata's data for a test database.
1177
+ Using SQLite in production ENV is generally discouraged. SQLite is also the default adapter
1178
+ in a new Rails application.
1179
+ For the above reasons log a warning message when running SQLite in production.
746
1180
 
747
- Before:
1181
+ The warning can be disabled by setting `config.active_record.sqlite3_production_warning=false`.
1182
+
1183
+ *Jacopo Beschi*
1184
+
1185
+ * Add option to disable joins for `has_one` associations.
1186
+
1187
+ In a multiple database application, associations can't join across
1188
+ databases. When set, this option instructs Rails to generate 2 or
1189
+ more queries rather than generating joins for `has_one` associations.
1190
+
1191
+ Set the option on a has one through association:
1192
+
1193
+ ```ruby
1194
+ class Person
1195
+ has_one :dog
1196
+ has_one :veterinarian, through: :dog, disable_joins: true
1197
+ end
748
1198
  ```
749
- $ RAILS_ENV=test rails dbconsole
750
- > SELECT * FROM ar_internal_metadata;
751
- key|value|created_at|updated_at
752
- environment|development|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679
1199
+
1200
+ Then instead of generating join SQL, two queries are used for `@person.veterinarian`:
1201
+
1202
+ ```
1203
+ SELECT "dogs"."id" FROM "dogs" WHERE "dogs"."person_id" = ? [["person_id", 1]]
1204
+ SELECT "veterinarians".* FROM "veterinarians" WHERE "veterinarians"."dog_id" = ? [["dog_id", 1]]
753
1205
  ```
754
1206
 
755
- After:
1207
+ *Sarah Vessels*, *Eileen M. Uchitelle*
1208
+
1209
+ * `Arel::Visitors::Dot` now renders a complete set of properties when visiting
1210
+ `Arel::Nodes::SelectCore`, `SelectStatement`, `InsertStatement`, `UpdateStatement`, and
1211
+ `DeleteStatement`, which fixes #42026. Previously, some properties were omitted.
1212
+
1213
+ *Mike Dalessio*
1214
+
1215
+ * `Arel::Visitors::Dot` now supports `Arel::Nodes::Bin`, `Case`, `CurrentRow`, `Distinct`,
1216
+ `DistinctOn`, `Else`, `Except`, `InfixOperation`, `Intersect`, `Lock`, `NotRegexp`, `Quoted`,
1217
+ `Regexp`, `UnaryOperation`, `Union`, `UnionAll`, `When`, and `With`. Previously, these node
1218
+ types caused an exception to be raised by `Arel::Visitors::Dot#accept`.
1219
+
1220
+ *Mike Dalessio*
1221
+
1222
+ * Optimize `remove_columns` to use a single SQL statement.
1223
+
1224
+ ```ruby
1225
+ remove_columns :my_table, :col_one, :col_two
756
1226
  ```
757
- $ RAILS_ENV=test rails dbconsole
758
- > SELECT * FROM ar_internal_metadata;
759
- key|value|created_at|updated_at
760
- environment|test|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679
1227
+
1228
+ Now results in the following SQL:
1229
+
1230
+ ```sql
1231
+ ALTER TABLE "my_table" DROP COLUMN "col_one", DROP COLUMN "col_two"
761
1232
  ```
762
1233
 
763
- Fixes #26731.
1234
+ *Jon Dufresne*
764
1235
 
765
- *bogdanvlviv*
1236
+ * Ensure `has_one` autosave association callbacks get called once.
766
1237
 
767
- * Fix longer sequence name detection for serial columns.
1238
+ Change the `has_one` autosave callback to be non cyclic as well.
1239
+ By doing this the autosave callback are made more consistent for
1240
+ all 3 cases: `has_many`, `has_one`, and `belongs_to`.
768
1241
 
769
- Fixes #28332.
1242
+ *Petrik de Heus*
770
1243
 
771
- *Ryuta Kamizono*
1244
+ * Add option to disable joins for associations.
772
1245
 
773
- * MySQL: Don't lose `auto_increment: true` in the `db/schema.rb`.
1246
+ In a multiple database application, associations can't join across
1247
+ databases. When set, this option instructs Rails to generate 2 or
1248
+ more queries rather than generating joins for associations.
774
1249
 
775
- Fixes #30894.
1250
+ Set the option on a has many through association:
776
1251
 
777
- *Ryuta Kamizono*
1252
+ ```ruby
1253
+ class Dog
1254
+ has_many :treats, through: :humans, disable_joins: true
1255
+ has_many :humans
1256
+ end
1257
+ ```
778
1258
 
779
- * Fix `COUNT(DISTINCT ...)` for `GROUP BY` with `ORDER BY` and `LIMIT`.
1259
+ Then instead of generating join SQL, two queries are used for `@dog.treats`:
780
1260
 
781
- Fixes #30886.
1261
+ ```
1262
+ SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ? [["dog_id", 1]]
1263
+ SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?) [["human_id", 1], ["human_id", 2], ["human_id", 3]]
1264
+ ```
782
1265
 
783
- *Ryuta Kamizono*
1266
+ *Eileen M. Uchitelle*, *Aaron Patterson*, *Lee Quarella*
1267
+
1268
+ * Add setting for enumerating column names in SELECT statements.
784
1269
 
785
- * PostgreSQL `tsrange` now preserves subsecond precision.
1270
+ Adding a column to a PostgreSQL database, for example, while the application is running can
1271
+ change the result of wildcard `SELECT *` queries, which invalidates the result
1272
+ of cached prepared statements and raises a `PreparedStatementCacheExpired` error.
786
1273
 
787
- PostgreSQL 9.1+ introduced range types, and Rails added support for using
788
- this datatype in Active Record. However, the serialization of
789
- `PostgreSQL::OID::Range` was incomplete, because it did not properly
790
- cast the bounds that make up the range. This led to subseconds being
791
- dropped in SQL commands:
1274
+ When enabled, Active Record will avoid wildcards and always include column names
1275
+ in `SELECT` queries, which will return consistent results and avoid prepared
1276
+ statement errors.
792
1277
 
793
1278
  Before:
794
1279
 
795
- connection.type_cast(tsrange.serialize(range_value))
796
- # => "[2010-01-01 13:30:00 UTC,2011-02-02 19:30:00 UTC)"
1280
+ ```ruby
1281
+ Book.limit(5)
1282
+ # SELECT * FROM books LIMIT 5
1283
+ ```
1284
+
1285
+ After:
1286
+
1287
+ ```ruby
1288
+ # config/application.rb
1289
+ module MyApp
1290
+ class Application < Rails::Application
1291
+ config.active_record.enumerate_columns_in_select_statements = true
1292
+ end
1293
+ end
1294
+
1295
+ # or, configure per-model
1296
+ class Book < ApplicationRecord
1297
+ self.enumerate_columns_in_select_statements = true
1298
+ end
1299
+ ```
1300
+
1301
+ ```ruby
1302
+ Book.limit(5)
1303
+ # SELECT id, author_id, name, format, status, language, etc FROM books LIMIT 5
1304
+ ```
1305
+
1306
+ *Matt Duszynski*
1307
+
1308
+ * Allow passing SQL as `on_duplicate` value to `#upsert_all` to make it possible to use raw SQL to update columns on conflict:
1309
+
1310
+ ```ruby
1311
+ Book.upsert_all(
1312
+ [{ id: 1, status: 1 }, { id: 2, status: 1 }],
1313
+ on_duplicate: Arel.sql("status = GREATEST(books.status, EXCLUDED.status)")
1314
+ )
1315
+ ```
1316
+
1317
+ *Vladimir Dementyev*
1318
+
1319
+ * Allow passing SQL as `returning` statement to `#upsert_all`:
1320
+
1321
+ ```ruby
1322
+ Article.insert_all(
1323
+ [
1324
+ { title: "Article 1", slug: "article-1", published: false },
1325
+ { title: "Article 2", slug: "article-2", published: false }
1326
+ ],
1327
+ returning: Arel.sql("id, (xmax = '0') as inserted, name as new_name")
1328
+ )
1329
+ ```
1330
+
1331
+ *Vladimir Dementyev*
1332
+
1333
+ * Deprecate `legacy_connection_handling`.
1334
+
1335
+ *Eileen M. Uchitelle*
1336
+
1337
+ * Add attribute encryption support.
797
1338
 
798
- Now:
1339
+ Encrypted attributes are declared at the model level. These
1340
+ are regular Active Record attributes backed by a column with
1341
+ the same name. The system will transparently encrypt these
1342
+ attributes before saving them into the database and will
1343
+ decrypt them when retrieving their values.
799
1344
 
800
- connection.type_cast(tsrange.serialize(range_value))
801
- # => "[2010-01-01 13:30:00.670277,2011-02-02 19:30:00.745125)"
802
1345
 
803
- *Thomas Cannon*
1346
+ ```ruby
1347
+ class Person < ApplicationRecord
1348
+ encrypts :name
1349
+ encrypts :email_address, deterministic: true
1350
+ end
1351
+ ```
1352
+
1353
+ You can learn more in the [Active Record Encryption
1354
+ guide](https://edgeguides.rubyonrails.org/active_record_encryption.html).
1355
+
1356
+ *Jorge Manrubia*
1357
+
1358
+ * Changed Arel predications `contains` and `overlaps` to use
1359
+ `quoted_node` so that PostgreSQL arrays are quoted properly.
1360
+
1361
+ *Bradley Priest*
1362
+
1363
+ * Add mode argument to record level `strict_loading!`.
1364
+
1365
+ This argument can be used when enabling strict loading for a single record
1366
+ to specify that we only want to raise on n plus one queries.
1367
+
1368
+ ```ruby
1369
+ developer.strict_loading!(mode: :n_plus_one_only)
1370
+
1371
+ developer.projects.to_a # Does not raise
1372
+ developer.projects.first.client # Raises StrictLoadingViolationError
1373
+ ```
1374
+
1375
+ Previously, enabling strict loading would cause any lazily loaded
1376
+ association to raise an error. Using `n_plus_one_only` mode allows us to
1377
+ lazily load belongs_to, has_many, and other associations that are fetched
1378
+ through a single query.
1379
+
1380
+ *Dinah Shi*
1381
+
1382
+ * Fix Float::INFINITY assignment to datetime column with postgresql adapter.
804
1383
 
805
- * Passing a `Set` to `Relation#where` now behaves the same as passing an
806
- array.
1384
+ Before:
1385
+
1386
+ ```ruby
1387
+ # With this config
1388
+ ActiveRecord::Base.time_zone_aware_attributes = true
1389
+
1390
+ # and the following schema:
1391
+ create_table "postgresql_infinities" do |t|
1392
+ t.datetime "datetime"
1393
+ end
807
1394
 
808
- *Sean Griffin*
1395
+ # This test fails
1396
+ record = PostgresqlInfinity.create!(datetime: Float::INFINITY)
1397
+ assert_equal Float::INFINITY, record.datetime # record.datetime gets nil
1398
+ ```
809
1399
 
810
- * Use given algorithm while removing index from database.
1400
+ After this commit, `record.datetime` gets `Float::INFINITY` as expected.
811
1401
 
812
- Fixes #24190.
1402
+ *Shunichi Ikegami*
813
1403
 
814
- *Mehmet Emin İNAÇ*
1404
+ * Type cast enum values by the original attribute type.
815
1405
 
816
- * Update payload names for `sql.active_record` instrumentation to be
817
- more descriptive.
1406
+ The notable thing about this change is that unknown labels will no longer match 0 on MySQL.
818
1407
 
819
- Fixes #30586.
1408
+ ```ruby
1409
+ class Book < ActiveRecord::Base
1410
+ enum :status, { proposed: 0, written: 1, published: 2 }
1411
+ end
1412
+ ```
820
1413
 
821
- *Jeremy Green*
1414
+ Before:
822
1415
 
823
- * Add new error class `LockWaitTimeout` which will be raised
824
- when lock wait timeout exceeded.
1416
+ ```ruby
1417
+ # SELECT `books`.* FROM `books` WHERE `books`.`status` = 'prohibited' LIMIT 1
1418
+ Book.find_by(status: :prohibited)
1419
+ # => #<Book id: 1, status: "proposed", ...> (for mysql2 adapter)
1420
+ # => ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for type integer: "prohibited" (for postgresql adapter)
1421
+ # => nil (for sqlite3 adapter)
1422
+ ```
825
1423
 
826
- *Gabriel Courtemanche*
1424
+ After:
827
1425
 
828
- * Remove deprecated `#migration_keys`.
1426
+ ```ruby
1427
+ # SELECT `books`.* FROM `books` WHERE `books`.`status` IS NULL LIMIT 1
1428
+ Book.find_by(status: :prohibited)
1429
+ # => nil (for all adapters)
1430
+ ```
829
1431
 
830
1432
  *Ryuta Kamizono*
831
1433
 
832
- * Automatically guess the inverse associations for STI.
1434
+ * Fixtures for `has_many :through` associations now load timestamps on join tables.
833
1435
 
834
- *Yuichiro Kaneko*
1436
+ Given this fixture:
835
1437
 
836
- * Ensure `sum` honors `distinct` on `has_many :through` associations.
1438
+ ```yml
1439
+ ### monkeys.yml
1440
+ george:
1441
+ name: George the Monkey
1442
+ fruits: apple
837
1443
 
838
- Fixes #16791.
1444
+ ### fruits.yml
1445
+ apple:
1446
+ name: apple
1447
+ ```
839
1448
 
840
- *Aaron Wortham*
1449
+ If the join table (`fruit_monkeys`) contains `created_at` or `updated_at` columns,
1450
+ these will now be populated when loading the fixture. Previously, fixture loading
1451
+ would crash if these columns were required, and leave them as null otherwise.
841
1452
 
842
- * Add `binary` fixture helper method.
1453
+ *Alex Ghiculescu*
843
1454
 
844
- *Atsushi Yoshida*
1455
+ * Allow applications to configure the thread pool for async queries.
845
1456
 
846
- * When using `Relation#or`, extract the common conditions and put them before the OR condition.
1457
+ Some applications may want one thread pool per database whereas others want to use
1458
+ a single global thread pool for all queries. By default, Rails will set `async_query_executor`
1459
+ to `nil` which will not initialize any executor. If `load_async` is called and no executor
1460
+ has been configured, the query will be executed in the foreground.
847
1461
 
848
- *Maxime Handfield Lapointe*
1462
+ To create one thread pool for all database connections to use applications can set
1463
+ `config.active_record.async_query_executor` to `:global_thread_pool` and optionally define
1464
+ `config.active_record.global_executor_concurrency`. This defaults to 4. For applications that want
1465
+ to have a thread pool for each database connection, `config.active_record.async_query_executor` can
1466
+ be set to `:multi_thread_pool`. The configuration for each thread pool is set in the database
1467
+ configuration.
849
1468
 
850
- * `Relation#or` now accepts two relations who have different values for
851
- `references` only, as `references` can be implicitly called by `where`.
1469
+ *Eileen M. Uchitelle*
852
1470
 
853
- Fixes #29411.
1471
+ * Allow new syntax for `enum` to avoid leading `_` from reserved options.
854
1472
 
855
- *Sean Griffin*
1473
+ Before:
856
1474
 
857
- * `ApplicationRecord` is no longer generated when generating models. If you
858
- need to generate it, it can be created with `rails g application_record`.
1475
+ ```ruby
1476
+ class Book < ActiveRecord::Base
1477
+ enum status: [ :proposed, :written ], _prefix: true, _scopes: false
1478
+ enum cover: [ :hard, :soft ], _suffix: true, _default: :hard
1479
+ end
1480
+ ```
859
1481
 
860
- *Lisa Ugray*
1482
+ After:
861
1483
 
862
- * Fix `COUNT(DISTINCT ...)` with `ORDER BY` and `LIMIT` to keep the existing select list.
1484
+ ```ruby
1485
+ class Book < ActiveRecord::Base
1486
+ enum :status, [ :proposed, :written ], prefix: true, scopes: false
1487
+ enum :cover, [ :hard, :soft ], suffix: true, default: :hard
1488
+ end
1489
+ ```
863
1490
 
864
1491
  *Ryuta Kamizono*
865
1492
 
866
- * When a `has_one` association is destroyed by `dependent: destroy`,
867
- `destroyed_by_association` will now be set to the reflection, matching the
868
- behaviour of `has_many` associations.
1493
+ * Add `ActiveRecord::Relation#load_async`.
1494
+
1495
+ This method schedules the query to be performed asynchronously from a thread pool.
869
1496
 
870
- *Lisa Ugray*
1497
+ If the result is accessed before a background thread had the opportunity to perform
1498
+ the query, it will be performed in the foreground.
871
1499
 
872
- * Fix `unscoped(where: [columns])` removing the wrong bind values.
1500
+ This is useful for queries that can be performed long enough before their result will be
1501
+ needed, or for controllers which need to perform several independent queries.
1502
+
1503
+ ```ruby
1504
+ def index
1505
+ @categories = Category.some_complex_scope.load_async
1506
+ @posts = Post.some_complex_scope.load_async
1507
+ end
1508
+ ```
873
1509
 
874
- When the `where` is called on a relation after a `or`, unscoping the column of that later `where` removed
875
- bind values used by the `or` instead. (possibly other cases too)
1510
+ Active Record logs will also include timing info for the duration of how long
1511
+ the main thread had to wait to access the result. This timing is useful to know
1512
+ whether or not it's worth to load the query asynchronously.
876
1513
 
877
1514
  ```
878
- Post.where(id: 1).or(Post.where(id: 2)).where(foo: 3).unscope(where: :foo).to_sql
879
- # Currently:
880
- # SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 2 OR "posts"."id" = 3)
881
- # With fix:
882
- # SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 1 OR "posts"."id" = 2)
1515
+ DEBUG -- : Category Load (62.1ms) SELECT * FROM `categories` LIMIT 50
1516
+ DEBUG -- : ASYNC Post Load (64ms) (db time 126.1ms) SELECT * FROM `posts` LIMIT 100
883
1517
  ```
884
1518
 
885
- *Maxime Handfield Lapointe*
1519
+ The duration in the first set of parens is how long the main thread was blocked
1520
+ waiting for the results, and the second set of parens with "db time" is how long
1521
+ the entire query took to execute.
886
1522
 
887
- * Values constructed using multi-parameter assignment will now use the
888
- post-type-cast value for rendering in single-field form inputs.
1523
+ *Jean Boussier*
889
1524
 
890
- *Sean Griffin*
1525
+ * Implemented `ActiveRecord::Relation#excluding` method.
891
1526
 
892
- * `Relation#joins` is no longer affected by the target model's
893
- `current_scope`, with the exception of `unscoped`.
1527
+ This method excludes the specified record (or collection of records) from
1528
+ the resulting relation:
894
1529
 
895
- Fixes #29338.
1530
+ ```ruby
1531
+ Post.excluding(post)
1532
+ Post.excluding(post_one, post_two)
1533
+ ```
896
1534
 
897
- *Sean Griffin*
1535
+ Also works on associations:
898
1536
 
899
- * Change sqlite3 boolean serialization to use 1 and 0.
1537
+ ```ruby
1538
+ post.comments.excluding(comment)
1539
+ post.comments.excluding(comment_one, comment_two)
1540
+ ```
900
1541
 
901
- SQLite natively recognizes 1 and 0 as true and false, but does not natively
902
- recognize 't' and 'f' as was previously serialized.
1542
+ This is short-hand for `Post.where.not(id: post.id)` (for a single record)
1543
+ and `Post.where.not(id: [post_one.id, post_two.id])` (for a collection).
903
1544
 
904
- This change in serialization requires a migration of stored boolean data
905
- for SQLite databases, so it's implemented behind a configuration flag
906
- whose default false value is deprecated.
1545
+ *Glen Crawford*
907
1546
 
908
- *Lisa Ugray*
1547
+ * Skip optimised #exist? query when #include? is called on a relation
1548
+ with a having clause.
909
1549
 
910
- * Skip query caching when working with batches of records (`find_each`, `find_in_batches`,
911
- `in_batches`).
1550
+ Relations that have aliased select values AND a having clause that
1551
+ references an aliased select value would generate an error when
1552
+ #include? was called, due to an optimisation that would generate
1553
+ call #exists? on the relation instead, which effectively alters
1554
+ the select values of the query (and thus removes the aliased select
1555
+ values), but leaves the having clause intact. Because the having
1556
+ clause is then referencing an aliased column that is no longer
1557
+ present in the simplified query, an ActiveRecord::InvalidStatement
1558
+ error was raised.
912
1559
 
913
- Previously, records would be fetched in batches, but all records would be retained in memory
914
- until the end of the request or job.
1560
+ A sample query affected by this problem:
915
1561
 
916
- *Eugene Kenny*
1562
+ ```ruby
1563
+ Author.select('COUNT(*) as total_posts', 'authors.*')
1564
+ .joins(:posts)
1565
+ .group(:id)
1566
+ .having('total_posts > 2')
1567
+ .include?(Author.first)
1568
+ ```
917
1569
 
918
- * Prevent errors raised by `sql.active_record` notification subscribers from being converted into
919
- `ActiveRecord::StatementInvalid` exceptions.
1570
+ This change adds an addition check to the condition that skips the
1571
+ simplified #exists? query, which simply checks for the presence of
1572
+ a having clause.
920
1573
 
921
- *Dennis Taylor*
1574
+ Fixes #41417.
922
1575
 
923
- * Fix eager loading/preloading association with scope including joins.
1576
+ *Michael Smart*
924
1577
 
925
- Fixes #28324.
1578
+ * Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
1579
+ without Rails knowledge (e.g., if app gets killed during long-running query or due to Rack::Timeout), app won't end
1580
+ up in perpetual crash state for being inconsistent with PostgreSQL.
926
1581
 
927
- *Ryuta Kamizono*
1582
+ *wbharding*, *Martin Tepper*
928
1583
 
929
- * Fix transactions to apply state to child transactions.
1584
+ * Add ability to apply `scoping` to `all_queries`.
930
1585
 
931
- Previously, if you had a nested transaction and the outer transaction was rolledback, the record from the
932
- inner transaction would still be marked as persisted.
1586
+ Some applications may want to use the `scoping` method but previously it only
1587
+ worked on certain types of queries. This change allows the `scoping` method to apply
1588
+ to all queries for a model in a block.
933
1589
 
934
- This change fixes that by applying the state of the parent transaction to the child transaction when the
935
- parent transaction is rolledback. This will correctly mark records from the inner transaction as not persisted.
1590
+ ```ruby
1591
+ Post.where(blog_id: post.blog_id).scoping(all_queries: true) do
1592
+ post.update(title: "a post title") # adds `posts.blog_id = 1` to the query
1593
+ end
1594
+ ```
936
1595
 
937
- *Eileen M. Uchitelle*, *Aaron Patterson*
1596
+ *Eileen M. Uchitelle*
938
1597
 
939
- * Deprecate `set_state` method in `TransactionState`.
1598
+ * `ActiveRecord::Calculations.calculate` called with `:average`
1599
+ (aliased as `ActiveRecord::Calculations.average`) will now use column-based
1600
+ type casting. This means that floating-point number columns will now be
1601
+ aggregated as `Float` and decimal columns will be aggregated as `BigDecimal`.
940
1602
 
941
- Deprecated the `set_state` method in favor of setting the state via specific methods. If you need to mark the
942
- state of the transaction you can now use `rollback!`, `commit!` or `nullify!` instead of
943
- `set_state(:rolledback)`, `set_state(:committed)`, or `set_state(nil)`.
1603
+ Integers are handled as a special case returning `BigDecimal` always
1604
+ (this was the case before already).
944
1605
 
945
- *Eileen M. Uchitelle*, *Aaron Patterson*
1606
+ ```ruby
1607
+ # With the following schema:
1608
+ create_table "measurements" do |t|
1609
+ t.float "temperature"
1610
+ end
946
1611
 
947
- * Deprecate delegating to `arel` in `Relation`.
1612
+ # Before:
1613
+ Measurement.average(:temperature).class
1614
+ # => BigDecimal
948
1615
 
949
- *Ryuta Kamizono*
1616
+ # After:
1617
+ Measurement.average(:temperature).class
1618
+ # => Float
1619
+ ```
1620
+
1621
+ Before this change, Rails just called `to_d` on average aggregates from the
1622
+ database adapter. This is not the case anymore. If you relied on that kind
1623
+ of magic, you now need to register your own `ActiveRecord::Type`
1624
+ (see `ActiveRecord::Attributes::ClassMethods` for documentation).
1625
+
1626
+ *Josua Schmid*
950
1627
 
951
- * Query cache was unavailable when entering the `ActiveRecord::Base.cache` block
952
- without being connected.
1628
+ * PostgreSQL: introduce `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type`.
953
1629
 
954
- *Tsukasa Oishi*
1630
+ This setting controls what native type Active Record should use when you call `datetime` in
1631
+ a migration or schema. It takes a symbol which must correspond to one of the configured
1632
+ `NATIVE_DATABASE_TYPES`. The default is `:timestamp`, meaning `t.datetime` in a migration
1633
+ will create a "timestamp without time zone" column. To use "timestamp with time zone",
1634
+ change this to `:timestamptz` in an initializer.
955
1635
 
956
- * Previously, when building records using a `has_many :through` association,
957
- if the child records were deleted before the parent was saved, they would
958
- still be persisted. Now, if child records are deleted before the parent is saved
959
- on a `has_many :through` association, the child records will not be persisted.
1636
+ You should run `bin/rails db:migrate` to rebuild your schema.rb if you change this.
960
1637
 
961
- *Tobias Kraze*
1638
+ *Alex Ghiculescu*
962
1639
 
963
- * Merging two relations representing nested joins no longer transforms the joins of
964
- the merged relation into LEFT OUTER JOIN.
1640
+ * PostgreSQL: handle `timestamp with time zone` columns correctly in `schema.rb`.
965
1641
 
966
- Example:
1642
+ Previously they dumped as `t.datetime :column_name`, now they dump as `t.timestamptz :column_name`,
1643
+ and are created as `timestamptz` columns when the schema is loaded.
967
1644
 
1645
+ *Alex Ghiculescu*
1646
+
1647
+ * Removing trailing whitespace when matching columns in
1648
+ `ActiveRecord::Sanitization.disallow_raw_sql!`.
1649
+
1650
+ *Gannon McGibbon*, *Adrian Hirt*
1651
+
1652
+ * Expose a way for applications to set a `primary_abstract_class`.
1653
+
1654
+ Multiple database applications that use a primary abstract class that is not
1655
+ named `ApplicationRecord` can now set a specific class to be the `primary_abstract_class`.
1656
+
1657
+ ```ruby
1658
+ class PrimaryApplicationRecord
1659
+ self.primary_abstract_class
1660
+ end
968
1661
  ```
969
- Author.joins(:posts).merge(Post.joins(:comments))
970
- # Before the change:
971
- #=> SELECT ... FROM authors INNER JOIN posts ON ... LEFT OUTER JOIN comments ON...
972
1662
 
973
- # After the change:
974
- #=> SELECT ... FROM authors INNER JOIN posts ON ... INNER JOIN comments ON...
1663
+ When an application boots it automatically connects to the primary or first database in the
1664
+ database configuration file. In a multiple database application that then call `connects_to`
1665
+ needs to know that the default connection is the same as the `ApplicationRecord` connection.
1666
+ However, some applications have a differently named `ApplicationRecord`. This prevents Active
1667
+ Record from opening duplicate connections to the same database.
1668
+
1669
+ *Eileen M. Uchitelle*, *John Crepezzi*
1670
+
1671
+ * Support hash config for `structure_dump_flags` and `structure_load_flags` flags.
1672
+ Now that Active Record supports multiple databases configuration,
1673
+ we need a way to pass specific flags for dump/load databases since
1674
+ the options are not the same for different adapters.
1675
+ We can use in the original way:
1676
+
1677
+ ```ruby
1678
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-defaults', '--skip-add-drop-table']
1679
+ # or
1680
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table'
975
1681
  ```
976
1682
 
977
- *Maxime Handfield Lapointe*
1683
+ And also use it passing a hash, with one or more keys, where the key
1684
+ is the adapter
978
1685
 
979
- * `ActiveRecord::Persistence#touch` does not work well when optimistic locking enabled and
980
- `locking_column`, without default value, is null in the database.
1686
+ ```ruby
1687
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = {
1688
+ mysql2: ['--no-defaults', '--skip-add-drop-table'],
1689
+ postgres: '--no-tablespaces'
1690
+ }
1691
+ ```
981
1692
 
982
- *bogdanvlviv*
1693
+ *Gustavo Gonzalez*
983
1694
 
984
- * Fix destroying existing object does not work well when optimistic locking enabled and
985
- `locking_column` is null in the database.
1695
+ * Connection specification now passes the "url" key as a configuration for the
1696
+ adapter if the "url" protocol is "jdbc", "http", or "https". Previously only
1697
+ urls with the "jdbc" prefix were passed to the Active Record Adapter, others
1698
+ are assumed to be adapter specification urls.
986
1699
 
987
- *bogdanvlviv*
1700
+ Fixes #41137.
988
1701
 
989
- * Use bulk INSERT to insert fixtures for better performance.
1702
+ *Jonathan Bracy*
990
1703
 
991
- *Kir Shatrov*
1704
+ * Allow to opt-out of `strict_loading` mode on a per-record base.
992
1705
 
993
- * Prevent creation of bind param if casted value is nil.
1706
+ This is useful when strict loading is enabled application wide or on a
1707
+ model level.
994
1708
 
995
- *Ryuta Kamizono*
1709
+ ```ruby
1710
+ class User < ApplicationRecord
1711
+ has_many :bookmarks
1712
+ has_many :articles, strict_loading: true
1713
+ end
996
1714
 
997
- * Deprecate passing arguments and block at the same time to `count` and `sum` in `ActiveRecord::Calculations`.
1715
+ user = User.first
1716
+ user.articles # => ActiveRecord::StrictLoadingViolationError
1717
+ user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy>
998
1718
 
999
- *Ryuta Kamizono*
1719
+ user.strict_loading!(true) # => true
1720
+ user.bookmarks # => ActiveRecord::StrictLoadingViolationError
1721
+
1722
+ user.strict_loading!(false) # => false
1723
+ user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy>
1724
+ user.articles.strict_loading!(false) # => #<ActiveRecord::Associations::CollectionProxy>
1725
+ ```
1726
+
1727
+ *Ayrton De Craene*
1000
1728
 
1001
- * Loading model schema from database is now thread-safe.
1729
+ * Add `FinderMethods#sole` and `#find_sole_by` to find and assert the
1730
+ presence of exactly one record.
1002
1731
 
1003
- Fixes #28589.
1732
+ Used when you need a single row, but also want to assert that there aren't
1733
+ multiple rows matching the condition; especially for when database
1734
+ constraints aren't enough or are impractical.
1004
1735
 
1005
- *Vikrant Chaudhary*, *David Abdemoulaie*
1736
+ ```ruby
1737
+ Product.where(["price = %?", price]).sole
1738
+ # => ActiveRecord::RecordNotFound (if no Product with given price)
1739
+ # => #<Product ...> (if one Product with given price)
1740
+ # => ActiveRecord::SoleRecordExceeded (if more than one Product with given price)
1006
1741
 
1007
- * Add `ActiveRecord::Base#cache_version` to support recyclable cache keys via the new versioned entries
1008
- in `ActiveSupport::Cache`. This also means that `ActiveRecord::Base#cache_key` will now return a stable key
1009
- that does not include a timestamp any more.
1742
+ user.api_keys.find_sole_by(key: key)
1743
+ # as above
1744
+ ```
1010
1745
 
1011
- NOTE: This feature is turned off by default, and `#cache_key` will still return cache keys with timestamps
1012
- until you set `ActiveRecord::Base.cache_versioning = true`. That's the setting for all new apps on Rails 5.2+
1746
+ *Asherah Connor*
1013
1747
 
1014
- *DHH*
1748
+ * Makes `ActiveRecord::AttributeMethods::Query` respect the getter overrides defined in the model.
1015
1749
 
1016
- * Respect `SchemaDumper.ignore_tables` in rake tasks for databases structure dump.
1750
+ Before:
1017
1751
 
1018
- *Rusty Geldmacher*, *Guillermo Iguaran*
1752
+ ```ruby
1753
+ class User
1754
+ def admin
1755
+ false # Overriding the getter to always return false
1756
+ end
1757
+ end
1019
1758
 
1020
- * Add type caster to `RuntimeReflection#alias_name`.
1759
+ user = User.first
1760
+ user.update(admin: true)
1021
1761
 
1022
- Fixes #28959.
1762
+ user.admin # false (as expected, due to the getter overwrite)
1763
+ user.admin? # true (not expected, returned the DB column value)
1764
+ ```
1023
1765
 
1024
- *Jon Moss*
1766
+ After this commit, `user.admin?` above returns false, as expected.
1025
1767
 
1026
- * Deprecate `supports_statement_cache?`.
1768
+ Fixes #40771.
1027
1769
 
1028
- *Ryuta Kamizono*
1770
+ *Felipe*
1029
1771
 
1030
- * Raise error `UnknownMigrationVersionError` on the movement of migrations
1031
- when the current migration does not exist.
1772
+ * Allow delegated_type to be specified primary_key and foreign_key.
1032
1773
 
1033
- *bogdanvlviv*
1774
+ Since delegated_type assumes that the foreign_key ends with `_id`,
1775
+ `singular_id` defined by it does not work when the foreign_key does
1776
+ not end with `id`. This change fixes it by taking into account
1777
+ `primary_key` and `foreign_key` in the options.
1034
1778
 
1035
- * Fix `bin/rails db:forward` first migration.
1779
+ *Ryota Egusa*
1036
1780
 
1037
- *bogdanvlviv*
1781
+ * Expose an `invert_where` method that will invert all scope conditions.
1038
1782
 
1039
- * Support Descending Indexes for MySQL.
1783
+ ```ruby
1784
+ class User
1785
+ scope :active, -> { where(accepted: true, locked: false) }
1786
+ end
1040
1787
 
1041
- MySQL 8.0.1 and higher supports descending indexes: `DESC` in an index definition is no longer ignored.
1042
- See https://dev.mysql.com/doc/refman/8.0/en/descending-indexes.html.
1788
+ User.active
1789
+ # ... WHERE `accepted` = 1 AND `locked` = 0
1043
1790
 
1044
- *Ryuta Kamizono*
1791
+ User.active.invert_where
1792
+ # ... WHERE NOT (`accepted` = 1 AND `locked` = 0)
1793
+ ```
1794
+
1795
+ *Kevin Deisz*
1796
+
1797
+ * Restore possibility of passing `false` to :polymorphic option of `belongs_to`.
1798
+
1799
+ Previously, passing `false` would trigger the option validation logic
1800
+ to throw an error saying :polymorphic would not be a valid option.
1801
+
1802
+ *glaszig*
1803
+
1804
+ * Remove deprecated `database` kwarg from `connected_to`.
1805
+
1806
+ *Eileen M. Uchitelle*, *John Crepezzi*
1807
+
1808
+ * Allow adding nonnamed expression indexes to be revertible.
1809
+
1810
+ Previously, the following code would raise an error, when executed while rolling back,
1811
+ and the index name should be specified explicitly. Now, the index name is inferred
1812
+ automatically.
1813
+
1814
+ ```ruby
1815
+ add_index(:items, "to_tsvector('english', description)")
1816
+ ```
1817
+
1818
+ Fixes #40732.
1819
+
1820
+ *fatkodima*
1821
+
1822
+ * Only warn about negative enums if a positive form that would cause conflicts exists.
1823
+
1824
+ Fixes #39065.
1825
+
1826
+ *Alex Ghiculescu*
1827
+
1828
+ * Add option to run `default_scope` on all queries.
1829
+
1830
+ 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`).
1831
+
1832
+ 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.
1833
+
1834
+ ```ruby
1835
+ class Article < ApplicationRecord
1836
+ default_scope -> { where(blog_id: Current.blog.id) }, all_queries: true
1837
+ end
1838
+ ```
1839
+
1840
+ *Eileen M. Uchitelle*
1841
+
1842
+ * Add `where.associated` to check for the presence of an association.
1843
+
1844
+ ```ruby
1845
+ # Before:
1846
+ account.users.joins(:contact).where.not(contact_id: nil)
1847
+
1848
+ # After:
1849
+ account.users.where.associated(:contact)
1850
+ ```
1045
1851
 
1046
- * Fix inconsistency with changed attributes when overriding Active Record attribute reader.
1852
+ Also mirrors `where.missing`.
1047
1853
 
1048
- *bogdanvlviv*
1854
+ *Kasper Timm Hansen*
1049
1855
 
1050
- * When calling the dynamic fixture accessor method with no arguments, it now returns all fixtures of this type.
1051
- Previously this method always returned an empty array.
1856
+ * Allow constructors (`build_association` and `create_association`) on
1857
+ `has_one :through` associations.
1052
1858
 
1053
- *Kevin McPhillips*
1859
+ *Santiago Perez Perret*
1054
1860
 
1055
1861
 
1056
- Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/activerecord/CHANGELOG.md) for previous changes.
1862
+ Please check [6-1-stable](https://github.com/rails/rails/blob/6-1-stable/activerecord/CHANGELOG.md) for previous changes.