activerecord 4.2.11.2 → 6.0.0

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