activerecord 5.2.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 (244) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +937 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +217 -0
  5. data/examples/performance.rb +185 -0
  6. data/examples/simple.rb +15 -0
  7. data/lib/active_record.rb +188 -0
  8. data/lib/active_record/aggregations.rb +283 -0
  9. data/lib/active_record/association_relation.rb +40 -0
  10. data/lib/active_record/associations.rb +1860 -0
  11. data/lib/active_record/associations/alias_tracker.rb +81 -0
  12. data/lib/active_record/associations/association.rb +299 -0
  13. data/lib/active_record/associations/association_scope.rb +168 -0
  14. data/lib/active_record/associations/belongs_to_association.rb +130 -0
  15. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +40 -0
  16. data/lib/active_record/associations/builder/association.rb +140 -0
  17. data/lib/active_record/associations/builder/belongs_to.rb +163 -0
  18. data/lib/active_record/associations/builder/collection_association.rb +82 -0
  19. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +135 -0
  20. data/lib/active_record/associations/builder/has_many.rb +17 -0
  21. data/lib/active_record/associations/builder/has_one.rb +30 -0
  22. data/lib/active_record/associations/builder/singular_association.rb +42 -0
  23. data/lib/active_record/associations/collection_association.rb +513 -0
  24. data/lib/active_record/associations/collection_proxy.rb +1131 -0
  25. data/lib/active_record/associations/foreign_association.rb +13 -0
  26. data/lib/active_record/associations/has_many_association.rb +144 -0
  27. data/lib/active_record/associations/has_many_through_association.rb +227 -0
  28. data/lib/active_record/associations/has_one_association.rb +120 -0
  29. data/lib/active_record/associations/has_one_through_association.rb +45 -0
  30. data/lib/active_record/associations/join_dependency.rb +262 -0
  31. data/lib/active_record/associations/join_dependency/join_association.rb +60 -0
  32. data/lib/active_record/associations/join_dependency/join_base.rb +23 -0
  33. data/lib/active_record/associations/join_dependency/join_part.rb +71 -0
  34. data/lib/active_record/associations/preloader.rb +193 -0
  35. data/lib/active_record/associations/preloader/association.rb +131 -0
  36. data/lib/active_record/associations/preloader/through_association.rb +107 -0
  37. data/lib/active_record/associations/singular_association.rb +73 -0
  38. data/lib/active_record/associations/through_association.rb +121 -0
  39. data/lib/active_record/attribute_assignment.rb +88 -0
  40. data/lib/active_record/attribute_decorators.rb +90 -0
  41. data/lib/active_record/attribute_methods.rb +492 -0
  42. data/lib/active_record/attribute_methods/before_type_cast.rb +78 -0
  43. data/lib/active_record/attribute_methods/dirty.rb +150 -0
  44. data/lib/active_record/attribute_methods/primary_key.rb +143 -0
  45. data/lib/active_record/attribute_methods/query.rb +42 -0
  46. data/lib/active_record/attribute_methods/read.rb +85 -0
  47. data/lib/active_record/attribute_methods/serialization.rb +90 -0
  48. data/lib/active_record/attribute_methods/time_zone_conversion.rb +91 -0
  49. data/lib/active_record/attribute_methods/write.rb +68 -0
  50. data/lib/active_record/attributes.rb +266 -0
  51. data/lib/active_record/autosave_association.rb +498 -0
  52. data/lib/active_record/base.rb +329 -0
  53. data/lib/active_record/callbacks.rb +353 -0
  54. data/lib/active_record/coders/json.rb +15 -0
  55. data/lib/active_record/coders/yaml_column.rb +50 -0
  56. data/lib/active_record/collection_cache_key.rb +53 -0
  57. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +1068 -0
  58. data/lib/active_record/connection_adapters/abstract/database_limits.rb +72 -0
  59. data/lib/active_record/connection_adapters/abstract/database_statements.rb +540 -0
  60. data/lib/active_record/connection_adapters/abstract/query_cache.rb +145 -0
  61. data/lib/active_record/connection_adapters/abstract/quoting.rb +200 -0
  62. data/lib/active_record/connection_adapters/abstract/savepoints.rb +23 -0
  63. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +146 -0
  64. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +685 -0
  65. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +95 -0
  66. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +1396 -0
  67. data/lib/active_record/connection_adapters/abstract/transaction.rb +283 -0
  68. data/lib/active_record/connection_adapters/abstract_adapter.rb +628 -0
  69. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +887 -0
  70. data/lib/active_record/connection_adapters/column.rb +91 -0
  71. data/lib/active_record/connection_adapters/connection_specification.rb +287 -0
  72. data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +33 -0
  73. data/lib/active_record/connection_adapters/mysql/column.rb +27 -0
  74. data/lib/active_record/connection_adapters/mysql/database_statements.rb +140 -0
  75. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +72 -0
  76. data/lib/active_record/connection_adapters/mysql/quoting.rb +44 -0
  77. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +73 -0
  78. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +87 -0
  79. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +80 -0
  80. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +148 -0
  81. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +35 -0
  82. data/lib/active_record/connection_adapters/mysql2_adapter.rb +129 -0
  83. data/lib/active_record/connection_adapters/postgresql/column.rb +44 -0
  84. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +163 -0
  85. data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +44 -0
  86. data/lib/active_record/connection_adapters/postgresql/oid.rb +34 -0
  87. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +92 -0
  88. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +56 -0
  89. data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +15 -0
  90. data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +17 -0
  91. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +50 -0
  92. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +23 -0
  93. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +23 -0
  94. data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +15 -0
  95. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +21 -0
  96. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +71 -0
  97. data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +15 -0
  98. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +15 -0
  99. data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +45 -0
  100. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +41 -0
  101. data/lib/active_record/connection_adapters/postgresql/oid/oid.rb +15 -0
  102. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +65 -0
  103. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +97 -0
  104. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +18 -0
  105. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +111 -0
  106. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +23 -0
  107. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +28 -0
  108. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +30 -0
  109. data/lib/active_record/connection_adapters/postgresql/quoting.rb +168 -0
  110. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +43 -0
  111. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +65 -0
  112. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +206 -0
  113. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +50 -0
  114. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +774 -0
  115. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +39 -0
  116. data/lib/active_record/connection_adapters/postgresql/utils.rb +81 -0
  117. data/lib/active_record/connection_adapters/postgresql_adapter.rb +863 -0
  118. data/lib/active_record/connection_adapters/schema_cache.rb +118 -0
  119. data/lib/active_record/connection_adapters/sql_type_metadata.rb +34 -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 +67 -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 +106 -0
  126. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +573 -0
  127. data/lib/active_record/connection_adapters/statement_pool.rb +61 -0
  128. data/lib/active_record/connection_handling.rb +145 -0
  129. data/lib/active_record/core.rb +559 -0
  130. data/lib/active_record/counter_cache.rb +218 -0
  131. data/lib/active_record/define_callbacks.rb +22 -0
  132. data/lib/active_record/dynamic_matchers.rb +122 -0
  133. data/lib/active_record/enum.rb +244 -0
  134. data/lib/active_record/errors.rb +380 -0
  135. data/lib/active_record/explain.rb +50 -0
  136. data/lib/active_record/explain_registry.rb +32 -0
  137. data/lib/active_record/explain_subscriber.rb +34 -0
  138. data/lib/active_record/fixture_set/file.rb +82 -0
  139. data/lib/active_record/fixtures.rb +1065 -0
  140. data/lib/active_record/gem_version.rb +17 -0
  141. data/lib/active_record/inheritance.rb +283 -0
  142. data/lib/active_record/integration.rb +155 -0
  143. data/lib/active_record/internal_metadata.rb +45 -0
  144. data/lib/active_record/legacy_yaml_adapter.rb +48 -0
  145. data/lib/active_record/locale/en.yml +48 -0
  146. data/lib/active_record/locking/optimistic.rb +198 -0
  147. data/lib/active_record/locking/pessimistic.rb +89 -0
  148. data/lib/active_record/log_subscriber.rb +137 -0
  149. data/lib/active_record/migration.rb +1378 -0
  150. data/lib/active_record/migration/command_recorder.rb +240 -0
  151. data/lib/active_record/migration/compatibility.rb +217 -0
  152. data/lib/active_record/migration/join_table.rb +17 -0
  153. data/lib/active_record/model_schema.rb +521 -0
  154. data/lib/active_record/nested_attributes.rb +600 -0
  155. data/lib/active_record/no_touching.rb +58 -0
  156. data/lib/active_record/null_relation.rb +68 -0
  157. data/lib/active_record/persistence.rb +763 -0
  158. data/lib/active_record/query_cache.rb +45 -0
  159. data/lib/active_record/querying.rb +70 -0
  160. data/lib/active_record/railtie.rb +226 -0
  161. data/lib/active_record/railties/console_sandbox.rb +7 -0
  162. data/lib/active_record/railties/controller_runtime.rb +56 -0
  163. data/lib/active_record/railties/databases.rake +377 -0
  164. data/lib/active_record/readonly_attributes.rb +24 -0
  165. data/lib/active_record/reflection.rb +1044 -0
  166. data/lib/active_record/relation.rb +629 -0
  167. data/lib/active_record/relation/batches.rb +287 -0
  168. data/lib/active_record/relation/batches/batch_enumerator.rb +69 -0
  169. data/lib/active_record/relation/calculations.rb +417 -0
  170. data/lib/active_record/relation/delegation.rb +147 -0
  171. data/lib/active_record/relation/finder_methods.rb +565 -0
  172. data/lib/active_record/relation/from_clause.rb +26 -0
  173. data/lib/active_record/relation/merger.rb +193 -0
  174. data/lib/active_record/relation/predicate_builder.rb +152 -0
  175. data/lib/active_record/relation/predicate_builder/array_handler.rb +48 -0
  176. data/lib/active_record/relation/predicate_builder/association_query_value.rb +46 -0
  177. data/lib/active_record/relation/predicate_builder/base_handler.rb +19 -0
  178. data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +20 -0
  179. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +56 -0
  180. data/lib/active_record/relation/predicate_builder/range_handler.rb +42 -0
  181. data/lib/active_record/relation/predicate_builder/relation_handler.rb +19 -0
  182. data/lib/active_record/relation/query_attribute.rb +45 -0
  183. data/lib/active_record/relation/query_methods.rb +1231 -0
  184. data/lib/active_record/relation/record_fetch_warning.rb +51 -0
  185. data/lib/active_record/relation/spawn_methods.rb +77 -0
  186. data/lib/active_record/relation/where_clause.rb +186 -0
  187. data/lib/active_record/relation/where_clause_factory.rb +34 -0
  188. data/lib/active_record/result.rb +149 -0
  189. data/lib/active_record/runtime_registry.rb +24 -0
  190. data/lib/active_record/sanitization.rb +222 -0
  191. data/lib/active_record/schema.rb +70 -0
  192. data/lib/active_record/schema_dumper.rb +255 -0
  193. data/lib/active_record/schema_migration.rb +56 -0
  194. data/lib/active_record/scoping.rb +106 -0
  195. data/lib/active_record/scoping/default.rb +152 -0
  196. data/lib/active_record/scoping/named.rb +213 -0
  197. data/lib/active_record/secure_token.rb +40 -0
  198. data/lib/active_record/serialization.rb +22 -0
  199. data/lib/active_record/statement_cache.rb +121 -0
  200. data/lib/active_record/store.rb +211 -0
  201. data/lib/active_record/suppressor.rb +61 -0
  202. data/lib/active_record/table_metadata.rb +82 -0
  203. data/lib/active_record/tasks/database_tasks.rb +337 -0
  204. data/lib/active_record/tasks/mysql_database_tasks.rb +115 -0
  205. data/lib/active_record/tasks/postgresql_database_tasks.rb +143 -0
  206. data/lib/active_record/tasks/sqlite_database_tasks.rb +83 -0
  207. data/lib/active_record/timestamp.rb +153 -0
  208. data/lib/active_record/touch_later.rb +64 -0
  209. data/lib/active_record/transactions.rb +502 -0
  210. data/lib/active_record/translation.rb +24 -0
  211. data/lib/active_record/type.rb +79 -0
  212. data/lib/active_record/type/adapter_specific_registry.rb +136 -0
  213. data/lib/active_record/type/date.rb +9 -0
  214. data/lib/active_record/type/date_time.rb +9 -0
  215. data/lib/active_record/type/decimal_without_scale.rb +15 -0
  216. data/lib/active_record/type/hash_lookup_type_map.rb +25 -0
  217. data/lib/active_record/type/internal/timezone.rb +17 -0
  218. data/lib/active_record/type/json.rb +30 -0
  219. data/lib/active_record/type/serialized.rb +71 -0
  220. data/lib/active_record/type/text.rb +11 -0
  221. data/lib/active_record/type/time.rb +21 -0
  222. data/lib/active_record/type/type_map.rb +62 -0
  223. data/lib/active_record/type/unsigned_integer.rb +17 -0
  224. data/lib/active_record/type_caster.rb +9 -0
  225. data/lib/active_record/type_caster/connection.rb +33 -0
  226. data/lib/active_record/type_caster/map.rb +23 -0
  227. data/lib/active_record/validations.rb +93 -0
  228. data/lib/active_record/validations/absence.rb +25 -0
  229. data/lib/active_record/validations/associated.rb +60 -0
  230. data/lib/active_record/validations/length.rb +26 -0
  231. data/lib/active_record/validations/presence.rb +68 -0
  232. data/lib/active_record/validations/uniqueness.rb +238 -0
  233. data/lib/active_record/version.rb +10 -0
  234. data/lib/rails/generators/active_record.rb +19 -0
  235. data/lib/rails/generators/active_record/application_record/application_record_generator.rb +27 -0
  236. data/lib/rails/generators/active_record/application_record/templates/application_record.rb.tt +5 -0
  237. data/lib/rails/generators/active_record/migration.rb +35 -0
  238. data/lib/rails/generators/active_record/migration/migration_generator.rb +78 -0
  239. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +24 -0
  240. data/lib/rails/generators/active_record/migration/templates/migration.rb.tt +46 -0
  241. data/lib/rails/generators/active_record/model/model_generator.rb +48 -0
  242. data/lib/rails/generators/active_record/model/templates/model.rb.tt +13 -0
  243. data/lib/rails/generators/active_record/model/templates/module.rb.tt +7 -0
  244. metadata +333 -0
@@ -0,0 +1,629 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ # = Active Record \Relation
5
+ class Relation
6
+ MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
7
+ :order, :joins, :left_outer_joins, :references,
8
+ :extending, :unscope]
9
+
10
+ SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :reordering,
11
+ :reverse_order, :distinct, :create_with, :skip_query_cache]
12
+ CLAUSE_METHODS = [:where, :having, :from]
13
+ INVALID_METHODS_FOR_DELETE_ALL = [:distinct, :group, :having]
14
+
15
+ VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS + CLAUSE_METHODS
16
+
17
+ include Enumerable
18
+ include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
19
+
20
+ attr_reader :table, :klass, :loaded, :predicate_builder
21
+ alias :model :klass
22
+ alias :loaded? :loaded
23
+ alias :locked? :lock_value
24
+
25
+ def initialize(klass, table: klass.arel_table, predicate_builder: klass.predicate_builder, values: {})
26
+ @klass = klass
27
+ @table = table
28
+ @values = values
29
+ @offsets = {}
30
+ @loaded = false
31
+ @predicate_builder = predicate_builder
32
+ @delegate_to_klass = false
33
+ end
34
+
35
+ def initialize_copy(other)
36
+ @values = @values.dup
37
+ reset
38
+ end
39
+
40
+ def arel_attribute(name) # :nodoc:
41
+ klass.arel_attribute(name, table)
42
+ end
43
+
44
+ # Initializes new record from relation while maintaining the current
45
+ # scope.
46
+ #
47
+ # Expects arguments in the same format as {ActiveRecord::Base.new}[rdoc-ref:Core.new].
48
+ #
49
+ # users = User.where(name: 'DHH')
50
+ # user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
51
+ #
52
+ # You can also pass a block to new with the new record as argument:
53
+ #
54
+ # user = users.new { |user| user.name = 'Oscar' }
55
+ # user.name # => Oscar
56
+ def new(attributes = nil, &block)
57
+ scoping { klass.new(values_for_create(attributes), &block) }
58
+ end
59
+
60
+ alias build new
61
+
62
+ # Tries to create a new record with the same scoped attributes
63
+ # defined in the relation. Returns the initialized object if validation fails.
64
+ #
65
+ # Expects arguments in the same format as
66
+ # {ActiveRecord::Base.create}[rdoc-ref:Persistence::ClassMethods#create].
67
+ #
68
+ # ==== Examples
69
+ #
70
+ # users = User.where(name: 'Oscar')
71
+ # users.create # => #<User id: 3, name: "Oscar", ...>
72
+ #
73
+ # users.create(name: 'fxn')
74
+ # users.create # => #<User id: 4, name: "fxn", ...>
75
+ #
76
+ # users.create { |user| user.name = 'tenderlove' }
77
+ # # => #<User id: 5, name: "tenderlove", ...>
78
+ #
79
+ # users.create(name: nil) # validation on name
80
+ # # => #<User id: nil, name: nil, ...>
81
+ def create(attributes = nil, &block)
82
+ if attributes.is_a?(Array)
83
+ attributes.collect { |attr| create(attr, &block) }
84
+ else
85
+ scoping { klass.create(values_for_create(attributes), &block) }
86
+ end
87
+ end
88
+
89
+ # Similar to #create, but calls
90
+ # {create!}[rdoc-ref:Persistence::ClassMethods#create!]
91
+ # on the base class. Raises an exception if a validation error occurs.
92
+ #
93
+ # Expects arguments in the same format as
94
+ # {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!].
95
+ def create!(attributes = nil, &block)
96
+ if attributes.is_a?(Array)
97
+ attributes.collect { |attr| create!(attr, &block) }
98
+ else
99
+ scoping { klass.create!(values_for_create(attributes), &block) }
100
+ end
101
+ end
102
+
103
+ def first_or_create(attributes = nil, &block) # :nodoc:
104
+ first || create(attributes, &block)
105
+ end
106
+
107
+ def first_or_create!(attributes = nil, &block) # :nodoc:
108
+ first || create!(attributes, &block)
109
+ end
110
+
111
+ def first_or_initialize(attributes = nil, &block) # :nodoc:
112
+ first || new(attributes, &block)
113
+ end
114
+
115
+ # Finds the first record with the given attributes, or creates a record
116
+ # with the attributes if one is not found:
117
+ #
118
+ # # Find the first user named "Penélope" or create a new one.
119
+ # User.find_or_create_by(first_name: 'Penélope')
120
+ # # => #<User id: 1, first_name: "Penélope", last_name: nil>
121
+ #
122
+ # # Find the first user named "Penélope" or create a new one.
123
+ # # We already have one so the existing record will be returned.
124
+ # User.find_or_create_by(first_name: 'Penélope')
125
+ # # => #<User id: 1, first_name: "Penélope", last_name: nil>
126
+ #
127
+ # # Find the first user named "Scarlett" or create a new one with
128
+ # # a particular last name.
129
+ # User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
130
+ # # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
131
+ #
132
+ # This method accepts a block, which is passed down to #create. The last example
133
+ # above can be alternatively written this way:
134
+ #
135
+ # # Find the first user named "Scarlett" or create a new one with a
136
+ # # different last name.
137
+ # User.find_or_create_by(first_name: 'Scarlett') do |user|
138
+ # user.last_name = 'Johansson'
139
+ # end
140
+ # # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
141
+ #
142
+ # This method always returns a record, but if creation was attempted and
143
+ # failed due to validation errors it won't be persisted, you get what
144
+ # #create returns in such situation.
145
+ #
146
+ # Please note *this method is not atomic*, it runs first a SELECT, and if
147
+ # there are no results an INSERT is attempted. If there are other threads
148
+ # or processes there is a race condition between both calls and it could
149
+ # be the case that you end up with two similar records.
150
+ #
151
+ # Whether that is a problem or not depends on the logic of the
152
+ # application, but in the particular case in which rows have a UNIQUE
153
+ # constraint an exception may be raised, just retry:
154
+ #
155
+ # begin
156
+ # CreditAccount.transaction(requires_new: true) do
157
+ # CreditAccount.find_or_create_by(user_id: user.id)
158
+ # end
159
+ # rescue ActiveRecord::RecordNotUnique
160
+ # retry
161
+ # end
162
+ #
163
+ def find_or_create_by(attributes, &block)
164
+ find_by(attributes) || create(attributes, &block)
165
+ end
166
+
167
+ # Like #find_or_create_by, but calls
168
+ # {create!}[rdoc-ref:Persistence::ClassMethods#create!] so an exception
169
+ # is raised if the created record is invalid.
170
+ def find_or_create_by!(attributes, &block)
171
+ find_by(attributes) || create!(attributes, &block)
172
+ end
173
+
174
+ # Like #find_or_create_by, but calls {new}[rdoc-ref:Core#new]
175
+ # instead of {create}[rdoc-ref:Persistence::ClassMethods#create].
176
+ def find_or_initialize_by(attributes, &block)
177
+ find_by(attributes) || new(attributes, &block)
178
+ end
179
+
180
+ # Runs EXPLAIN on the query or queries triggered by this relation and
181
+ # returns the result as a string. The string is formatted imitating the
182
+ # ones printed by the database shell.
183
+ #
184
+ # Note that this method actually runs the queries, since the results of some
185
+ # are needed by the next ones when eager loading is going on.
186
+ #
187
+ # Please see further details in the
188
+ # {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
189
+ def explain
190
+ exec_explain(collecting_queries_for_explain { exec_queries })
191
+ end
192
+
193
+ # Converts relation objects to Array.
194
+ def to_ary
195
+ records.dup
196
+ end
197
+ alias to_a to_ary
198
+
199
+ def records # :nodoc:
200
+ load
201
+ @records
202
+ end
203
+
204
+ # Serializes the relation objects Array.
205
+ def encode_with(coder)
206
+ coder.represent_seq(nil, records)
207
+ end
208
+
209
+ # Returns size of the records.
210
+ def size
211
+ loaded? ? @records.length : count(:all)
212
+ end
213
+
214
+ # Returns true if there are no records.
215
+ def empty?
216
+ return @records.empty? if loaded?
217
+ !exists?
218
+ end
219
+
220
+ # Returns true if there are no records.
221
+ def none?
222
+ return super if block_given?
223
+ empty?
224
+ end
225
+
226
+ # Returns true if there are any records.
227
+ def any?
228
+ return super if block_given?
229
+ !empty?
230
+ end
231
+
232
+ # Returns true if there is exactly one record.
233
+ def one?
234
+ return super if block_given?
235
+ limit_value ? records.one? : size == 1
236
+ end
237
+
238
+ # Returns true if there is more than one record.
239
+ def many?
240
+ return super if block_given?
241
+ limit_value ? records.many? : size > 1
242
+ end
243
+
244
+ # Returns a cache key that can be used to identify the records fetched by
245
+ # this query. The cache key is built with a fingerprint of the sql query,
246
+ # the number of records matched by the query and a timestamp of the last
247
+ # updated record. When a new record comes to match the query, or any of
248
+ # the existing records is updated or deleted, the cache key changes.
249
+ #
250
+ # Product.where("name like ?", "%Cosmic Encounter%").cache_key
251
+ # # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000"
252
+ #
253
+ # If the collection is loaded, the method will iterate through the records
254
+ # to generate the timestamp, otherwise it will trigger one SQL query like:
255
+ #
256
+ # SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%')
257
+ #
258
+ # You can also pass a custom timestamp column to fetch the timestamp of the
259
+ # last updated record.
260
+ #
261
+ # Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at)
262
+ #
263
+ # You can customize the strategy to generate the key on a per model basis
264
+ # overriding ActiveRecord::Base#collection_cache_key.
265
+ def cache_key(timestamp_column = :updated_at)
266
+ @cache_keys ||= {}
267
+ @cache_keys[timestamp_column] ||= @klass.collection_cache_key(self, timestamp_column)
268
+ end
269
+
270
+ # Scope all queries to the current scope.
271
+ #
272
+ # Comment.where(post_id: 1).scoping do
273
+ # Comment.first
274
+ # end
275
+ # # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
276
+ #
277
+ # Please check unscoped if you want to remove all previous scopes (including
278
+ # the default_scope) during the execution of a block.
279
+ def scoping
280
+ previous, klass.current_scope = klass.current_scope(true), self unless @delegate_to_klass
281
+ yield
282
+ ensure
283
+ klass.current_scope = previous unless @delegate_to_klass
284
+ end
285
+
286
+ def _exec_scope(*args, &block) # :nodoc:
287
+ @delegate_to_klass = true
288
+ instance_exec(*args, &block) || self
289
+ ensure
290
+ @delegate_to_klass = false
291
+ end
292
+
293
+ # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
294
+ # statement and sends it straight to the database. It does not instantiate the involved models and it does not
295
+ # trigger Active Record callbacks or validations. However, values passed to #update_all will still go through
296
+ # Active Record's normal type casting and serialization.
297
+ #
298
+ # ==== Parameters
299
+ #
300
+ # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
301
+ #
302
+ # ==== Examples
303
+ #
304
+ # # Update all customers with the given attributes
305
+ # Customer.update_all wants_email: true
306
+ #
307
+ # # Update all books with 'Rails' in their title
308
+ # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
309
+ #
310
+ # # Update all books that match conditions, but limit it to 5 ordered by date
311
+ # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
312
+ #
313
+ # # Update all invoices and set the number column to its id value.
314
+ # Invoice.update_all('number = id')
315
+ def update_all(updates)
316
+ raise ArgumentError, "Empty list of attributes to change" if updates.blank?
317
+
318
+ if eager_loading?
319
+ relation = apply_join_dependency
320
+ return relation.update_all(updates)
321
+ end
322
+
323
+ stmt = Arel::UpdateManager.new
324
+
325
+ stmt.set Arel.sql(@klass.sanitize_sql_for_assignment(updates))
326
+ stmt.table(table)
327
+
328
+ if has_join_values? || offset_value
329
+ @klass.connection.join_to_update(stmt, arel, arel_attribute(primary_key))
330
+ else
331
+ stmt.key = arel_attribute(primary_key)
332
+ stmt.take(arel.limit)
333
+ stmt.order(*arel.orders)
334
+ stmt.wheres = arel.constraints
335
+ end
336
+
337
+ @klass.connection.update stmt, "#{@klass} Update All"
338
+ end
339
+
340
+ def update(id = :all, attributes) # :nodoc:
341
+ if id == :all
342
+ each { |record| record.update(attributes) }
343
+ else
344
+ klass.update(id, attributes)
345
+ end
346
+ end
347
+
348
+ # Destroys the records by instantiating each
349
+ # record and calling its {#destroy}[rdoc-ref:Persistence#destroy] method.
350
+ # Each object's callbacks are executed (including <tt>:dependent</tt> association options).
351
+ # Returns the collection of objects that were destroyed; each will be frozen, to
352
+ # reflect that no changes should be made (since they can't be persisted).
353
+ #
354
+ # Note: Instantiation, callback execution, and deletion of each
355
+ # record can be time consuming when you're removing many records at
356
+ # once. It generates at least one SQL +DELETE+ query per record (or
357
+ # possibly more, to enforce your callbacks). If you want to delete many
358
+ # rows quickly, without concern for their associations or callbacks, use
359
+ # #delete_all instead.
360
+ #
361
+ # ==== Examples
362
+ #
363
+ # Person.where(age: 0..18).destroy_all
364
+ def destroy_all
365
+ records.each(&:destroy).tap { reset }
366
+ end
367
+
368
+ # Deletes the records without instantiating the records
369
+ # first, and hence not calling the {#destroy}[rdoc-ref:Persistence#destroy]
370
+ # method nor invoking callbacks.
371
+ # This is a single SQL DELETE statement that goes straight to the database, much more
372
+ # efficient than #destroy_all. Be careful with relations though, in particular
373
+ # <tt>:dependent</tt> rules defined on associations are not honored. Returns the
374
+ # number of rows affected.
375
+ #
376
+ # Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
377
+ #
378
+ # Both calls delete the affected posts all at once with a single DELETE statement.
379
+ # If you need to destroy dependent associations or call your <tt>before_*</tt> or
380
+ # +after_destroy+ callbacks, use the #destroy_all method instead.
381
+ #
382
+ # If an invalid method is supplied, #delete_all raises an ActiveRecordError:
383
+ #
384
+ # Post.distinct.delete_all
385
+ # # => ActiveRecord::ActiveRecordError: delete_all doesn't support distinct
386
+ def delete_all
387
+ invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select do |method|
388
+ value = get_value(method)
389
+ SINGLE_VALUE_METHODS.include?(method) ? value : value.any?
390
+ end
391
+ if invalid_methods.any?
392
+ raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
393
+ end
394
+
395
+ if eager_loading?
396
+ relation = apply_join_dependency
397
+ return relation.delete_all
398
+ end
399
+
400
+ stmt = Arel::DeleteManager.new
401
+ stmt.from(table)
402
+
403
+ if has_join_values? || has_limit_or_offset?
404
+ @klass.connection.join_to_delete(stmt, arel, arel_attribute(primary_key))
405
+ else
406
+ stmt.wheres = arel.constraints
407
+ end
408
+
409
+ affected = @klass.connection.delete(stmt, "#{@klass} Destroy")
410
+
411
+ reset
412
+ affected
413
+ end
414
+
415
+ # Causes the records to be loaded from the database if they have not
416
+ # been loaded already. You can use this if for some reason you need
417
+ # to explicitly load some records before actually using them. The
418
+ # return value is the relation itself, not the records.
419
+ #
420
+ # Post.where(published: true).load # => #<ActiveRecord::Relation>
421
+ def load(&block)
422
+ exec_queries(&block) unless loaded?
423
+
424
+ self
425
+ end
426
+
427
+ # Forces reloading of relation.
428
+ def reload
429
+ reset
430
+ load
431
+ end
432
+
433
+ def reset
434
+ @delegate_to_klass = false
435
+ @to_sql = @arel = @loaded = @should_eager_load = nil
436
+ @records = [].freeze
437
+ @offsets = {}
438
+ self
439
+ end
440
+
441
+ # Returns sql statement for the relation.
442
+ #
443
+ # User.where(name: 'Oscar').to_sql
444
+ # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
445
+ def to_sql
446
+ @to_sql ||= begin
447
+ if eager_loading?
448
+ apply_join_dependency do |relation, join_dependency|
449
+ relation = join_dependency.apply_column_aliases(relation)
450
+ relation.to_sql
451
+ end
452
+ else
453
+ conn = klass.connection
454
+ conn.unprepared_statement { conn.to_sql(arel) }
455
+ end
456
+ end
457
+ end
458
+
459
+ # Returns a hash of where conditions.
460
+ #
461
+ # User.where(name: 'Oscar').where_values_hash
462
+ # # => {name: "Oscar"}
463
+ def where_values_hash(relation_table_name = klass.table_name)
464
+ where_clause.to_h(relation_table_name)
465
+ end
466
+
467
+ def scope_for_create
468
+ where_values_hash.merge!(create_with_value.stringify_keys)
469
+ end
470
+
471
+ # Returns true if relation needs eager loading.
472
+ def eager_loading?
473
+ @should_eager_load ||=
474
+ eager_load_values.any? ||
475
+ includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
476
+ end
477
+
478
+ # Joins that are also marked for preloading. In which case we should just eager load them.
479
+ # Note that this is a naive implementation because we could have strings and symbols which
480
+ # represent the same association, but that aren't matched by this. Also, we could have
481
+ # nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
482
+ def joined_includes_values
483
+ includes_values & joins_values
484
+ end
485
+
486
+ # Compares two relations for equality.
487
+ def ==(other)
488
+ case other
489
+ when Associations::CollectionProxy, AssociationRelation
490
+ self == other.records
491
+ when Relation
492
+ other.to_sql == to_sql
493
+ when Array
494
+ records == other
495
+ end
496
+ end
497
+
498
+ def pretty_print(q)
499
+ q.pp(records)
500
+ end
501
+
502
+ # Returns true if relation is blank.
503
+ def blank?
504
+ records.blank?
505
+ end
506
+
507
+ def values
508
+ @values.dup
509
+ end
510
+
511
+ def inspect
512
+ subject = loaded? ? records : self
513
+ entries = subject.take([limit_value, 11].compact.min).map!(&:inspect)
514
+
515
+ entries[10] = "..." if entries.size == 11
516
+
517
+ "#<#{self.class.name} [#{entries.join(', ')}]>"
518
+ end
519
+
520
+ def empty_scope? # :nodoc:
521
+ @values == klass.unscoped.values
522
+ end
523
+
524
+ def has_limit_or_offset? # :nodoc:
525
+ limit_value || offset_value
526
+ end
527
+
528
+ def alias_tracker(joins = [], aliases = nil) # :nodoc:
529
+ joins += [aliases] if aliases
530
+ ActiveRecord::Associations::AliasTracker.create(connection, table.name, joins)
531
+ end
532
+
533
+ protected
534
+
535
+ def load_records(records)
536
+ @records = records.freeze
537
+ @loaded = true
538
+ end
539
+
540
+ private
541
+
542
+ def has_join_values?
543
+ joins_values.any? || left_outer_joins_values.any?
544
+ end
545
+
546
+ def exec_queries(&block)
547
+ skip_query_cache_if_necessary do
548
+ @records =
549
+ if eager_loading?
550
+ apply_join_dependency do |relation, join_dependency|
551
+ if ActiveRecord::NullRelation === relation
552
+ []
553
+ else
554
+ relation = join_dependency.apply_column_aliases(relation)
555
+ rows = connection.select_all(relation.arel, "SQL")
556
+ join_dependency.instantiate(rows, &block)
557
+ end.freeze
558
+ end
559
+ else
560
+ klass.find_by_sql(arel, &block).freeze
561
+ end
562
+
563
+ preload = preload_values
564
+ preload += includes_values unless eager_loading?
565
+ preloader = nil
566
+ preload.each do |associations|
567
+ preloader ||= build_preloader
568
+ preloader.preload @records, associations
569
+ end
570
+
571
+ @records.each(&:readonly!) if readonly_value
572
+
573
+ @loaded = true
574
+ @records
575
+ end
576
+ end
577
+
578
+ def skip_query_cache_if_necessary
579
+ if skip_query_cache_value
580
+ uncached do
581
+ yield
582
+ end
583
+ else
584
+ yield
585
+ end
586
+ end
587
+
588
+ def build_preloader
589
+ ActiveRecord::Associations::Preloader.new
590
+ end
591
+
592
+ def references_eager_loaded_tables?
593
+ joined_tables = arel.join_sources.map do |join|
594
+ if join.is_a?(Arel::Nodes::StringJoin)
595
+ tables_in_string(join.left)
596
+ else
597
+ [join.left.table_name, join.left.table_alias]
598
+ end
599
+ end
600
+
601
+ joined_tables += [table.name, table.table_alias]
602
+
603
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
604
+ joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
605
+
606
+ (references_values - joined_tables).any?
607
+ end
608
+
609
+ def tables_in_string(string)
610
+ return [] if string.blank?
611
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
612
+ # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
613
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"]
614
+ end
615
+
616
+ def values_for_create(attributes = nil)
617
+ result = attributes ? where_values_hash.merge!(attributes) : where_values_hash
618
+
619
+ # NOTE: if there are same keys in both create_with and result, create_with should be used.
620
+ # This is to make sure nested attributes don't get passed to the klass.new,
621
+ # while keeping the precedence of the duplicate keys in create_with.
622
+ create_with_value.stringify_keys.each do |k, v|
623
+ result[k] = v if result.key?(k)
624
+ end
625
+
626
+ result
627
+ end
628
+ end
629
+ end