activerecord 4.2.11.1 → 6.0.3

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 (373) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +711 -1547
  3. data/MIT-LICENSE +4 -2
  4. data/README.rdoc +14 -13
  5. data/examples/performance.rb +33 -32
  6. data/examples/simple.rb +5 -4
  7. data/lib/active_record/advisory_lock_base.rb +18 -0
  8. data/lib/active_record/aggregations.rb +266 -251
  9. data/lib/active_record/association_relation.rb +20 -13
  10. data/lib/active_record/associations/alias_tracker.rb +29 -36
  11. data/lib/active_record/associations/association.rb +128 -57
  12. data/lib/active_record/associations/association_scope.rb +103 -132
  13. data/lib/active_record/associations/belongs_to_association.rb +65 -60
  14. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +8 -12
  15. data/lib/active_record/associations/builder/association.rb +27 -40
  16. data/lib/active_record/associations/builder/belongs_to.rb +69 -55
  17. data/lib/active_record/associations/builder/collection_association.rb +10 -33
  18. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +50 -66
  19. data/lib/active_record/associations/builder/has_many.rb +8 -4
  20. data/lib/active_record/associations/builder/has_one.rb +46 -5
  21. data/lib/active_record/associations/builder/singular_association.rb +16 -10
  22. data/lib/active_record/associations/collection_association.rb +136 -288
  23. data/lib/active_record/associations/collection_proxy.rb +241 -147
  24. data/lib/active_record/associations/foreign_association.rb +10 -1
  25. data/lib/active_record/associations/has_many_association.rb +34 -98
  26. data/lib/active_record/associations/has_many_through_association.rb +60 -87
  27. data/lib/active_record/associations/has_one_association.rb +61 -49
  28. data/lib/active_record/associations/has_one_through_association.rb +20 -11
  29. data/lib/active_record/associations/join_dependency/join_association.rb +38 -86
  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 +149 -166
  33. data/lib/active_record/associations/preloader/association.rb +90 -123
  34. data/lib/active_record/associations/preloader/through_association.rb +85 -65
  35. data/lib/active_record/associations/preloader.rb +90 -93
  36. data/lib/active_record/associations/singular_association.rb +18 -39
  37. data/lib/active_record/associations/through_association.rb +38 -18
  38. data/lib/active_record/associations.rb +1737 -1597
  39. data/lib/active_record/attribute_assignment.rb +57 -185
  40. data/lib/active_record/attribute_decorators.rb +39 -17
  41. data/lib/active_record/attribute_methods/before_type_cast.rb +13 -9
  42. data/lib/active_record/attribute_methods/dirty.rb +174 -144
  43. data/lib/active_record/attribute_methods/primary_key.rb +90 -84
  44. data/lib/active_record/attribute_methods/query.rb +6 -5
  45. data/lib/active_record/attribute_methods/read.rb +20 -77
  46. data/lib/active_record/attribute_methods/serialization.rb +40 -21
  47. data/lib/active_record/attribute_methods/time_zone_conversion.rb +57 -37
  48. data/lib/active_record/attribute_methods/write.rb +32 -55
  49. data/lib/active_record/attribute_methods.rb +120 -135
  50. data/lib/active_record/attributes.rb +213 -82
  51. data/lib/active_record/autosave_association.rb +97 -41
  52. data/lib/active_record/base.rb +57 -45
  53. data/lib/active_record/callbacks.rb +101 -76
  54. data/lib/active_record/coders/json.rb +3 -1
  55. data/lib/active_record/coders/yaml_column.rb +23 -12
  56. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +804 -297
  57. data/lib/active_record/connection_adapters/abstract/database_limits.rb +26 -8
  58. data/lib/active_record/connection_adapters/abstract/database_statements.rb +240 -115
  59. data/lib/active_record/connection_adapters/abstract/query_cache.rb +83 -24
  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 -47
  63. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +371 -242
  64. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +79 -36
  65. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +694 -256
  66. data/lib/active_record/connection_adapters/abstract/transaction.rb +190 -83
  67. data/lib/active_record/connection_adapters/abstract_adapter.rb +473 -202
  68. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +507 -639
  69. data/lib/active_record/connection_adapters/column.rb +56 -43
  70. data/lib/active_record/connection_adapters/connection_specification.rb +174 -153
  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 +196 -0
  74. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +71 -0
  75. data/lib/active_record/connection_adapters/mysql/quoting.rb +81 -0
  76. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +71 -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 -181
  82. data/lib/active_record/connection_adapters/postgresql/column.rb +21 -11
  83. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +70 -114
  84. data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +44 -0
  85. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +49 -58
  86. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +9 -8
  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 +4 -2
  89. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +5 -1
  90. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +13 -1
  91. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +9 -22
  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 +31 -20
  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 -9
  99. data/lib/active_record/connection_adapters/postgresql/oid/{infinity.rb → oid.rb} +5 -3
  100. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +32 -11
  101. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +51 -34
  102. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +4 -5
  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 +9 -5
  105. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +3 -1
  106. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +3 -1
  107. data/lib/active_record/connection_adapters/postgresql/oid.rb +23 -25
  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 +49 -0
  113. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +462 -296
  114. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +36 -0
  115. data/lib/active_record/connection_adapters/postgresql/utils.rb +11 -8
  116. data/lib/active_record/connection_adapters/postgresql_adapter.rb +558 -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 +119 -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 +102 -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 +299 -349
  127. data/lib/active_record/connection_adapters/statement_pool.rb +33 -13
  128. data/lib/active_record/connection_handling.rb +167 -41
  129. data/lib/active_record/core.rb +252 -230
  130. data/lib/active_record/counter_cache.rb +70 -49
  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 -106
  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 +22 -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 +152 -0
  146. data/lib/active_record/fixture_set/table_rows.rb +46 -0
  147. data/lib/active_record/fixtures.rb +227 -501
  148. data/lib/active_record/gem_version.rb +6 -4
  149. data/lib/active_record/inheritance.rb +158 -115
  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 +86 -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/resolver/session.rb +45 -0
  159. data/lib/active_record/middleware/database_selector/resolver.rb +87 -0
  160. data/lib/active_record/middleware/database_selector.rb +74 -0
  161. data/lib/active_record/migration/command_recorder.rb +166 -91
  162. data/lib/active_record/migration/compatibility.rb +244 -0
  163. data/lib/active_record/migration/join_table.rb +8 -7
  164. data/lib/active_record/migration.rb +623 -305
  165. data/lib/active_record/model_schema.rb +313 -112
  166. data/lib/active_record/nested_attributes.rb +263 -223
  167. data/lib/active_record/no_touching.rb +15 -2
  168. data/lib/active_record/null_relation.rb +24 -38
  169. data/lib/active_record/persistence.rb +557 -126
  170. data/lib/active_record/query_cache.rb +19 -23
  171. data/lib/active_record/querying.rb +44 -30
  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 +331 -185
  177. data/lib/active_record/readonly_attributes.rb +5 -4
  178. data/lib/active_record/reflection.rb +430 -281
  179. data/lib/active_record/relation/batches/batch_enumerator.rb +69 -0
  180. data/lib/active_record/relation/batches.rb +206 -55
  181. data/lib/active_record/relation/calculations.rb +268 -254
  182. data/lib/active_record/relation/delegation.rb +75 -84
  183. data/lib/active_record/relation/finder_methods.rb +285 -241
  184. data/lib/active_record/relation/from_clause.rb +30 -0
  185. data/lib/active_record/relation/merger.rb +78 -88
  186. data/lib/active_record/relation/predicate_builder/array_handler.rb +27 -26
  187. data/lib/active_record/relation/predicate_builder/association_query_value.rb +43 -0
  188. data/lib/active_record/relation/predicate_builder/base_handler.rb +18 -0
  189. data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +19 -0
  190. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +53 -0
  191. data/lib/active_record/relation/predicate_builder/range_handler.rb +22 -0
  192. data/lib/active_record/relation/predicate_builder/relation_handler.rb +7 -1
  193. data/lib/active_record/relation/predicate_builder.rb +110 -119
  194. data/lib/active_record/relation/query_attribute.rb +50 -0
  195. data/lib/active_record/relation/query_methods.rb +603 -397
  196. data/lib/active_record/relation/record_fetch_warning.rb +51 -0
  197. data/lib/active_record/relation/spawn_methods.rb +11 -14
  198. data/lib/active_record/relation/where_clause.rb +189 -0
  199. data/lib/active_record/relation/where_clause_factory.rb +33 -0
  200. data/lib/active_record/relation.rb +530 -341
  201. data/lib/active_record/result.rb +79 -43
  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/default.rb +98 -83
  208. data/lib/active_record/scoping/named.rb +86 -33
  209. data/lib/active_record/scoping.rb +45 -27
  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 +90 -0
  216. data/lib/active_record/tasks/database_tasks.rb +307 -100
  217. data/lib/active_record/tasks/mysql_database_tasks.rb +55 -100
  218. data/lib/active_record/tasks/postgresql_database_tasks.rb +80 -41
  219. data/lib/active_record/tasks/sqlite_database_tasks.rb +37 -16
  220. data/lib/active_record/test_databases.rb +23 -0
  221. data/lib/active_record/test_fixtures.rb +225 -0
  222. data/lib/active_record/timestamp.rb +86 -41
  223. data/lib/active_record/touch_later.rb +65 -0
  224. data/lib/active_record/transactions.rb +223 -157
  225. data/lib/active_record/translation.rb +3 -1
  226. data/lib/active_record/type/adapter_specific_registry.rb +126 -0
  227. data/lib/active_record/type/date.rb +4 -45
  228. data/lib/active_record/type/date_time.rb +4 -49
  229. data/lib/active_record/type/decimal_without_scale.rb +6 -2
  230. data/lib/active_record/type/hash_lookup_type_map.rb +5 -4
  231. data/lib/active_record/type/internal/timezone.rb +17 -0
  232. data/lib/active_record/type/json.rb +30 -0
  233. data/lib/active_record/type/serialized.rb +23 -15
  234. data/lib/active_record/type/text.rb +2 -2
  235. data/lib/active_record/type/time.rb +11 -16
  236. data/lib/active_record/type/type_map.rb +16 -19
  237. data/lib/active_record/type/unsigned_integer.rb +9 -8
  238. data/lib/active_record/type.rb +77 -23
  239. data/lib/active_record/type_caster/connection.rb +34 -0
  240. data/lib/active_record/type_caster/map.rb +20 -0
  241. data/lib/active_record/type_caster.rb +9 -0
  242. data/lib/active_record/validations/absence.rb +25 -0
  243. data/lib/active_record/validations/associated.rb +12 -4
  244. data/lib/active_record/validations/length.rb +26 -0
  245. data/lib/active_record/validations/presence.rb +14 -13
  246. data/lib/active_record/validations/uniqueness.rb +42 -55
  247. data/lib/active_record/validations.rb +38 -35
  248. data/lib/active_record/version.rb +3 -1
  249. data/lib/active_record.rb +42 -22
  250. data/lib/arel/alias_predication.rb +9 -0
  251. data/lib/arel/attributes/attribute.rb +37 -0
  252. data/lib/arel/attributes.rb +22 -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/and.rb +32 -0
  266. data/lib/arel/nodes/ascending.rb +23 -0
  267. data/lib/arel/nodes/binary.rb +52 -0
  268. data/lib/arel/nodes/bind_param.rb +36 -0
  269. data/lib/arel/nodes/case.rb +55 -0
  270. data/lib/arel/nodes/casted.rb +50 -0
  271. data/lib/arel/nodes/comment.rb +29 -0
  272. data/lib/arel/nodes/count.rb +12 -0
  273. data/lib/arel/nodes/delete_statement.rb +45 -0
  274. data/lib/arel/nodes/descending.rb +23 -0
  275. data/lib/arel/nodes/equality.rb +18 -0
  276. data/lib/arel/nodes/extract.rb +24 -0
  277. data/lib/arel/nodes/false.rb +16 -0
  278. data/lib/arel/nodes/full_outer_join.rb +8 -0
  279. data/lib/arel/nodes/function.rb +44 -0
  280. data/lib/arel/nodes/grouping.rb +8 -0
  281. data/lib/arel/nodes/in.rb +8 -0
  282. data/lib/arel/nodes/infix_operation.rb +80 -0
  283. data/lib/arel/nodes/inner_join.rb +8 -0
  284. data/lib/arel/nodes/insert_statement.rb +37 -0
  285. data/lib/arel/nodes/join_source.rb +20 -0
  286. data/lib/arel/nodes/matches.rb +18 -0
  287. data/lib/arel/nodes/named_function.rb +23 -0
  288. data/lib/arel/nodes/node.rb +50 -0
  289. data/lib/arel/nodes/node_expression.rb +13 -0
  290. data/lib/arel/nodes/outer_join.rb +8 -0
  291. data/lib/arel/nodes/over.rb +15 -0
  292. data/lib/arel/nodes/regexp.rb +16 -0
  293. data/lib/arel/nodes/right_outer_join.rb +8 -0
  294. data/lib/arel/nodes/select_core.rb +67 -0
  295. data/lib/arel/nodes/select_statement.rb +41 -0
  296. data/lib/arel/nodes/sql_literal.rb +16 -0
  297. data/lib/arel/nodes/string_join.rb +11 -0
  298. data/lib/arel/nodes/table_alias.rb +27 -0
  299. data/lib/arel/nodes/terminal.rb +16 -0
  300. data/lib/arel/nodes/true.rb +16 -0
  301. data/lib/arel/nodes/unary.rb +45 -0
  302. data/lib/arel/nodes/unary_operation.rb +20 -0
  303. data/lib/arel/nodes/unqualified_column.rb +22 -0
  304. data/lib/arel/nodes/update_statement.rb +41 -0
  305. data/lib/arel/nodes/values_list.rb +9 -0
  306. data/lib/arel/nodes/window.rb +126 -0
  307. data/lib/arel/nodes/with.rb +11 -0
  308. data/lib/arel/nodes.rb +68 -0
  309. data/lib/arel/order_predications.rb +13 -0
  310. data/lib/arel/predications.rb +256 -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/depth_first.rb +203 -0
  316. data/lib/arel/visitors/dot.rb +296 -0
  317. data/lib/arel/visitors/ibm_db.rb +34 -0
  318. data/lib/arel/visitors/informix.rb +62 -0
  319. data/lib/arel/visitors/mssql.rb +156 -0
  320. data/lib/arel/visitors/mysql.rb +83 -0
  321. data/lib/arel/visitors/oracle.rb +158 -0
  322. data/lib/arel/visitors/oracle12.rb +65 -0
  323. data/lib/arel/visitors/postgresql.rb +109 -0
  324. data/lib/arel/visitors/sqlite.rb +38 -0
  325. data/lib/arel/visitors/to_sql.rb +888 -0
  326. data/lib/arel/visitors/visitor.rb +45 -0
  327. data/lib/arel/visitors/where_sql.rb +22 -0
  328. data/lib/arel/visitors.rb +20 -0
  329. data/lib/arel/window_predications.rb +9 -0
  330. data/lib/arel.rb +62 -0
  331. data/lib/rails/generators/active_record/application_record/application_record_generator.rb +26 -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/migration_generator.rb +42 -37
  334. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +24 -0
  335. data/lib/rails/generators/active_record/migration/templates/{migration.rb → migration.rb.tt} +11 -2
  336. data/lib/rails/generators/active_record/migration.rb +30 -1
  337. data/lib/rails/generators/active_record/model/model_generator.rb +18 -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. data/lib/rails/generators/active_record.rb +7 -5
  341. metadata +168 -59
  342. data/lib/active_record/associations/preloader/belongs_to.rb +0 -17
  343. data/lib/active_record/associations/preloader/collection_association.rb +0 -24
  344. data/lib/active_record/associations/preloader/has_many.rb +0 -17
  345. data/lib/active_record/associations/preloader/has_many_through.rb +0 -19
  346. data/lib/active_record/associations/preloader/has_one.rb +0 -23
  347. data/lib/active_record/associations/preloader/has_one_through.rb +0 -9
  348. data/lib/active_record/associations/preloader/singular_association.rb +0 -21
  349. data/lib/active_record/attribute.rb +0 -163
  350. data/lib/active_record/attribute_set/builder.rb +0 -106
  351. data/lib/active_record/attribute_set.rb +0 -81
  352. data/lib/active_record/connection_adapters/mysql_adapter.rb +0 -498
  353. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +0 -93
  354. data/lib/active_record/connection_adapters/postgresql/oid/float.rb +0 -21
  355. data/lib/active_record/connection_adapters/postgresql/oid/integer.rb +0 -11
  356. data/lib/active_record/connection_adapters/postgresql/oid/json.rb +0 -35
  357. data/lib/active_record/connection_adapters/postgresql/oid/time.rb +0 -11
  358. data/lib/active_record/railties/jdbcmysql_error.rb +0 -16
  359. data/lib/active_record/serializers/xml_serializer.rb +0 -193
  360. data/lib/active_record/type/big_integer.rb +0 -13
  361. data/lib/active_record/type/binary.rb +0 -50
  362. data/lib/active_record/type/boolean.rb +0 -31
  363. data/lib/active_record/type/decimal.rb +0 -64
  364. data/lib/active_record/type/decorator.rb +0 -14
  365. data/lib/active_record/type/float.rb +0 -19
  366. data/lib/active_record/type/integer.rb +0 -59
  367. data/lib/active_record/type/mutable.rb +0 -16
  368. data/lib/active_record/type/numeric.rb +0 -36
  369. data/lib/active_record/type/string.rb +0 -40
  370. data/lib/active_record/type/time_value.rb +0 -38
  371. data/lib/active_record/type/value.rb +0 -110
  372. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +0 -19
  373. 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)
42
+ def arel_attribute(name) # :nodoc:
43
+ klass.arel_attribute(name, table)
71
44
  end
72
45
 
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)
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?
80
50
  end
81
51
 
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
- )
93
- end
94
-
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])]
102
- end
103
-
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,30 +264,133 @@ 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
286
322
  else
287
- limit_value ? to_a.many? : size > 1
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
288
394
  end
289
395
  end
290
396
 
@@ -298,17 +404,22 @@ module ActiveRecord
298
404
  # Please check unscoped if you want to remove all previous scopes (including
299
405
  # the default_scope) during the execution of a block.
300
406
  def scoping
301
- previous, klass.current_scope = klass.current_scope, self
302
- 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 }
303
413
  ensure
304
- klass.current_scope = previous
414
+ @delegate_to_klass = false
305
415
  end
306
416
 
307
417
  # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
308
418
  # 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.
419
+ # trigger Active Record callbacks or validations. However, values passed to #update_all will still go through
420
+ # Active Record's normal type casting and serialization.
421
+ #
422
+ # Note: As Active Record callbacks are not triggered, this method will not automatically update +updated_at+/+updated_on+ columns.
312
423
  #
313
424
  # ==== Parameters
314
425
  #
@@ -324,57 +435,99 @@ module ActiveRecord
324
435
  #
325
436
  # # Update all books that match conditions, but limit it to 5 ordered by date
326
437
  # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
438
+ #
439
+ # # Update all invoices and set the number column to its id value.
440
+ # Invoice.update_all('number = id')
327
441
  def update_all(updates)
328
442
  raise ArgumentError, "Empty list of attributes to change" if updates.blank?
329
443
 
330
- stmt = Arel::UpdateManager.new(arel.engine)
444
+ if eager_loading?
445
+ relation = apply_join_dependency
446
+ return relation.update_all(updates)
447
+ end
331
448
 
332
- stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
333
- stmt.table(table)
334
- stmt.key = table[primary_key]
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
335
468
 
336
- if joins_values.any?
337
- @klass.connection.join_to_update(stmt, arel)
469
+ @klass.connection.update stmt, "#{@klass} Update All"
470
+ end
471
+
472
+ def update(id = :all, attributes) # :nodoc:
473
+ if id == :all
474
+ each { |record| record.update(attributes) }
338
475
  else
339
- stmt.take(arel.limit)
340
- stmt.order(*arel.orders)
341
- stmt.wheres = arel.constraints
476
+ klass.update(id, attributes)
342
477
  end
478
+ end
343
479
 
344
- bvs = arel.bind_values + bind_values
345
- @klass.connection.update stmt, 'SQL', bvs
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)
487
+ end
488
+
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
346
498
  end
347
499
 
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.
500
+ # Touches all records in the current relation without instantiating records first with the +updated_at+/+updated_on+ attributes
501
+ # set to the current time or the time specified.
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.
350
505
  #
351
- # ==== Parameters
506
+ # === Examples
352
507
  #
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.
508
+ # # Touch all records
509
+ # Person.all.touch_all
510
+ # # => "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670'"
355
511
  #
356
- # ==== 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'"
357
515
  #
358
- # # Updates one record
359
- # Person.update(15, user_name: 'Samuel', group: 'expert')
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'"
360
519
  #
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
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)
372
525
  end
373
526
 
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
527
+ # Destroys the records by instantiating each
528
+ # record and calling its {#destroy}[rdoc-ref:Persistence#destroy] method.
529
+ # Each object's callbacks are executed (including <tt>:dependent</tt> association options).
530
+ # Returns the collection of objects that were destroyed; each will be frozen, to
378
531
  # reflect that no changes should be made (since they can't be persisted).
379
532
  #
380
533
  # Note: Instantiation, callback execution, and deletion of each
@@ -382,127 +535,85 @@ module ActiveRecord
382
535
  # once. It generates at least one SQL +DELETE+ query per record (or
383
536
  # possibly more, to enforce your callbacks). If you want to delete many
384
537
  # 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.
538
+ # #delete_all instead.
393
539
  #
394
540
  # ==== Examples
395
541
  #
396
- # Person.destroy_all("last_login < '2004-04-04'")
397
- # Person.destroy_all(status: "inactive")
398
542
  # 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
543
+ def destroy_all
544
+ records.each(&:destroy).tap { reset }
405
545
  end
406
546
 
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
432
- end
433
-
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
547
+ # Deletes the records without instantiating the records
548
+ # first, and hence not calling the {#destroy}[rdoc-ref:Persistence#destroy]
549
+ # method nor invoking callbacks.
550
+ # This is a single SQL DELETE statement that goes straight to the database, much more
551
+ # efficient than #destroy_all. Be careful with relations though, in particular
438
552
  # <tt>:dependent</tt> rules defined on associations are not honored. Returns the
439
553
  # number of rows affected.
440
554
  #
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
555
  # Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
444
556
  #
445
557
  # Both calls delete the affected posts all at once with a single DELETE statement.
446
558
  # If you need to destroy dependent associations or call your <tt>before_*</tt> or
447
- # +after_destroy+ callbacks, use the +destroy_all+ method instead.
559
+ # +after_destroy+ callbacks, use the #destroy_all method instead.
448
560
  #
449
- # If an invalid method is supplied, +delete_all+ raises an ActiveRecord error:
561
+ # If an invalid method is supplied, #delete_all raises an ActiveRecordError:
450
562
  #
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
- }
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
461
570
  if invalid_methods.any?
462
571
  raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
463
572
  end
464
573
 
465
- if conditions
466
- where(conditions).delete_all
467
- else
468
- stmt = Arel::DeleteManager.new(arel.engine)
469
- stmt.from(table)
574
+ if eager_loading?
575
+ relation = apply_join_dependency
576
+ return relation.delete_all
577
+ end
470
578
 
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
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
476
586
 
477
- bvs = arel.bind_values + bind_values
478
- affected = @klass.connection.delete(stmt, 'SQL', bvs)
587
+ affected = @klass.connection.delete(stmt, "#{@klass} Destroy")
479
588
 
480
- reset
481
- affected
482
- end
589
+ reset
590
+ affected
483
591
  end
484
592
 
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.
489
- #
490
- # 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.
491
596
  #
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.
597
+ # If no record is found, returns empty array.
496
598
  #
497
- # ==== 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.
498
609
  #
499
- # # Delete a single row
500
- # Todo.delete(1)
610
+ # If no record is found, returns <tt>0</tt> as zero rows were affected.
501
611
  #
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
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
506
617
  end
507
618
 
508
619
  # Causes the records to be loaded from the database if they have not
@@ -511,8 +622,8 @@ module ActiveRecord
511
622
  # return value is the relation itself, not the records.
512
623
  #
513
624
  # Post.where(published: true).load # => #<ActiveRecord::Relation>
514
- def load
515
- exec_queries unless loaded?
625
+ def load(&block)
626
+ exec_queries(&block) unless loaded?
516
627
 
517
628
  self
518
629
  end
@@ -524,10 +635,12 @@ module ActiveRecord
524
635
  end
525
636
 
526
637
  def reset
527
- @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
528
- @should_eager_load = @join_dependency = nil
529
- @records = []
638
+ @delegate_to_klass = false
639
+ @_deprecated_scope_source = nil
640
+ @to_sql = @arel = @loaded = @should_eager_load = nil
641
+ @records = [].freeze
530
642
  @offsets = {}
643
+ @take = nil
531
644
  self
532
645
  end
533
646
 
@@ -537,47 +650,28 @@ module ActiveRecord
537
650
  # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
538
651
  def to_sql
539
652
  @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
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
554
663
  end
555
664
 
556
665
  # Returns a hash of where conditions.
557
666
  #
558
667
  # User.where(name: 'Oscar').where_values_hash
559
668
  # # => {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
- }]
669
+ def where_values_hash(relation_table_name = klass.table_name)
670
+ where_clause.to_h(relation_table_name)
577
671
  end
578
672
 
579
673
  def scope_for_create
580
- @scope_for_create ||= where_values_hash.merge(create_with_value)
674
+ where_values_hash.merge!(create_with_value.stringify_keys)
581
675
  end
582
676
 
583
677
  # Returns true if relation needs eager loading.
@@ -595,88 +689,183 @@ module ActiveRecord
595
689
  includes_values & joins_values
596
690
  end
597
691
 
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
692
  # Compares two relations for equality.
605
693
  def ==(other)
606
694
  case other
607
695
  when Associations::CollectionProxy, AssociationRelation
608
- self == other.to_a
696
+ self == other.records
609
697
  when Relation
610
698
  other.to_sql == to_sql
611
699
  when Array
612
- to_a == other
700
+ records == other
613
701
  end
614
702
  end
615
703
 
616
704
  def pretty_print(q)
617
- q.pp(self.to_a)
705
+ q.pp(records)
618
706
  end
619
707
 
620
708
  # Returns true if relation is blank.
621
709
  def blank?
622
- to_a.blank?
710
+ records.blank?
623
711
  end
624
712
 
625
713
  def values
626
- Hash[@values]
714
+ @values.dup
627
715
  end
628
716
 
629
717
  def inspect
630
- entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
631
- entries[10] = '...' if entries.size == 11
718
+ subject = loaded? ? records : self
719
+ entries = subject.take([limit_value, 11].compact.min).map!(&:inspect)
720
+
721
+ entries[10] = "..." if entries.size == 11
632
722
 
633
723
  "#<#{self.class.name} [#{entries.join(', ')}]>"
634
724
  end
635
725
 
636
- private
726
+ def empty_scope? # :nodoc:
727
+ @values == klass.unscoped.values
728
+ end
637
729
 
638
- def exec_queries
639
- @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, arel.bind_values + bind_values)
730
+ def has_limit_or_offset? # :nodoc:
731
+ limit_value || offset_value
732
+ end
640
733
 
734
+ def alias_tracker(joins = [], aliases = nil) # :nodoc:
735
+ joins += [aliases] if aliases
736
+ ActiveRecord::Associations::AliasTracker.create(connection, table.name, joins)
737
+ end
738
+
739
+ def preload_associations(records) # :nodoc:
641
740
  preload = preload_values
642
- preload += includes_values unless eager_loading?
643
- preloader = build_preloader
741
+ preload += includes_values unless eager_loading?
742
+ preloader = nil
644
743
  preload.each do |associations|
645
- preloader.preload @records, associations
744
+ preloader ||= build_preloader
745
+ preloader.preload records, associations
646
746
  end
747
+ end
647
748
 
648
- @records.each { |record| record.readonly! } if readonly_value
749
+ attr_reader :_deprecated_scope_source # :nodoc:
649
750
 
650
- @loaded = true
651
- @records
652
- end
751
+ protected
752
+ attr_writer :_deprecated_scope_source # :nodoc:
653
753
 
654
- def build_preloader
655
- ActiveRecord::Associations::Preloader.new
656
- end
754
+ def load_records(records)
755
+ @records = records.freeze
756
+ @loaded = true
757
+ end
758
+
759
+ def null_relation? # :nodoc:
760
+ is_a?(NullRelation)
761
+ end
762
+
763
+ private
764
+ def already_in_scope?
765
+ @delegate_to_klass && begin
766
+ scope = klass.current_scope(true)
767
+ scope && !scope._deprecated_scope_source
768
+ end
769
+ end
770
+
771
+ def _deprecated_spawn(name)
772
+ spawn.tap { |scope| scope._deprecated_scope_source = name }
773
+ end
774
+
775
+ def _deprecated_scope_block(name, &block)
776
+ -> record do
777
+ klass.current_scope = _deprecated_spawn(name)
778
+ yield record if block_given?
779
+ end
780
+ end
781
+
782
+ def _scoping(scope)
783
+ previous, klass.current_scope = klass.current_scope(true), scope
784
+ yield
785
+ ensure
786
+ klass.current_scope = previous
787
+ end
788
+
789
+ def _substitute_values(values)
790
+ values.map do |name, value|
791
+ attr = arel_attribute(name)
792
+ unless Arel.arel_node?(value)
793
+ type = klass.type_for_attribute(attr.name)
794
+ value = predicate_builder.build_bind_attribute(attr.name, type.cast(value))
795
+ end
796
+ [attr, value]
797
+ end
798
+ end
799
+
800
+ def _increment_attribute(attribute, value = 1)
801
+ bind = predicate_builder.build_bind_attribute(attribute.name, value.abs)
802
+ expr = table.coalesce(Arel::Nodes::UnqualifiedColumn.new(attribute), 0)
803
+ expr = value < 0 ? expr - bind : expr + bind
804
+ expr.expr
805
+ end
806
+
807
+ def exec_queries(&block)
808
+ skip_query_cache_if_necessary do
809
+ @records =
810
+ if eager_loading?
811
+ apply_join_dependency do |relation, join_dependency|
812
+ if relation.null_relation?
813
+ []
814
+ else
815
+ relation = join_dependency.apply_column_aliases(relation)
816
+ rows = connection.select_all(relation.arel, "SQL")
817
+ join_dependency.instantiate(rows, &block)
818
+ end.freeze
819
+ end
820
+ else
821
+ klass.find_by_sql(arel, &block).freeze
822
+ end
823
+
824
+ preload_associations(@records) unless skip_preloading_value
825
+
826
+ @records.each(&:readonly!) if readonly_value
827
+
828
+ @loaded = true
829
+ @records
830
+ end
831
+ end
657
832
 
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)
833
+ def skip_query_cache_if_necessary
834
+ if skip_query_cache_value
835
+ uncached do
836
+ yield
837
+ end
662
838
  else
663
- [join.left.table_name, join.left.table_alias]
839
+ yield
664
840
  end
665
841
  end
666
842
 
667
- joined_tables += [table.name, table.table_alias]
843
+ def build_preloader
844
+ ActiveRecord::Associations::Preloader.new
845
+ end
668
846
 
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
847
+ def references_eager_loaded_tables?
848
+ joined_tables = arel.join_sources.map do |join|
849
+ if join.is_a?(Arel::Nodes::StringJoin)
850
+ tables_in_string(join.left)
851
+ else
852
+ [join.left.table_name, join.left.table_alias]
853
+ end
854
+ end
671
855
 
672
- (references_values - joined_tables).any?
673
- end
856
+ joined_tables += [table.name, table.table_alias]
674
857
 
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
858
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
859
+ joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
860
+
861
+ (references_values - joined_tables).any?
862
+ end
863
+
864
+ def tables_in_string(string)
865
+ return [] if string.blank?
866
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
867
+ # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
868
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"]
869
+ end
681
870
  end
682
871
  end