activerecord 5.0.7.2 → 6.0.6.1

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 (359) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +844 -1944
  3. data/MIT-LICENSE +3 -1
  4. data/README.rdoc +9 -7
  5. data/examples/performance.rb +31 -29
  6. data/examples/simple.rb +5 -3
  7. data/lib/active_record/advisory_lock_base.rb +18 -0
  8. data/lib/active_record/aggregations.rb +249 -247
  9. data/lib/active_record/association_relation.rb +18 -14
  10. data/lib/active_record/associations/alias_tracker.rb +24 -34
  11. data/lib/active_record/associations/association.rb +113 -55
  12. data/lib/active_record/associations/association_scope.rb +102 -96
  13. data/lib/active_record/associations/belongs_to_association.rb +58 -42
  14. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +8 -12
  15. data/lib/active_record/associations/builder/association.rb +18 -25
  16. data/lib/active_record/associations/builder/belongs_to.rb +43 -54
  17. data/lib/active_record/associations/builder/collection_association.rb +7 -18
  18. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +41 -62
  19. data/lib/active_record/associations/builder/has_many.rb +4 -0
  20. data/lib/active_record/associations/builder/has_one.rb +37 -1
  21. data/lib/active_record/associations/builder/singular_association.rb +4 -0
  22. data/lib/active_record/associations/collection_association.rb +93 -254
  23. data/lib/active_record/associations/collection_proxy.rb +159 -122
  24. data/lib/active_record/associations/foreign_association.rb +9 -0
  25. data/lib/active_record/associations/has_many_association.rb +23 -30
  26. data/lib/active_record/associations/has_many_through_association.rb +58 -44
  27. data/lib/active_record/associations/has_one_association.rb +59 -54
  28. data/lib/active_record/associations/has_one_through_association.rb +20 -11
  29. data/lib/active_record/associations/join_dependency/join_association.rb +43 -85
  30. data/lib/active_record/associations/join_dependency/join_base.rb +10 -9
  31. data/lib/active_record/associations/join_dependency/join_part.rb +14 -14
  32. data/lib/active_record/associations/join_dependency.rb +152 -177
  33. data/lib/active_record/associations/preloader/association.rb +101 -97
  34. data/lib/active_record/associations/preloader/through_association.rb +77 -76
  35. data/lib/active_record/associations/preloader.rb +94 -103
  36. data/lib/active_record/associations/singular_association.rb +12 -45
  37. data/lib/active_record/associations/through_association.rb +27 -15
  38. data/lib/active_record/associations.rb +1603 -1592
  39. data/lib/active_record/attribute_assignment.rb +54 -61
  40. data/lib/active_record/attribute_decorators.rb +38 -17
  41. data/lib/active_record/attribute_methods/before_type_cast.rb +12 -8
  42. data/lib/active_record/attribute_methods/dirty.rb +179 -109
  43. data/lib/active_record/attribute_methods/primary_key.rb +85 -92
  44. data/lib/active_record/attribute_methods/query.rb +4 -3
  45. data/lib/active_record/attribute_methods/read.rb +20 -49
  46. data/lib/active_record/attribute_methods/serialization.rb +29 -7
  47. data/lib/active_record/attribute_methods/time_zone_conversion.rb +39 -66
  48. data/lib/active_record/attribute_methods/write.rb +34 -33
  49. data/lib/active_record/attribute_methods.rb +66 -106
  50. data/lib/active_record/attributes.rb +38 -25
  51. data/lib/active_record/autosave_association.rb +58 -39
  52. data/lib/active_record/base.rb +27 -24
  53. data/lib/active_record/callbacks.rb +64 -35
  54. data/lib/active_record/coders/json.rb +2 -0
  55. data/lib/active_record/coders/yaml_column.rb +34 -13
  56. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +558 -323
  57. data/lib/active_record/connection_adapters/abstract/database_limits.rb +23 -5
  58. data/lib/active_record/connection_adapters/abstract/database_statements.rb +215 -94
  59. data/lib/active_record/connection_adapters/abstract/query_cache.rb +59 -35
  60. data/lib/active_record/connection_adapters/abstract/quoting.rb +128 -75
  61. data/lib/active_record/connection_adapters/abstract/savepoints.rb +2 -0
  62. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +33 -28
  63. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +233 -147
  64. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +68 -80
  65. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +400 -213
  66. data/lib/active_record/connection_adapters/abstract/transaction.rb +169 -79
  67. data/lib/active_record/connection_adapters/abstract_adapter.rb +373 -202
  68. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +401 -562
  69. data/lib/active_record/connection_adapters/column.rb +41 -13
  70. data/lib/active_record/connection_adapters/connection_specification.rb +172 -139
  71. data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +11 -4
  72. data/lib/active_record/connection_adapters/mysql/column.rb +8 -31
  73. data/lib/active_record/connection_adapters/mysql/database_statements.rb +137 -49
  74. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +24 -23
  75. data/lib/active_record/connection_adapters/mysql/quoting.rb +50 -20
  76. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +49 -45
  77. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +58 -56
  78. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +70 -36
  79. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +268 -0
  80. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +12 -13
  81. data/lib/active_record/connection_adapters/mysql2_adapter.rb +48 -30
  82. data/lib/active_record/connection_adapters/postgresql/column.rb +19 -31
  83. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +64 -54
  84. data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +5 -3
  85. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +22 -11
  86. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +6 -5
  87. data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +2 -0
  88. data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +2 -0
  89. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +3 -1
  90. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +23 -0
  91. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +12 -2
  92. data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +3 -1
  93. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +5 -4
  94. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +19 -18
  95. data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +2 -0
  96. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +3 -11
  97. data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +44 -0
  98. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +7 -5
  99. data/lib/active_record/connection_adapters/postgresql/oid/{json.rb → oid.rb} +6 -1
  100. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +30 -9
  101. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +52 -30
  102. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +4 -1
  103. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +58 -54
  104. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +8 -4
  105. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +2 -0
  106. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +2 -0
  107. data/lib/active_record/connection_adapters/postgresql/oid.rb +24 -21
  108. data/lib/active_record/connection_adapters/postgresql/quoting.rb +95 -35
  109. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +20 -26
  110. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +76 -0
  111. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +147 -105
  112. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +34 -32
  113. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +378 -308
  114. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +26 -25
  115. data/lib/active_record/connection_adapters/postgresql/utils.rb +9 -6
  116. data/lib/active_record/connection_adapters/postgresql_adapter.rb +383 -275
  117. data/lib/active_record/connection_adapters/schema_cache.rb +46 -12
  118. data/lib/active_record/connection_adapters/sql_type_metadata.rb +13 -8
  119. data/lib/active_record/connection_adapters/sqlite3/database_statements.rb +119 -0
  120. data/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +3 -1
  121. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +72 -18
  122. data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +3 -8
  123. data/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb +19 -0
  124. data/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb +18 -0
  125. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +137 -0
  126. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +261 -267
  127. data/lib/active_record/connection_adapters/statement_pool.rb +9 -8
  128. data/lib/active_record/connection_handling.rb +143 -40
  129. data/lib/active_record/core.rb +207 -160
  130. data/lib/active_record/counter_cache.rb +60 -28
  131. data/lib/active_record/database_configurations/database_config.rb +37 -0
  132. data/lib/active_record/database_configurations/hash_config.rb +50 -0
  133. data/lib/active_record/database_configurations/url_config.rb +78 -0
  134. data/lib/active_record/database_configurations.rb +233 -0
  135. data/lib/active_record/define_callbacks.rb +22 -0
  136. data/lib/active_record/dynamic_matchers.rb +87 -87
  137. data/lib/active_record/enum.rb +67 -23
  138. data/lib/active_record/errors.rb +114 -18
  139. data/lib/active_record/explain.rb +4 -4
  140. data/lib/active_record/explain_registry.rb +3 -1
  141. data/lib/active_record/explain_subscriber.rb +9 -4
  142. data/lib/active_record/fixture_set/file.rb +13 -8
  143. data/lib/active_record/fixture_set/model_metadata.rb +33 -0
  144. data/lib/active_record/fixture_set/render_context.rb +17 -0
  145. data/lib/active_record/fixture_set/table_row.rb +152 -0
  146. data/lib/active_record/fixture_set/table_rows.rb +46 -0
  147. data/lib/active_record/fixtures.rb +194 -504
  148. data/lib/active_record/gem_version.rb +5 -3
  149. data/lib/active_record/inheritance.rb +150 -99
  150. data/lib/active_record/insert_all.rb +179 -0
  151. data/lib/active_record/integration.rb +116 -25
  152. data/lib/active_record/internal_metadata.rb +16 -19
  153. data/lib/active_record/legacy_yaml_adapter.rb +4 -2
  154. data/lib/active_record/locking/optimistic.rb +85 -86
  155. data/lib/active_record/locking/pessimistic.rb +18 -6
  156. data/lib/active_record/log_subscriber.rb +48 -29
  157. data/lib/active_record/middleware/database_selector/resolver/session.rb +45 -0
  158. data/lib/active_record/middleware/database_selector/resolver.rb +87 -0
  159. data/lib/active_record/middleware/database_selector.rb +74 -0
  160. data/lib/active_record/migration/command_recorder.rb +134 -100
  161. data/lib/active_record/migration/compatibility.rb +174 -56
  162. data/lib/active_record/migration/join_table.rb +8 -7
  163. data/lib/active_record/migration.rb +369 -302
  164. data/lib/active_record/model_schema.rb +160 -127
  165. data/lib/active_record/nested_attributes.rb +213 -202
  166. data/lib/active_record/no_touching.rb +12 -3
  167. data/lib/active_record/null_relation.rb +12 -34
  168. data/lib/active_record/persistence.rb +446 -77
  169. data/lib/active_record/query_cache.rb +13 -12
  170. data/lib/active_record/querying.rb +37 -24
  171. data/lib/active_record/railtie.rb +128 -36
  172. data/lib/active_record/railties/collection_cache_association_loading.rb +34 -0
  173. data/lib/active_record/railties/console_sandbox.rb +2 -0
  174. data/lib/active_record/railties/controller_runtime.rb +34 -33
  175. data/lib/active_record/railties/databases.rake +312 -177
  176. data/lib/active_record/readonly_attributes.rb +5 -4
  177. data/lib/active_record/reflection.rb +214 -254
  178. data/lib/active_record/relation/batches/batch_enumerator.rb +3 -1
  179. data/lib/active_record/relation/batches.rb +98 -52
  180. data/lib/active_record/relation/calculations.rb +212 -173
  181. data/lib/active_record/relation/delegation.rb +73 -69
  182. data/lib/active_record/relation/finder_methods.rb +207 -247
  183. data/lib/active_record/relation/from_clause.rb +6 -8
  184. data/lib/active_record/relation/merger.rb +82 -61
  185. data/lib/active_record/relation/predicate_builder/array_handler.rb +20 -14
  186. data/lib/active_record/relation/predicate_builder/association_query_value.rb +43 -0
  187. data/lib/active_record/relation/predicate_builder/base_handler.rb +4 -3
  188. data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +6 -4
  189. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +53 -0
  190. data/lib/active_record/relation/predicate_builder/range_handler.rb +7 -18
  191. data/lib/active_record/relation/predicate_builder/relation_handler.rb +6 -0
  192. data/lib/active_record/relation/predicate_builder.rb +83 -105
  193. data/lib/active_record/relation/query_attribute.rb +33 -2
  194. data/lib/active_record/relation/query_methods.rb +488 -332
  195. data/lib/active_record/relation/record_fetch_warning.rb +5 -3
  196. data/lib/active_record/relation/spawn_methods.rb +8 -8
  197. data/lib/active_record/relation/where_clause.rb +111 -96
  198. data/lib/active_record/relation/where_clause_factory.rb +6 -11
  199. data/lib/active_record/relation.rb +443 -318
  200. data/lib/active_record/result.rb +69 -40
  201. data/lib/active_record/runtime_registry.rb +5 -3
  202. data/lib/active_record/sanitization.rb +83 -99
  203. data/lib/active_record/schema.rb +7 -14
  204. data/lib/active_record/schema_dumper.rb +71 -69
  205. data/lib/active_record/schema_migration.rb +16 -6
  206. data/lib/active_record/scoping/default.rb +92 -95
  207. data/lib/active_record/scoping/named.rb +51 -26
  208. data/lib/active_record/scoping.rb +20 -20
  209. data/lib/active_record/secure_token.rb +4 -2
  210. data/lib/active_record/serialization.rb +2 -0
  211. data/lib/active_record/statement_cache.rb +63 -28
  212. data/lib/active_record/store.rb +121 -41
  213. data/lib/active_record/suppressor.rb +6 -3
  214. data/lib/active_record/table_metadata.rb +39 -18
  215. data/lib/active_record/tasks/database_tasks.rb +271 -81
  216. data/lib/active_record/tasks/mysql_database_tasks.rb +54 -91
  217. data/lib/active_record/tasks/postgresql_database_tasks.rb +77 -47
  218. data/lib/active_record/tasks/sqlite_database_tasks.rb +33 -16
  219. data/lib/active_record/test_databases.rb +23 -0
  220. data/lib/active_record/test_fixtures.rb +243 -0
  221. data/lib/active_record/timestamp.rb +70 -36
  222. data/lib/active_record/touch_later.rb +8 -6
  223. data/lib/active_record/transactions.rb +141 -157
  224. data/lib/active_record/translation.rb +3 -1
  225. data/lib/active_record/type/adapter_specific_registry.rb +44 -48
  226. data/lib/active_record/type/date.rb +2 -0
  227. data/lib/active_record/type/date_time.rb +2 -0
  228. data/lib/active_record/type/decimal_without_scale.rb +15 -0
  229. data/lib/active_record/type/hash_lookup_type_map.rb +5 -4
  230. data/lib/active_record/type/internal/timezone.rb +2 -0
  231. data/lib/active_record/type/json.rb +30 -0
  232. data/lib/active_record/type/serialized.rb +16 -9
  233. data/lib/active_record/type/text.rb +11 -0
  234. data/lib/active_record/type/time.rb +12 -1
  235. data/lib/active_record/type/type_map.rb +14 -17
  236. data/lib/active_record/type/unsigned_integer.rb +16 -0
  237. data/lib/active_record/type.rb +23 -18
  238. data/lib/active_record/type_caster/connection.rb +17 -12
  239. data/lib/active_record/type_caster/map.rb +5 -4
  240. data/lib/active_record/type_caster.rb +4 -2
  241. data/lib/active_record/validations/absence.rb +2 -0
  242. data/lib/active_record/validations/associated.rb +3 -2
  243. data/lib/active_record/validations/length.rb +2 -0
  244. data/lib/active_record/validations/presence.rb +4 -2
  245. data/lib/active_record/validations/uniqueness.rb +29 -42
  246. data/lib/active_record/validations.rb +7 -5
  247. data/lib/active_record/version.rb +3 -1
  248. data/lib/active_record.rb +37 -22
  249. data/lib/arel/alias_predication.rb +9 -0
  250. data/lib/arel/attributes/attribute.rb +37 -0
  251. data/lib/arel/attributes.rb +22 -0
  252. data/lib/arel/collectors/bind.rb +24 -0
  253. data/lib/arel/collectors/composite.rb +31 -0
  254. data/lib/arel/collectors/plain_string.rb +20 -0
  255. data/lib/arel/collectors/sql_string.rb +20 -0
  256. data/lib/arel/collectors/substitute_binds.rb +28 -0
  257. data/lib/arel/crud.rb +42 -0
  258. data/lib/arel/delete_manager.rb +18 -0
  259. data/lib/arel/errors.rb +9 -0
  260. data/lib/arel/expressions.rb +29 -0
  261. data/lib/arel/factory_methods.rb +49 -0
  262. data/lib/arel/insert_manager.rb +49 -0
  263. data/lib/arel/math.rb +45 -0
  264. data/lib/arel/nodes/and.rb +32 -0
  265. data/lib/arel/nodes/ascending.rb +23 -0
  266. data/lib/arel/nodes/binary.rb +52 -0
  267. data/lib/arel/nodes/bind_param.rb +36 -0
  268. data/lib/arel/nodes/case.rb +55 -0
  269. data/lib/arel/nodes/casted.rb +50 -0
  270. data/lib/arel/nodes/comment.rb +29 -0
  271. data/lib/arel/nodes/count.rb +12 -0
  272. data/lib/arel/nodes/delete_statement.rb +45 -0
  273. data/lib/arel/nodes/descending.rb +23 -0
  274. data/lib/arel/nodes/equality.rb +18 -0
  275. data/lib/arel/nodes/extract.rb +24 -0
  276. data/lib/arel/nodes/false.rb +16 -0
  277. data/lib/arel/nodes/full_outer_join.rb +8 -0
  278. data/lib/arel/nodes/function.rb +44 -0
  279. data/lib/arel/nodes/grouping.rb +8 -0
  280. data/lib/arel/nodes/in.rb +8 -0
  281. data/lib/arel/nodes/infix_operation.rb +80 -0
  282. data/lib/arel/nodes/inner_join.rb +8 -0
  283. data/lib/arel/nodes/insert_statement.rb +37 -0
  284. data/lib/arel/nodes/join_source.rb +20 -0
  285. data/lib/arel/nodes/matches.rb +18 -0
  286. data/lib/arel/nodes/named_function.rb +23 -0
  287. data/lib/arel/nodes/node.rb +50 -0
  288. data/lib/arel/nodes/node_expression.rb +13 -0
  289. data/lib/arel/nodes/outer_join.rb +8 -0
  290. data/lib/arel/nodes/over.rb +15 -0
  291. data/lib/arel/nodes/regexp.rb +16 -0
  292. data/lib/arel/nodes/right_outer_join.rb +8 -0
  293. data/lib/arel/nodes/select_core.rb +67 -0
  294. data/lib/arel/nodes/select_statement.rb +41 -0
  295. data/lib/arel/nodes/sql_literal.rb +16 -0
  296. data/lib/arel/nodes/string_join.rb +11 -0
  297. data/lib/arel/nodes/table_alias.rb +27 -0
  298. data/lib/arel/nodes/terminal.rb +16 -0
  299. data/lib/arel/nodes/true.rb +16 -0
  300. data/lib/arel/nodes/unary.rb +45 -0
  301. data/lib/arel/nodes/unary_operation.rb +20 -0
  302. data/lib/arel/nodes/unqualified_column.rb +22 -0
  303. data/lib/arel/nodes/update_statement.rb +41 -0
  304. data/lib/arel/nodes/values_list.rb +9 -0
  305. data/lib/arel/nodes/window.rb +126 -0
  306. data/lib/arel/nodes/with.rb +11 -0
  307. data/lib/arel/nodes.rb +68 -0
  308. data/lib/arel/order_predications.rb +13 -0
  309. data/lib/arel/predications.rb +256 -0
  310. data/lib/arel/select_manager.rb +271 -0
  311. data/lib/arel/table.rb +110 -0
  312. data/lib/arel/tree_manager.rb +72 -0
  313. data/lib/arel/update_manager.rb +34 -0
  314. data/lib/arel/visitors/depth_first.rb +203 -0
  315. data/lib/arel/visitors/dot.rb +296 -0
  316. data/lib/arel/visitors/ibm_db.rb +34 -0
  317. data/lib/arel/visitors/informix.rb +62 -0
  318. data/lib/arel/visitors/mssql.rb +156 -0
  319. data/lib/arel/visitors/mysql.rb +83 -0
  320. data/lib/arel/visitors/oracle.rb +158 -0
  321. data/lib/arel/visitors/oracle12.rb +65 -0
  322. data/lib/arel/visitors/postgresql.rb +109 -0
  323. data/lib/arel/visitors/sqlite.rb +38 -0
  324. data/lib/arel/visitors/to_sql.rb +888 -0
  325. data/lib/arel/visitors/visitor.rb +45 -0
  326. data/lib/arel/visitors/where_sql.rb +22 -0
  327. data/lib/arel/visitors.rb +20 -0
  328. data/lib/arel/window_predications.rb +9 -0
  329. data/lib/arel.rb +62 -0
  330. data/lib/rails/generators/active_record/application_record/application_record_generator.rb +26 -0
  331. data/lib/rails/generators/active_record/migration/migration_generator.rb +37 -35
  332. data/lib/rails/generators/active_record/migration/templates/{create_table_migration.rb → create_table_migration.rb.tt} +1 -1
  333. data/lib/rails/generators/active_record/migration/templates/{migration.rb → migration.rb.tt} +4 -2
  334. data/lib/rails/generators/active_record/migration.rb +17 -3
  335. data/lib/rails/generators/active_record/model/model_generator.rb +9 -30
  336. data/lib/rails/generators/active_record/model/templates/{model.rb → model.rb.tt} +10 -1
  337. data/lib/rails/generators/active_record.rb +7 -5
  338. metadata +138 -52
  339. data/lib/active_record/associations/preloader/belongs_to.rb +0 -17
  340. data/lib/active_record/associations/preloader/collection_association.rb +0 -17
  341. data/lib/active_record/associations/preloader/has_many.rb +0 -17
  342. data/lib/active_record/associations/preloader/has_many_through.rb +0 -19
  343. data/lib/active_record/associations/preloader/has_one.rb +0 -15
  344. data/lib/active_record/associations/preloader/has_one_through.rb +0 -9
  345. data/lib/active_record/associations/preloader/singular_association.rb +0 -20
  346. data/lib/active_record/attribute/user_provided_default.rb +0 -28
  347. data/lib/active_record/attribute.rb +0 -213
  348. data/lib/active_record/attribute_mutation_tracker.rb +0 -70
  349. data/lib/active_record/attribute_set/builder.rb +0 -132
  350. data/lib/active_record/attribute_set.rb +0 -110
  351. data/lib/active_record/collection_cache_key.rb +0 -50
  352. data/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb +0 -50
  353. data/lib/active_record/railties/jdbcmysql_error.rb +0 -16
  354. data/lib/active_record/relation/predicate_builder/association_query_handler.rb +0 -88
  355. data/lib/active_record/relation/predicate_builder/class_handler.rb +0 -27
  356. data/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb +0 -57
  357. data/lib/active_record/type/internal/abstract_json.rb +0 -33
  358. /data/lib/rails/generators/active_record/{model/templates/application_record.rb → application_record/templates/application_record.rb.tt} +0 -0
  359. /data/lib/rails/generators/active_record/model/templates/{module.rb → module.rb.tt} +0 -0
@@ -1,16 +1,17 @@
1
- require "arel/collectors/bind"
1
+ # frozen_string_literal: true
2
2
 
3
3
  module ActiveRecord
4
4
  # = Active Record \Relation
5
5
  class Relation
6
6
  MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
7
- :order, :joins, :left_joins, :left_outer_joins, :references,
8
- :extending, :unscope]
7
+ :order, :joins, :left_outer_joins, :references,
8
+ :extending, :unscope, :optimizer_hints, :annotate]
9
9
 
10
10
  SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :reordering,
11
- :reverse_order, :distinct, :create_with]
11
+ :reverse_order, :distinct, :create_with, :skip_query_cache]
12
+
12
13
  CLAUSE_METHODS = [:where, :having, :from]
13
- INVALID_METHODS_FOR_DELETE_ALL = [:limit, :distinct, :offset, :group, :having]
14
+ INVALID_METHODS_FOR_DELETE_ALL = [:distinct, :group, :having]
14
15
 
15
16
  VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS + CLAUSE_METHODS
16
17
 
@@ -18,95 +19,39 @@ module ActiveRecord
18
19
  include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
19
20
 
20
21
  attr_reader :table, :klass, :loaded, :predicate_builder
22
+ attr_accessor :skip_preloading_value
21
23
  alias :model :klass
22
24
  alias :loaded? :loaded
25
+ alias :locked? :lock_value
23
26
 
24
- def initialize(klass, table, predicate_builder, values = {})
27
+ def initialize(klass, table: klass.arel_table, predicate_builder: klass.predicate_builder, values: {})
25
28
  @klass = klass
26
29
  @table = table
27
30
  @values = values
28
31
  @offsets = {}
29
32
  @loaded = false
30
33
  @predicate_builder = predicate_builder
34
+ @delegate_to_klass = false
31
35
  end
32
36
 
33
37
  def initialize_copy(other)
34
- # This method is a hot spot, so for now, use Hash[] to dup the hash.
35
- # https://bugs.ruby-lang.org/issues/7166
36
- @values = Hash[@values]
38
+ @values = @values.dup
37
39
  reset
38
40
  end
39
41
 
40
- def insert(values) # :nodoc:
41
- primary_key_value = nil
42
-
43
- if primary_key && Hash === values
44
- primary_key_value = values[values.keys.find { |k|
45
- k.name == primary_key
46
- }]
47
-
48
- if !primary_key_value && klass.prefetch_primary_key?
49
- primary_key_value = klass.next_sequence_value
50
- values[arel_attribute(klass.primary_key)] = primary_key_value
51
- end
52
- end
53
-
54
- im = arel.create_insert
55
- im.into @table
56
-
57
- substitutes, binds = substitute_values values
58
-
59
- if values.empty? # empty insert
60
- im.values = Arel.sql(connection.empty_insert_statement_value)
61
- else
62
- im.insert substitutes
63
- end
64
-
65
- @klass.connection.insert(
66
- im,
67
- 'SQL',
68
- primary_key,
69
- primary_key_value,
70
- nil,
71
- binds)
72
- end
73
-
74
- def _update_record(values, id, id_was) # :nodoc:
75
- substitutes, binds = substitute_values values
76
-
77
- scope = @klass.unscoped
78
-
79
- if @klass.finder_needs_type_condition?
80
- scope.unscope!(where: @klass.inheritance_column)
81
- end
82
-
83
- relation = scope.where(@klass.primary_key => (id_was || id))
84
- bvs = binds + relation.bound_attributes
85
- um = relation
86
- .arel
87
- .compile_update(substitutes, @klass.primary_key)
88
-
89
- @klass.connection.update(
90
- um,
91
- 'SQL',
92
- bvs,
93
- )
42
+ def arel_attribute(name) # :nodoc:
43
+ klass.arel_attribute(name, table)
94
44
  end
95
45
 
96
- def substitute_values(values) # :nodoc:
97
- binds = []
98
- substitutes = []
99
-
100
- values.each do |arel_attr, value|
101
- binds.push QueryAttribute.new(arel_attr.name, value, klass.type_for_attribute(arel_attr.name))
102
- substitutes.push [arel_attr, Arel::Nodes::BindParam.new]
46
+ def bind_attribute(name, value) # :nodoc:
47
+ if reflection = klass._reflect_on_association(name)
48
+ name = reflection.foreign_key
49
+ value = value.read_attribute(reflection.klass.primary_key) unless value.nil?
103
50
  end
104
51
 
105
- [substitutes, binds]
106
- end
107
-
108
- def arel_attribute(name) # :nodoc:
109
- klass.arel_attribute(name, table)
52
+ attr = arel_attribute(name)
53
+ bind = predicate_builder.build_bind_attribute(attr.name, value)
54
+ yield attr, bind
110
55
  end
111
56
 
112
57
  # Initializes new record from relation while maintaining the current
@@ -121,8 +66,9 @@ module ActiveRecord
121
66
  #
122
67
  # user = users.new { |user| user.name = 'Oscar' }
123
68
  # user.name # => Oscar
124
- def new(*args, &block)
125
- scoping { @klass.new(*args, &block) }
69
+ def new(attributes = nil, &block)
70
+ block = _deprecated_scope_block("new", &block)
71
+ scoping { klass.new(attributes, &block) }
126
72
  end
127
73
 
128
74
  alias build new
@@ -146,8 +92,13 @@ module ActiveRecord
146
92
  #
147
93
  # users.create(name: nil) # validation on name
148
94
  # # => #<User id: nil, name: nil, ...>
149
- def create(*args, &block)
150
- scoping { @klass.create(*args, &block) }
95
+ def create(attributes = nil, &block)
96
+ if attributes.is_a?(Array)
97
+ attributes.collect { |attr| create(attr, &block) }
98
+ else
99
+ block = _deprecated_scope_block("create", &block)
100
+ scoping { klass.create(attributes, &block) }
101
+ end
151
102
  end
152
103
 
153
104
  # Similar to #create, but calls
@@ -156,8 +107,13 @@ module ActiveRecord
156
107
  #
157
108
  # Expects arguments in the same format as
158
109
  # {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!].
159
- def create!(*args, &block)
160
- scoping { @klass.create!(*args, &block) }
110
+ def create!(attributes = nil, &block)
111
+ if attributes.is_a?(Array)
112
+ attributes.collect { |attr| create!(attr, &block) }
113
+ else
114
+ block = _deprecated_scope_block("create!", &block)
115
+ scoping { klass.create!(attributes, &block) }
116
+ end
161
117
  end
162
118
 
163
119
  def first_or_create(attributes = nil, &block) # :nodoc:
@@ -203,23 +159,12 @@ module ActiveRecord
203
159
  # failed due to validation errors it won't be persisted, you get what
204
160
  # #create returns in such situation.
205
161
  #
206
- # Please note *this method is not atomic*, it runs first a SELECT, and if
162
+ # Please note <b>this method is not atomic</b>, it runs first a SELECT, and if
207
163
  # there are no results an INSERT is attempted. If there are other threads
208
164
  # or processes there is a race condition between both calls and it could
209
165
  # be the case that you end up with two similar records.
210
166
  #
211
- # Whether that is a problem or not depends on the logic of the
212
- # application, but in the particular case in which rows have a UNIQUE
213
- # constraint an exception may be raised, just retry:
214
- #
215
- # begin
216
- # CreditAccount.transaction(requires_new: true) do
217
- # CreditAccount.find_or_create_by(user_id: user.id)
218
- # end
219
- # rescue ActiveRecord::RecordNotUnique
220
- # retry
221
- # end
222
- #
167
+ # If this might be a problem for your application, please see #create_or_find_by.
223
168
  def find_or_create_by(attributes, &block)
224
169
  find_by(attributes) || create(attributes, &block)
225
170
  end
@@ -231,6 +176,51 @@ module ActiveRecord
231
176
  find_by(attributes) || create!(attributes, &block)
232
177
  end
233
178
 
179
+ # Attempts to create a record with the given attributes in a table that has a unique constraint
180
+ # on one or several of its columns. If a row already exists with one or several of these
181
+ # unique constraints, the exception such an insertion would normally raise is caught,
182
+ # and the existing record with those attributes is found using #find_by!.
183
+ #
184
+ # This is similar to #find_or_create_by, but avoids the problem of stale reads between the SELECT
185
+ # and the INSERT, as that method needs to first query the table, then attempt to insert a row
186
+ # if none is found.
187
+ #
188
+ # There are several drawbacks to #create_or_find_by, though:
189
+ #
190
+ # * The underlying table must have the relevant columns defined with unique constraints.
191
+ # * A unique constraint violation may be triggered by only one, or at least less than all,
192
+ # of the given attributes. This means that the subsequent #find_by! may fail to find a
193
+ # matching record, which will then raise an <tt>ActiveRecord::RecordNotFound</tt> exception,
194
+ # rather than a record with the given attributes.
195
+ # * While we avoid the race condition between SELECT -> INSERT from #find_or_create_by,
196
+ # we actually have another race condition between INSERT -> SELECT, which can be triggered
197
+ # if a DELETE between those two statements is run by another client. But for most applications,
198
+ # that's a significantly less likely condition to hit.
199
+ # * It relies on exception handling to handle control flow, which may be marginally slower.
200
+ # * The primary key may auto-increment on each create, even if it fails. This can accelerate
201
+ # the problem of running out of integers, if the underlying table is still stuck on a primary
202
+ # key of type int (note: All Rails apps since 5.1+ have defaulted to bigint, which is not liable
203
+ # to this problem).
204
+ #
205
+ # This method will return a record if all given attributes are covered by unique constraints
206
+ # (unless the INSERT -> DELETE -> SELECT race condition is triggered), but if creation was attempted
207
+ # and failed due to validation errors it won't be persisted, you get what #create returns in
208
+ # such situation.
209
+ def create_or_find_by(attributes, &block)
210
+ transaction(requires_new: true) { create(attributes, &block) }
211
+ rescue ActiveRecord::RecordNotUnique
212
+ find_by!(attributes)
213
+ end
214
+
215
+ # Like #create_or_find_by, but calls
216
+ # {create!}[rdoc-ref:Persistence::ClassMethods#create!] so an exception
217
+ # is raised if the created record is invalid.
218
+ def create_or_find_by!(attributes, &block)
219
+ transaction(requires_new: true) { create!(attributes, &block) }
220
+ rescue ActiveRecord::RecordNotUnique
221
+ find_by!(attributes)
222
+ end
223
+
234
224
  # Like #find_or_create_by, but calls {new}[rdoc-ref:Core#new]
235
225
  # instead of {create}[rdoc-ref:Persistence::ClassMethods#create].
236
226
  def find_or_initialize_by(attributes, &block)
@@ -245,16 +235,16 @@ module ActiveRecord
245
235
  # are needed by the next ones when eager loading is going on.
246
236
  #
247
237
  # Please see further details in the
248
- # {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
238
+ # {Active Record Query Interface guide}[https://guides.rubyonrails.org/active_record_querying.html#running-explain].
249
239
  def explain
250
- #TODO: Fix for binds.
251
240
  exec_explain(collecting_queries_for_explain { exec_queries })
252
241
  end
253
242
 
254
243
  # Converts relation objects to Array.
255
- def to_a
244
+ def to_ary
256
245
  records.dup
257
246
  end
247
+ alias to_a to_ary
258
248
 
259
249
  def records # :nodoc:
260
250
  load
@@ -266,10 +256,6 @@ module ActiveRecord
266
256
  coder.represent_seq(nil, records)
267
257
  end
268
258
 
269
- def as_json(options = nil) #:nodoc:
270
- records.as_json(options)
271
- end
272
-
273
259
  # Returns size of the records.
274
260
  def size
275
261
  loaded? ? @records.length : count(:all)
@@ -278,13 +264,7 @@ module ActiveRecord
278
264
  # Returns true if there are no records.
279
265
  def empty?
280
266
  return @records.empty? if loaded?
281
-
282
- if limit_value == 0
283
- true
284
- else
285
- c = count(:all)
286
- c.respond_to?(:zero?) ? c.zero? : c.empty?
287
- end
267
+ !exists?
288
268
  end
289
269
 
290
270
  # Returns true if there are no records.
@@ -311,30 +291,107 @@ module ActiveRecord
311
291
  limit_value ? records.many? : size > 1
312
292
  end
313
293
 
314
- # Returns a cache key that can be used to identify the records fetched by
315
- # this query. The cache key is built with a fingerprint of the sql query,
316
- # the number of records matched by the query and a timestamp of the last
317
- # updated record. When a new record comes to match the query, or any of
318
- # the existing records is updated or deleted, the cache key changes.
294
+ # Returns a stable cache key that can be used to identify this query.
295
+ # The cache key is built with a fingerprint of the SQL query.
319
296
  #
320
- # Product.where("name like ?", "%Cosmic Encounter%").cache_key
321
- # # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000"
297
+ # Product.where("name like ?", "%Cosmic Encounter%").cache_key
298
+ # # => "products/query-1850ab3d302391b85b8693e941286659"
322
299
  #
323
- # If the collection is loaded, the method will iterate through the records
324
- # to generate the timestamp, otherwise it will trigger one SQL query like:
300
+ # If ActiveRecord::Base.collection_cache_versioning is turned off, as it was
301
+ # in Rails 6.0 and earlier, the cache key will also include a version.
325
302
  #
326
- # SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%')
303
+ # ActiveRecord::Base.collection_cache_versioning = false
304
+ # Product.where("name like ?", "%Cosmic Encounter%").cache_key
305
+ # # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000"
327
306
  #
328
307
  # You can also pass a custom timestamp column to fetch the timestamp of the
329
308
  # last updated record.
330
309
  #
331
310
  # Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at)
332
- #
333
- # You can customize the strategy to generate the key on a per model basis
334
- # overriding ActiveRecord::Base#collection_cache_key.
335
311
  def cache_key(timestamp_column = :updated_at)
336
312
  @cache_keys ||= {}
337
- @cache_keys[timestamp_column] ||= @klass.collection_cache_key(self, timestamp_column)
313
+ @cache_keys[timestamp_column] ||= klass.collection_cache_key(self, timestamp_column)
314
+ end
315
+
316
+ def compute_cache_key(timestamp_column = :updated_at) # :nodoc:
317
+ query_signature = ActiveSupport::Digest.hexdigest(to_sql)
318
+ key = "#{klass.model_name.cache_key}/query-#{query_signature}"
319
+
320
+ if cache_version(timestamp_column)
321
+ key
322
+ else
323
+ "#{key}-#{compute_cache_version(timestamp_column)}"
324
+ end
325
+ end
326
+ private :compute_cache_key
327
+
328
+ # Returns a cache version that can be used together with the cache key to form
329
+ # a recyclable caching scheme. The cache version is built with the number of records
330
+ # matching the query, and the timestamp of the last updated record. When a new record
331
+ # comes to match the query, or any of the existing records is updated or deleted,
332
+ # the cache version changes.
333
+ #
334
+ # If the collection is loaded, the method will iterate through the records
335
+ # to generate the timestamp, otherwise it will trigger one SQL query like:
336
+ #
337
+ # SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%')
338
+ def cache_version(timestamp_column = :updated_at)
339
+ if collection_cache_versioning
340
+ @cache_versions ||= {}
341
+ @cache_versions[timestamp_column] ||= compute_cache_version(timestamp_column)
342
+ end
343
+ end
344
+
345
+ def compute_cache_version(timestamp_column) # :nodoc:
346
+ if loaded? || distinct_value
347
+ size = records.size
348
+ if size > 0
349
+ timestamp = max_by(&timestamp_column)._read_attribute(timestamp_column)
350
+ end
351
+ else
352
+ collection = eager_loading? ? apply_join_dependency : self
353
+
354
+ column = connection.visitor.compile(arel_attribute(timestamp_column))
355
+ select_values = "COUNT(*) AS #{connection.quote_column_name("size")}, MAX(%s) AS timestamp"
356
+
357
+ if collection.has_limit_or_offset?
358
+ query = collection.select("#{column} AS collection_cache_key_timestamp")
359
+ subquery_alias = "subquery_for_cache_key"
360
+ subquery_column = "#{subquery_alias}.collection_cache_key_timestamp"
361
+ arel = query.build_subquery(subquery_alias, select_values % subquery_column)
362
+ else
363
+ query = collection.unscope(:order)
364
+ query.select_values = [select_values % column]
365
+ arel = query.arel
366
+ end
367
+
368
+ result = connection.select_one(arel, nil)
369
+
370
+ if result
371
+ column_type = klass.type_for_attribute(timestamp_column)
372
+ timestamp = column_type.deserialize(result["timestamp"])
373
+ size = result["size"]
374
+ else
375
+ timestamp = nil
376
+ size = 0
377
+ end
378
+ end
379
+
380
+ if timestamp
381
+ "#{size}-#{timestamp.utc.to_s(cache_timestamp_format)}"
382
+ else
383
+ "#{size}"
384
+ end
385
+ end
386
+ private :compute_cache_version
387
+
388
+ # Returns a cache key along with the version.
389
+ def cache_key_with_version
390
+ if version = cache_version
391
+ "#{cache_key}-#{version}"
392
+ else
393
+ cache_key
394
+ end
338
395
  end
339
396
 
340
397
  # Scope all queries to the current scope.
@@ -347,10 +404,14 @@ module ActiveRecord
347
404
  # Please check unscoped if you want to remove all previous scopes (including
348
405
  # the default_scope) during the execution of a block.
349
406
  def scoping
350
- previous, klass.current_scope = klass.current_scope(true), self
351
- yield
407
+ already_in_scope? ? yield : _scoping(self) { yield }
408
+ end
409
+
410
+ def _exec_scope(name, *args, &block) # :nodoc:
411
+ @delegate_to_klass = true
412
+ _scoping(_deprecated_spawn(name)) { instance_exec(*args, &block) || self }
352
413
  ensure
353
- klass.current_scope = previous
414
+ @delegate_to_klass = false
354
415
  end
355
416
 
356
417
  # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
@@ -358,6 +419,8 @@ module ActiveRecord
358
419
  # trigger Active Record callbacks or validations. However, values passed to #update_all will still go through
359
420
  # Active Record's normal type casting and serialization.
360
421
  #
422
+ # Note: As Active Record callbacks are not triggered, this method will not automatically update +updated_at+/+updated_on+ columns.
423
+ #
361
424
  # ==== Parameters
362
425
  #
363
426
  # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
@@ -378,66 +441,87 @@ module ActiveRecord
378
441
  def update_all(updates)
379
442
  raise ArgumentError, "Empty list of attributes to change" if updates.blank?
380
443
 
444
+ if eager_loading?
445
+ relation = apply_join_dependency
446
+ return relation.update_all(updates)
447
+ end
448
+
381
449
  stmt = Arel::UpdateManager.new
450
+ stmt.table(arel.join_sources.empty? ? table : arel.source)
451
+ stmt.key = arel_attribute(primary_key)
452
+ stmt.take(arel.limit)
453
+ stmt.offset(arel.offset)
454
+ stmt.order(*arel.orders)
455
+ stmt.wheres = arel.constraints
456
+
457
+ if updates.is_a?(Hash)
458
+ if klass.locking_enabled? &&
459
+ !updates.key?(klass.locking_column) &&
460
+ !updates.key?(klass.locking_column.to_sym)
461
+ attr = arel_attribute(klass.locking_column)
462
+ updates[attr.name] = _increment_attribute(attr)
463
+ end
464
+ stmt.set _substitute_values(updates)
465
+ else
466
+ stmt.set Arel.sql(klass.sanitize_sql_for_assignment(updates, table.name))
467
+ end
382
468
 
383
- stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
384
- stmt.table(table)
469
+ @klass.connection.update stmt, "#{@klass} Update All"
470
+ end
385
471
 
386
- if joins_values.any?
387
- @klass.connection.join_to_update(stmt, arel, arel_attribute(primary_key))
472
+ def update(id = :all, attributes) # :nodoc:
473
+ if id == :all
474
+ each { |record| record.update(attributes) }
388
475
  else
389
- stmt.key = arel_attribute(primary_key)
390
- stmt.take(arel.limit)
391
- stmt.order(*arel.orders)
392
- stmt.wheres = arel.constraints
476
+ klass.update(id, attributes)
477
+ end
478
+ end
479
+
480
+ def update_counters(counters) # :nodoc:
481
+ touch = counters.delete(:touch)
482
+
483
+ updates = {}
484
+ counters.each do |counter_name, value|
485
+ attr = arel_attribute(counter_name)
486
+ updates[attr.name] = _increment_attribute(attr, value)
393
487
  end
394
488
 
395
- @klass.connection.update stmt, 'SQL', bound_attributes
489
+ if touch
490
+ names = touch if touch != true
491
+ names = Array.wrap(names)
492
+ options = names.extract_options!
493
+ touch_updates = klass.touch_attributes_with_time(*names, **options)
494
+ updates.merge!(touch_updates) unless touch_updates.empty?
495
+ end
496
+
497
+ update_all updates
396
498
  end
397
499
 
398
- # Updates an object (or multiple objects) and saves it to the database, if validations pass.
399
- # The resulting object is returned whether the object was saved successfully to the database or not.
500
+ # Touches all records in the current relation, setting the +updated_at+/+updated_on+ attributes to the current time or the time specified.
501
+ # It does not instantiate the involved models, and it does not trigger Active Record callbacks or validations.
502
+ # This method can be passed attribute names and an optional time argument.
503
+ # If attribute names are passed, they are updated along with +updated_at+/+updated_on+ attributes.
504
+ # If no time argument is passed, the current time is used as default.
400
505
  #
401
- # ==== Parameters
506
+ # === Examples
402
507
  #
403
- # * +id+ - This should be the id or an array of ids to be updated.
404
- # * +attributes+ - This should be a hash of attributes or an array of hashes.
508
+ # # Touch all records
509
+ # Person.all.touch_all
510
+ # # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670'"
405
511
  #
406
- # ==== Examples
512
+ # # Touch multiple records with a custom attribute
513
+ # Person.all.touch_all(:created_at)
514
+ # # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670', \"created_at\" = '2018-01-04 22:55:23.132670'"
407
515
  #
408
- # # Updates one record
409
- # Person.update(15, user_name: 'Samuel', group: 'expert')
410
- #
411
- # # Updates multiple records
412
- # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
413
- # Person.update(people.keys, people.values)
414
- #
415
- # # Updates multiple records from the result of a relation
416
- # people = Person.where(group: 'expert')
417
- # people.update(group: 'masters')
418
- #
419
- # Note: Updating a large number of records will run an
420
- # UPDATE query for each record, which may cause a performance
421
- # issue. So if it is not needed to run callbacks for each update, it is
422
- # preferred to use #update_all for updating all records using
423
- # a single query.
424
- def update(id = :all, attributes)
425
- if id.is_a?(Array)
426
- id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) }
427
- elsif id == :all
428
- records.each { |record| record.update(attributes) }
429
- else
430
- if ActiveRecord::Base === id
431
- id = id.id
432
- ActiveSupport::Deprecation.warn(<<-MSG.squish)
433
- You are passing an instance of ActiveRecord::Base to `update`.
434
- Please pass the id of the object by calling `.id`.
435
- MSG
436
- end
437
- object = find(id)
438
- object.update(attributes)
439
- object
440
- end
516
+ # # Touch multiple records with a specified time
517
+ # Person.all.touch_all(time: Time.new(2020, 5, 16, 0, 0, 0))
518
+ # # => "UPDATE \"people\" SET \"updated_at\" = '2020-05-16 00:00:00'"
519
+ #
520
+ # # Touch records with scope
521
+ # Person.where(name: 'David').touch_all
522
+ # # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670' WHERE \"people\".\"name\" = 'David'"
523
+ def touch_all(*names, time: nil)
524
+ update_all klass.touch_attributes_with_time(*names, time: time)
441
525
  end
442
526
 
443
527
  # Destroys the records by instantiating each
@@ -456,43 +540,8 @@ module ActiveRecord
456
540
  # ==== Examples
457
541
  #
458
542
  # Person.where(age: 0..18).destroy_all
459
- def destroy_all(conditions = nil)
460
- if conditions
461
- ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
462
- Passing conditions to destroy_all is deprecated and will be removed in Rails 5.1.
463
- To achieve the same use where(conditions).destroy_all.
464
- MESSAGE
465
- where(conditions).destroy_all
466
- else
467
- records.each(&:destroy).tap { reset }
468
- end
469
- end
470
-
471
- # Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
472
- # therefore all callbacks and filters are fired off before the object is deleted. This method is
473
- # less efficient than #delete but allows cleanup methods and other actions to be run.
474
- #
475
- # This essentially finds the object (or multiple objects) with the given id, creates a new object
476
- # from the attributes, and then calls destroy on it.
477
- #
478
- # ==== Parameters
479
- #
480
- # * +id+ - Can be either an Integer or an Array of Integers.
481
- #
482
- # ==== Examples
483
- #
484
- # # Destroy a single object
485
- # Todo.destroy(1)
486
- #
487
- # # Destroy multiple objects
488
- # todos = [1,2,3]
489
- # Todo.destroy(todos)
490
- def destroy(id)
491
- if id.is_a?(Array)
492
- id.map { |one_id| destroy(one_id) }
493
- else
494
- find(id).destroy
495
- end
543
+ def destroy_all
544
+ records.each(&:destroy).tap { reset }
496
545
  end
497
546
 
498
547
  # Deletes the records without instantiating the records
@@ -511,66 +560,60 @@ module ActiveRecord
511
560
  #
512
561
  # If an invalid method is supplied, #delete_all raises an ActiveRecordError:
513
562
  #
514
- # Post.limit(100).delete_all
515
- # # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit
516
- def delete_all(conditions = nil)
517
- invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select { |method|
518
- if MULTI_VALUE_METHODS.include?(method)
519
- send("#{method}_values").any?
520
- elsif SINGLE_VALUE_METHODS.include?(method)
521
- send("#{method}_value")
522
- elsif CLAUSE_METHODS.include?(method)
523
- send("#{method}_clause").any?
524
- end
525
- }
563
+ # Post.distinct.delete_all
564
+ # # => ActiveRecord::ActiveRecordError: delete_all doesn't support distinct
565
+ def delete_all
566
+ invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select do |method|
567
+ value = @values[method]
568
+ method == :distinct ? value : value&.any?
569
+ end
526
570
  if invalid_methods.any?
527
571
  raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
528
572
  end
529
573
 
530
- if conditions
531
- ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
532
- Passing conditions to delete_all is deprecated and will be removed in Rails 5.1.
533
- To achieve the same use where(conditions).delete_all.
534
- MESSAGE
535
- where(conditions).delete_all
536
- else
537
- stmt = Arel::DeleteManager.new
538
- stmt.from(table)
574
+ if eager_loading?
575
+ relation = apply_join_dependency
576
+ return relation.delete_all
577
+ end
539
578
 
540
- if joins_values.any?
541
- @klass.connection.join_to_delete(stmt, arel, arel_attribute(primary_key))
542
- else
543
- stmt.wheres = arel.constraints
544
- end
579
+ stmt = Arel::DeleteManager.new
580
+ stmt.from(arel.join_sources.empty? ? table : arel.source)
581
+ stmt.key = arel_attribute(primary_key)
582
+ stmt.take(arel.limit)
583
+ stmt.offset(arel.offset)
584
+ stmt.order(*arel.orders)
585
+ stmt.wheres = arel.constraints
545
586
 
546
- affected = @klass.connection.delete(stmt, 'SQL', bound_attributes)
587
+ affected = @klass.connection.delete(stmt, "#{@klass} Destroy")
547
588
 
548
- reset
549
- affected
550
- end
589
+ reset
590
+ affected
551
591
  end
552
592
 
553
- # Deletes the row with a primary key matching the +id+ argument, using a
554
- # SQL +DELETE+ statement, and returns the number of rows deleted. Active
555
- # Record objects are not instantiated, so the object's callbacks are not
556
- # executed, including any <tt>:dependent</tt> association options.
557
- #
558
- # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
593
+ # Finds and destroys all records matching the specified conditions.
594
+ # This is short-hand for <tt>relation.where(condition).destroy_all</tt>.
595
+ # Returns the collection of objects that were destroyed.
559
596
  #
560
- # Note: Although it is often much faster than the alternative,
561
- # #destroy, skipping callbacks might bypass business logic in
562
- # your application that ensures referential integrity or performs other
563
- # essential jobs.
597
+ # If no record is found, returns empty array.
564
598
  #
565
- # ==== Examples
599
+ # Person.destroy_by(id: 13)
600
+ # Person.destroy_by(name: 'Spartacus', rating: 4)
601
+ # Person.destroy_by("published_at < ?", 2.weeks.ago)
602
+ def destroy_by(*args)
603
+ where(*args).destroy_all
604
+ end
605
+
606
+ # Finds and deletes all records matching the specified conditions.
607
+ # This is short-hand for <tt>relation.where(condition).delete_all</tt>.
608
+ # Returns the number of rows affected.
566
609
  #
567
- # # Delete a single row
568
- # Todo.delete(1)
610
+ # If no record is found, returns <tt>0</tt> as zero rows were affected.
569
611
  #
570
- # # Delete multiple rows
571
- # Todo.delete([2,3,4])
572
- def delete(id_or_array)
573
- where(primary_key => id_or_array).delete_all
612
+ # Person.delete_by(id: 13)
613
+ # Person.delete_by(name: 'Spartacus', rating: 4)
614
+ # Person.delete_by("published_at < ?", 2.weeks.ago)
615
+ def delete_by(*args)
616
+ where(*args).delete_all
574
617
  end
575
618
 
576
619
  # Causes the records to be loaded from the database if they have not
@@ -592,10 +635,12 @@ module ActiveRecord
592
635
  end
593
636
 
594
637
  def reset
595
- @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
596
- @should_eager_load = @join_dependency = nil
638
+ @delegate_to_klass = false
639
+ @_deprecated_scope_source = nil
640
+ @to_sql = @arel = @loaded = @should_eager_load = nil
597
641
  @records = [].freeze
598
642
  @offsets = {}
643
+ @take = nil
599
644
  self
600
645
  end
601
646
 
@@ -605,32 +650,31 @@ module ActiveRecord
605
650
  # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
606
651
  def to_sql
607
652
  @to_sql ||= begin
608
- relation = self
609
- connection = klass.connection
610
- visitor = connection.visitor
611
-
612
- if eager_loading?
613
- find_with_associations { |rel| relation = rel }
614
- end
615
-
616
- binds = relation.bound_attributes
617
- binds = connection.prepare_binds_for_database(binds)
618
- binds.map! { |value| connection.quote(value) }
619
- collect = visitor.accept(relation.arel.ast, Arel::Collectors::Bind.new)
620
- collect.substitute_binds(binds).join
621
- end
653
+ if eager_loading?
654
+ apply_join_dependency do |relation, join_dependency|
655
+ relation = join_dependency.apply_column_aliases(relation)
656
+ relation.to_sql
657
+ end
658
+ else
659
+ conn = klass.connection
660
+ conn.unprepared_statement { conn.to_sql(arel) }
661
+ end
662
+ end
622
663
  end
623
664
 
624
665
  # Returns a hash of where conditions.
625
666
  #
626
667
  # User.where(name: 'Oscar').where_values_hash
627
668
  # # => {name: "Oscar"}
628
- def where_values_hash(relation_table_name = table_name)
669
+ def where_values_hash(relation_table_name = klass.table_name)
629
670
  where_clause.to_h(relation_table_name)
630
671
  end
631
672
 
632
673
  def scope_for_create
633
- @scope_for_create ||= where_values_hash.merge(create_with_value)
674
+ hash = where_values_hash
675
+ hash.delete(klass.inheritance_column) if klass.finder_needs_type_condition?
676
+ create_with_value.each { |k, v| hash[k.to_s] = v } unless create_with_value.empty?
677
+ hash
634
678
  end
635
679
 
636
680
  # Returns true if relation needs eager loading.
@@ -648,15 +692,6 @@ module ActiveRecord
648
692
  includes_values & joins_values
649
693
  end
650
694
 
651
- # {#uniq}[rdoc-ref:QueryMethods#uniq] and
652
- # {#uniq!}[rdoc-ref:QueryMethods#uniq!] are silently deprecated.
653
- # #uniq_value delegates to #distinct_value to maintain backwards compatibility.
654
- # Use #distinct_value instead.
655
- def uniq_value
656
- distinct_value
657
- end
658
- deprecate uniq_value: :distinct_value
659
-
660
695
  # Compares two relations for equality.
661
696
  def ==(other)
662
697
  case other
@@ -670,7 +705,7 @@ module ActiveRecord
670
705
  end
671
706
 
672
707
  def pretty_print(q)
673
- q.pp(self.records)
708
+ q.pp(records)
674
709
  end
675
710
 
676
711
  # Returns true if relation is blank.
@@ -679,12 +714,14 @@ module ActiveRecord
679
714
  end
680
715
 
681
716
  def values
682
- Hash[@values]
717
+ @values.dup
683
718
  end
684
719
 
685
720
  def inspect
686
- entries = records.take([limit_value, 11].compact.min).map!(&:inspect)
687
- entries[10] = '...' if entries.size == 11
721
+ subject = loaded? ? records : self
722
+ entries = subject.take([limit_value, 11].compact.min).map!(&:inspect)
723
+
724
+ entries[10] = "..." if entries.size == 11
688
725
 
689
726
  "#<#{self.class.name} [#{entries.join(', ')}]>"
690
727
  end
@@ -693,57 +730,145 @@ module ActiveRecord
693
730
  @values == klass.unscoped.values
694
731
  end
695
732
 
733
+ def has_limit_or_offset? # :nodoc:
734
+ limit_value || offset_value
735
+ end
736
+
737
+ def alias_tracker(joins = [], aliases = nil) # :nodoc:
738
+ joins += [aliases] if aliases
739
+ ActiveRecord::Associations::AliasTracker.create(connection, table.name, joins)
740
+ end
741
+
742
+ def preload_associations(records) # :nodoc:
743
+ preload = preload_values
744
+ preload += includes_values unless eager_loading?
745
+ preloader = nil
746
+ preload.each do |associations|
747
+ preloader ||= build_preloader
748
+ preloader.preload records, associations
749
+ end
750
+ end
751
+
752
+ attr_reader :_deprecated_scope_source # :nodoc:
753
+
696
754
  protected
755
+ attr_writer :_deprecated_scope_source # :nodoc:
697
756
 
698
757
  def load_records(records)
699
758
  @records = records.freeze
700
759
  @loaded = true
701
760
  end
702
761
 
762
+ def null_relation? # :nodoc:
763
+ is_a?(NullRelation)
764
+ end
765
+
703
766
  private
767
+ def already_in_scope?
768
+ @delegate_to_klass && begin
769
+ scope = klass.current_scope(true)
770
+ scope && !scope._deprecated_scope_source
771
+ end
772
+ end
773
+
774
+ def _deprecated_spawn(name)
775
+ spawn.tap { |scope| scope._deprecated_scope_source = name }
776
+ end
704
777
 
705
- def exec_queries(&block)
706
- @records = eager_loading? ? find_with_associations.freeze : @klass.find_by_sql(arel, bound_attributes, &block).freeze
778
+ def _deprecated_scope_block(name, &block)
779
+ -> record do
780
+ klass.current_scope = _deprecated_spawn(name)
781
+ yield record if block_given?
782
+ end
783
+ end
707
784
 
708
- preload = preload_values
709
- preload += includes_values unless eager_loading?
710
- preloader = build_preloader
711
- preload.each do |associations|
712
- preloader.preload @records, associations
785
+ def _scoping(scope)
786
+ previous, klass.current_scope = klass.current_scope(true), scope
787
+ yield
788
+ ensure
789
+ klass.current_scope = previous
713
790
  end
714
791
 
715
- @records.each(&:readonly!) if readonly_value
792
+ def _substitute_values(values)
793
+ values.map do |name, value|
794
+ attr = arel_attribute(name)
795
+ unless Arel.arel_node?(value)
796
+ type = klass.type_for_attribute(attr.name)
797
+ value = predicate_builder.build_bind_attribute(attr.name, type.cast(value))
798
+ end
799
+ [attr, value]
800
+ end
801
+ end
716
802
 
717
- @loaded = true
718
- @records
719
- end
803
+ def _increment_attribute(attribute, value = 1)
804
+ bind = predicate_builder.build_bind_attribute(attribute.name, value.abs)
805
+ expr = table.coalesce(Arel::Nodes::UnqualifiedColumn.new(attribute), 0)
806
+ expr = value < 0 ? expr - bind : expr + bind
807
+ expr.expr
808
+ end
720
809
 
721
- def build_preloader
722
- ActiveRecord::Associations::Preloader.new
723
- end
810
+ def exec_queries(&block)
811
+ skip_query_cache_if_necessary do
812
+ @records =
813
+ if eager_loading?
814
+ apply_join_dependency do |relation, join_dependency|
815
+ if relation.null_relation?
816
+ []
817
+ else
818
+ relation = join_dependency.apply_column_aliases(relation)
819
+ rows = connection.select_all(relation.arel, "SQL")
820
+ join_dependency.instantiate(rows, &block)
821
+ end.freeze
822
+ end
823
+ else
824
+ klass.find_by_sql(arel, &block).freeze
825
+ end
826
+
827
+ preload_associations(@records) unless skip_preloading_value
828
+
829
+ @records.each(&:readonly!) if readonly_value
830
+
831
+ @loaded = true
832
+ @records
833
+ end
834
+ end
724
835
 
725
- def references_eager_loaded_tables?
726
- joined_tables = arel.join_sources.map do |join|
727
- if join.is_a?(Arel::Nodes::StringJoin)
728
- tables_in_string(join.left)
836
+ def skip_query_cache_if_necessary
837
+ if skip_query_cache_value
838
+ uncached do
839
+ yield
840
+ end
729
841
  else
730
- [join.left.table_name, join.left.table_alias]
842
+ yield
731
843
  end
732
844
  end
733
845
 
734
- joined_tables += [table.name, table.table_alias]
846
+ def build_preloader
847
+ ActiveRecord::Associations::Preloader.new
848
+ end
735
849
 
736
- # always convert table names to downcase as in Oracle quoted table names are in uppercase
737
- joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
850
+ def references_eager_loaded_tables?
851
+ joined_tables = arel.join_sources.map do |join|
852
+ if join.is_a?(Arel::Nodes::StringJoin)
853
+ tables_in_string(join.left)
854
+ else
855
+ [join.left.table_name, join.left.table_alias]
856
+ end
857
+ end
738
858
 
739
- (references_values - joined_tables).any?
740
- end
859
+ joined_tables += [table.name, table.table_alias]
741
860
 
742
- def tables_in_string(string)
743
- return [] if string.blank?
744
- # always convert table names to downcase as in Oracle quoted table names are in uppercase
745
- # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
746
- string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ['raw_sql_']
747
- end
861
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
862
+ joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
863
+
864
+ (references_values - joined_tables).any?
865
+ end
866
+
867
+ def tables_in_string(string)
868
+ return [] if string.blank?
869
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
870
+ # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
871
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"]
872
+ end
748
873
  end
749
874
  end