activerecord 4.2.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (221) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +1372 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +218 -0
  5. data/examples/performance.rb +184 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record.rb +173 -0
  8. data/lib/active_record/aggregations.rb +266 -0
  9. data/lib/active_record/association_relation.rb +22 -0
  10. data/lib/active_record/associations.rb +1724 -0
  11. data/lib/active_record/associations/alias_tracker.rb +87 -0
  12. data/lib/active_record/associations/association.rb +253 -0
  13. data/lib/active_record/associations/association_scope.rb +194 -0
  14. data/lib/active_record/associations/belongs_to_association.rb +111 -0
  15. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +40 -0
  16. data/lib/active_record/associations/builder/association.rb +149 -0
  17. data/lib/active_record/associations/builder/belongs_to.rb +116 -0
  18. data/lib/active_record/associations/builder/collection_association.rb +91 -0
  19. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +124 -0
  20. data/lib/active_record/associations/builder/has_many.rb +15 -0
  21. data/lib/active_record/associations/builder/has_one.rb +23 -0
  22. data/lib/active_record/associations/builder/singular_association.rb +38 -0
  23. data/lib/active_record/associations/collection_association.rb +634 -0
  24. data/lib/active_record/associations/collection_proxy.rb +1027 -0
  25. data/lib/active_record/associations/has_many_association.rb +184 -0
  26. data/lib/active_record/associations/has_many_through_association.rb +238 -0
  27. data/lib/active_record/associations/has_one_association.rb +105 -0
  28. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  29. data/lib/active_record/associations/join_dependency.rb +282 -0
  30. data/lib/active_record/associations/join_dependency/join_association.rb +122 -0
  31. data/lib/active_record/associations/join_dependency/join_base.rb +22 -0
  32. data/lib/active_record/associations/join_dependency/join_part.rb +71 -0
  33. data/lib/active_record/associations/preloader.rb +203 -0
  34. data/lib/active_record/associations/preloader/association.rb +162 -0
  35. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  36. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  37. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  38. data/lib/active_record/associations/preloader/has_many_through.rb +19 -0
  39. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  40. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  41. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  42. data/lib/active_record/associations/preloader/through_association.rb +96 -0
  43. data/lib/active_record/associations/singular_association.rb +86 -0
  44. data/lib/active_record/associations/through_association.rb +96 -0
  45. data/lib/active_record/attribute.rb +149 -0
  46. data/lib/active_record/attribute_assignment.rb +212 -0
  47. data/lib/active_record/attribute_decorators.rb +66 -0
  48. data/lib/active_record/attribute_methods.rb +439 -0
  49. data/lib/active_record/attribute_methods/before_type_cast.rb +71 -0
  50. data/lib/active_record/attribute_methods/dirty.rb +181 -0
  51. data/lib/active_record/attribute_methods/primary_key.rb +128 -0
  52. data/lib/active_record/attribute_methods/query.rb +40 -0
  53. data/lib/active_record/attribute_methods/read.rb +103 -0
  54. data/lib/active_record/attribute_methods/serialization.rb +70 -0
  55. data/lib/active_record/attribute_methods/time_zone_conversion.rb +65 -0
  56. data/lib/active_record/attribute_methods/write.rb +83 -0
  57. data/lib/active_record/attribute_set.rb +77 -0
  58. data/lib/active_record/attribute_set/builder.rb +86 -0
  59. data/lib/active_record/attributes.rb +139 -0
  60. data/lib/active_record/autosave_association.rb +439 -0
  61. data/lib/active_record/base.rb +317 -0
  62. data/lib/active_record/callbacks.rb +313 -0
  63. data/lib/active_record/coders/json.rb +13 -0
  64. data/lib/active_record/coders/yaml_column.rb +38 -0
  65. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +659 -0
  66. data/lib/active_record/connection_adapters/abstract/database_limits.rb +67 -0
  67. data/lib/active_record/connection_adapters/abstract/database_statements.rb +373 -0
  68. data/lib/active_record/connection_adapters/abstract/query_cache.rb +95 -0
  69. data/lib/active_record/connection_adapters/abstract/quoting.rb +133 -0
  70. data/lib/active_record/connection_adapters/abstract/savepoints.rb +21 -0
  71. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +125 -0
  72. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +574 -0
  73. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +50 -0
  74. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +991 -0
  75. data/lib/active_record/connection_adapters/abstract/transaction.rb +219 -0
  76. data/lib/active_record/connection_adapters/abstract_adapter.rb +487 -0
  77. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +883 -0
  78. data/lib/active_record/connection_adapters/column.rb +82 -0
  79. data/lib/active_record/connection_adapters/connection_specification.rb +275 -0
  80. data/lib/active_record/connection_adapters/mysql2_adapter.rb +282 -0
  81. data/lib/active_record/connection_adapters/mysql_adapter.rb +491 -0
  82. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +93 -0
  83. data/lib/active_record/connection_adapters/postgresql/column.rb +20 -0
  84. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +232 -0
  85. data/lib/active_record/connection_adapters/postgresql/oid.rb +36 -0
  86. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +99 -0
  87. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +52 -0
  88. data/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +13 -0
  89. data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +14 -0
  90. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +46 -0
  91. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +11 -0
  92. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +27 -0
  93. data/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +13 -0
  94. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +17 -0
  95. data/lib/active_record/connection_adapters/postgresql/oid/float.rb +21 -0
  96. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +59 -0
  97. data/lib/active_record/connection_adapters/postgresql/oid/inet.rb +13 -0
  98. data/lib/active_record/connection_adapters/postgresql/oid/infinity.rb +13 -0
  99. data/lib/active_record/connection_adapters/postgresql/oid/integer.rb +11 -0
  100. data/lib/active_record/connection_adapters/postgresql/oid/json.rb +35 -0
  101. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +23 -0
  102. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +43 -0
  103. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +43 -0
  104. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +79 -0
  105. data/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +15 -0
  106. data/lib/active_record/connection_adapters/postgresql/oid/time.rb +11 -0
  107. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +97 -0
  108. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +21 -0
  109. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +26 -0
  110. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +28 -0
  111. data/lib/active_record/connection_adapters/postgresql/quoting.rb +108 -0
  112. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +30 -0
  113. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +152 -0
  114. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +588 -0
  115. data/lib/active_record/connection_adapters/postgresql/utils.rb +77 -0
  116. data/lib/active_record/connection_adapters/postgresql_adapter.rb +754 -0
  117. data/lib/active_record/connection_adapters/schema_cache.rb +94 -0
  118. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +628 -0
  119. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  120. data/lib/active_record/connection_handling.rb +132 -0
  121. data/lib/active_record/core.rb +566 -0
  122. data/lib/active_record/counter_cache.rb +175 -0
  123. data/lib/active_record/dynamic_matchers.rb +140 -0
  124. data/lib/active_record/enum.rb +198 -0
  125. data/lib/active_record/errors.rb +252 -0
  126. data/lib/active_record/explain.rb +38 -0
  127. data/lib/active_record/explain_registry.rb +30 -0
  128. data/lib/active_record/explain_subscriber.rb +29 -0
  129. data/lib/active_record/fixture_set/file.rb +56 -0
  130. data/lib/active_record/fixtures.rb +1007 -0
  131. data/lib/active_record/gem_version.rb +15 -0
  132. data/lib/active_record/inheritance.rb +247 -0
  133. data/lib/active_record/integration.rb +113 -0
  134. data/lib/active_record/locale/en.yml +47 -0
  135. data/lib/active_record/locking/optimistic.rb +204 -0
  136. data/lib/active_record/locking/pessimistic.rb +77 -0
  137. data/lib/active_record/log_subscriber.rb +75 -0
  138. data/lib/active_record/migration.rb +1051 -0
  139. data/lib/active_record/migration/command_recorder.rb +197 -0
  140. data/lib/active_record/migration/join_table.rb +15 -0
  141. data/lib/active_record/model_schema.rb +340 -0
  142. data/lib/active_record/nested_attributes.rb +548 -0
  143. data/lib/active_record/no_touching.rb +52 -0
  144. data/lib/active_record/null_relation.rb +81 -0
  145. data/lib/active_record/persistence.rb +532 -0
  146. data/lib/active_record/query_cache.rb +56 -0
  147. data/lib/active_record/querying.rb +68 -0
  148. data/lib/active_record/railtie.rb +162 -0
  149. data/lib/active_record/railties/console_sandbox.rb +5 -0
  150. data/lib/active_record/railties/controller_runtime.rb +50 -0
  151. data/lib/active_record/railties/databases.rake +391 -0
  152. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  153. data/lib/active_record/readonly_attributes.rb +23 -0
  154. data/lib/active_record/reflection.rb +881 -0
  155. data/lib/active_record/relation.rb +681 -0
  156. data/lib/active_record/relation/batches.rb +138 -0
  157. data/lib/active_record/relation/calculations.rb +403 -0
  158. data/lib/active_record/relation/delegation.rb +140 -0
  159. data/lib/active_record/relation/finder_methods.rb +528 -0
  160. data/lib/active_record/relation/merger.rb +170 -0
  161. data/lib/active_record/relation/predicate_builder.rb +126 -0
  162. data/lib/active_record/relation/predicate_builder/array_handler.rb +47 -0
  163. data/lib/active_record/relation/predicate_builder/relation_handler.rb +13 -0
  164. data/lib/active_record/relation/query_methods.rb +1176 -0
  165. data/lib/active_record/relation/spawn_methods.rb +75 -0
  166. data/lib/active_record/result.rb +131 -0
  167. data/lib/active_record/runtime_registry.rb +22 -0
  168. data/lib/active_record/sanitization.rb +191 -0
  169. data/lib/active_record/schema.rb +64 -0
  170. data/lib/active_record/schema_dumper.rb +251 -0
  171. data/lib/active_record/schema_migration.rb +56 -0
  172. data/lib/active_record/scoping.rb +87 -0
  173. data/lib/active_record/scoping/default.rb +134 -0
  174. data/lib/active_record/scoping/named.rb +164 -0
  175. data/lib/active_record/serialization.rb +22 -0
  176. data/lib/active_record/serializers/xml_serializer.rb +193 -0
  177. data/lib/active_record/statement_cache.rb +111 -0
  178. data/lib/active_record/store.rb +205 -0
  179. data/lib/active_record/tasks/database_tasks.rb +296 -0
  180. data/lib/active_record/tasks/mysql_database_tasks.rb +145 -0
  181. data/lib/active_record/tasks/postgresql_database_tasks.rb +90 -0
  182. data/lib/active_record/tasks/sqlite_database_tasks.rb +55 -0
  183. data/lib/active_record/timestamp.rb +121 -0
  184. data/lib/active_record/transactions.rb +417 -0
  185. data/lib/active_record/translation.rb +22 -0
  186. data/lib/active_record/type.rb +23 -0
  187. data/lib/active_record/type/big_integer.rb +13 -0
  188. data/lib/active_record/type/binary.rb +50 -0
  189. data/lib/active_record/type/boolean.rb +30 -0
  190. data/lib/active_record/type/date.rb +46 -0
  191. data/lib/active_record/type/date_time.rb +43 -0
  192. data/lib/active_record/type/decimal.rb +40 -0
  193. data/lib/active_record/type/decimal_without_scale.rb +11 -0
  194. data/lib/active_record/type/decorator.rb +14 -0
  195. data/lib/active_record/type/float.rb +19 -0
  196. data/lib/active_record/type/hash_lookup_type_map.rb +17 -0
  197. data/lib/active_record/type/integer.rb +55 -0
  198. data/lib/active_record/type/mutable.rb +16 -0
  199. data/lib/active_record/type/numeric.rb +36 -0
  200. data/lib/active_record/type/serialized.rb +56 -0
  201. data/lib/active_record/type/string.rb +36 -0
  202. data/lib/active_record/type/text.rb +11 -0
  203. data/lib/active_record/type/time.rb +26 -0
  204. data/lib/active_record/type/time_value.rb +38 -0
  205. data/lib/active_record/type/type_map.rb +64 -0
  206. data/lib/active_record/type/unsigned_integer.rb +15 -0
  207. data/lib/active_record/type/value.rb +101 -0
  208. data/lib/active_record/validations.rb +90 -0
  209. data/lib/active_record/validations/associated.rb +51 -0
  210. data/lib/active_record/validations/presence.rb +67 -0
  211. data/lib/active_record/validations/uniqueness.rb +229 -0
  212. data/lib/active_record/version.rb +8 -0
  213. data/lib/rails/generators/active_record.rb +17 -0
  214. data/lib/rails/generators/active_record/migration.rb +18 -0
  215. data/lib/rails/generators/active_record/migration/migration_generator.rb +70 -0
  216. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +22 -0
  217. data/lib/rails/generators/active_record/migration/templates/migration.rb +45 -0
  218. data/lib/rails/generators/active_record/model/model_generator.rb +52 -0
  219. data/lib/rails/generators/active_record/model/templates/model.rb +10 -0
  220. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  221. metadata +309 -0
@@ -0,0 +1,681 @@
1
+ # -*- coding: utf-8 -*-
2
+ require 'arel/collectors/bind'
3
+
4
+ module ActiveRecord
5
+ # = Active Record Relation
6
+ class Relation
7
+ MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
8
+ :order, :joins, :where, :having, :bind, :references,
9
+ :extending, :unscope]
10
+
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]
14
+
15
+ VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS
16
+
17
+ include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
18
+
19
+ attr_reader :table, :klass, :loaded
20
+ alias :model :klass
21
+ alias :loaded? :loaded
22
+
23
+ def initialize(klass, table, values = {})
24
+ @klass = klass
25
+ @table = table
26
+ @values = values
27
+ @offsets = {}
28
+ @loaded = false
29
+ end
30
+
31
+ 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
36
+ reset
37
+ end
38
+
39
+ def insert(values) # :nodoc:
40
+ primary_key_value = nil
41
+
42
+ if primary_key && Hash === values
43
+ primary_key_value = values[values.keys.find { |k|
44
+ k.name == primary_key
45
+ }]
46
+
47
+ if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
48
+ primary_key_value = connection.next_sequence_value(klass.sequence_name)
49
+ values[klass.arel_table[klass.primary_key]] = primary_key_value
50
+ end
51
+ end
52
+
53
+ im = arel.create_insert
54
+ im.into @table
55
+
56
+ substitutes, binds = substitute_values values
57
+
58
+ if values.empty? # empty insert
59
+ im.values = Arel.sql(connection.empty_insert_statement_value)
60
+ else
61
+ im.insert substitutes
62
+ end
63
+
64
+ @klass.connection.insert(
65
+ im,
66
+ 'SQL',
67
+ primary_key,
68
+ primary_key_value,
69
+ nil,
70
+ binds)
71
+ end
72
+
73
+ def _update_record(values, id, id_was) # :nodoc:
74
+ substitutes, binds = substitute_values values
75
+
76
+ scope = @klass.unscoped
77
+
78
+ if @klass.finder_needs_type_condition?
79
+ scope.unscope!(where: @klass.inheritance_column)
80
+ end
81
+
82
+ relation = scope.where(@klass.primary_key => (id_was || id))
83
+ bvs = binds + relation.bind_values
84
+ um = relation
85
+ .arel
86
+ .compile_update(substitutes, @klass.primary_key)
87
+
88
+ @klass.connection.update(
89
+ um,
90
+ 'SQL',
91
+ bvs,
92
+ )
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]
105
+ end
106
+
107
+ # Initializes new record from relation while maintaining the current
108
+ # scope.
109
+ #
110
+ # Expects arguments in the same format as +Base.new+.
111
+ #
112
+ # users = User.where(name: 'DHH')
113
+ # user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
114
+ #
115
+ # You can also pass a block to new with the new record as argument:
116
+ #
117
+ # user = users.new { |user| user.name = 'Oscar' }
118
+ # user.name # => Oscar
119
+ def new(*args, &block)
120
+ scoping { @klass.new(*args, &block) }
121
+ end
122
+
123
+ alias build new
124
+
125
+ # Tries to create a new record with the same scoped attributes
126
+ # defined in the relation. Returns the initialized object if validation fails.
127
+ #
128
+ # Expects arguments in the same format as +Base.create+.
129
+ #
130
+ # ==== Examples
131
+ # users = User.where(name: 'Oscar')
132
+ # users.create # #<User id: 3, name: "oscar", ...>
133
+ #
134
+ # users.create(name: 'fxn')
135
+ # users.create # #<User id: 4, name: "fxn", ...>
136
+ #
137
+ # users.create { |user| user.name = 'tenderlove' }
138
+ # # #<User id: 5, name: "tenderlove", ...>
139
+ #
140
+ # users.create(name: nil) # validation on name
141
+ # # #<User id: nil, name: nil, ...>
142
+ def create(*args, &block)
143
+ scoping { @klass.create(*args, &block) }
144
+ end
145
+
146
+ # Similar to #create, but calls +create!+ on the base class. Raises
147
+ # an exception if a validation error occurs.
148
+ #
149
+ # Expects arguments in the same format as <tt>Base.create!</tt>.
150
+ def create!(*args, &block)
151
+ scoping { @klass.create!(*args, &block) }
152
+ end
153
+
154
+ def first_or_create(attributes = nil, &block) # :nodoc:
155
+ first || create(attributes, &block)
156
+ end
157
+
158
+ def first_or_create!(attributes = nil, &block) # :nodoc:
159
+ first || create!(attributes, &block)
160
+ end
161
+
162
+ def first_or_initialize(attributes = nil, &block) # :nodoc:
163
+ first || new(attributes, &block)
164
+ end
165
+
166
+ # Finds the first record with the given attributes, or creates a record
167
+ # with the attributes if one is not found:
168
+ #
169
+ # # Find the first user named "Penélope" or create a new one.
170
+ # User.find_or_create_by(first_name: 'Penélope')
171
+ # # => #<User id: 1, first_name: "Penélope", last_name: nil>
172
+ #
173
+ # # Find the first user named "Penélope" or create a new one.
174
+ # # We already have one so the existing record will be returned.
175
+ # User.find_or_create_by(first_name: 'Penélope')
176
+ # # => #<User id: 1, first_name: "Penélope", last_name: nil>
177
+ #
178
+ # # Find the first user named "Scarlett" or create a new one with
179
+ # # a particular last name.
180
+ # User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
181
+ # # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
182
+ #
183
+ # This method accepts a block, which is passed down to +create+. The last example
184
+ # above can be alternatively written this way:
185
+ #
186
+ # # Find the first user named "Scarlett" or create a new one with a
187
+ # # different last name.
188
+ # User.find_or_create_by(first_name: 'Scarlett') do |user|
189
+ # user.last_name = 'Johansson'
190
+ # end
191
+ # # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
192
+ #
193
+ # This method always returns a record, but if creation was attempted and
194
+ # failed due to validation errors it won't be persisted, you get what
195
+ # +create+ returns in such situation.
196
+ #
197
+ # Please note *this method is not atomic*, it runs first a SELECT, and if
198
+ # there are no results an INSERT is attempted. If there are other threads
199
+ # or processes there is a race condition between both calls and it could
200
+ # be the case that you end up with two similar records.
201
+ #
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
+ #
212
+ def find_or_create_by(attributes, &block)
213
+ find_by(attributes) || create(attributes, &block)
214
+ end
215
+
216
+ # Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception
217
+ # is raised if the created record is invalid.
218
+ def find_or_create_by!(attributes, &block)
219
+ find_by(attributes) || create!(attributes, &block)
220
+ end
221
+
222
+ # Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
223
+ def find_or_initialize_by(attributes, &block)
224
+ find_by(attributes) || new(attributes, &block)
225
+ end
226
+
227
+ # Runs EXPLAIN on the query or queries triggered by this relation and
228
+ # returns the result as a string. The string is formatted imitating the
229
+ # ones printed by the database shell.
230
+ #
231
+ # Note that this method actually runs the queries, since the results of some
232
+ # are needed by the next ones when eager loading is going on.
233
+ #
234
+ # Please see further details in the
235
+ # {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
236
+ def explain
237
+ #TODO: Fix for binds.
238
+ exec_explain(collecting_queries_for_explain { exec_queries })
239
+ end
240
+
241
+ # Converts relation objects to Array.
242
+ def to_a
243
+ load
244
+ @records
245
+ end
246
+
247
+ # Serializes the relation objects Array.
248
+ 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)
254
+ end
255
+
256
+ # Returns size of the records.
257
+ def size
258
+ loaded? ? @records.length : count(:all)
259
+ end
260
+
261
+ # Returns true if there are no records.
262
+ def empty?
263
+ return @records.empty? if loaded?
264
+
265
+ if limit_value == 0
266
+ true
267
+ else
268
+ c = count(:all)
269
+ c.respond_to?(:zero?) ? c.zero? : c.empty?
270
+ end
271
+ end
272
+
273
+ # Returns true if there are any records.
274
+ def any?
275
+ if block_given?
276
+ to_a.any? { |*block_args| yield(*block_args) }
277
+ else
278
+ !empty?
279
+ end
280
+ end
281
+
282
+ # Returns true if there is more than one record.
283
+ def many?
284
+ if block_given?
285
+ to_a.many? { |*block_args| yield(*block_args) }
286
+ else
287
+ limit_value ? to_a.many? : size > 1
288
+ end
289
+ end
290
+
291
+ # Scope all queries to the current scope.
292
+ #
293
+ # Comment.where(post_id: 1).scoping do
294
+ # Comment.first
295
+ # end
296
+ # # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
297
+ #
298
+ # Please check unscoped if you want to remove all previous scopes (including
299
+ # the default_scope) during the execution of a block.
300
+ def scoping
301
+ previous, klass.current_scope = klass.current_scope, self
302
+ yield
303
+ ensure
304
+ klass.current_scope = previous
305
+ end
306
+
307
+ # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
308
+ # 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.
312
+ #
313
+ # ==== Parameters
314
+ #
315
+ # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
316
+ #
317
+ # ==== Examples
318
+ #
319
+ # # Update all customers with the given attributes
320
+ # Customer.update_all wants_email: true
321
+ #
322
+ # # Update all books with 'Rails' in their title
323
+ # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
324
+ #
325
+ # # Update all books that match conditions, but limit it to 5 ordered by date
326
+ # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
327
+ def update_all(updates)
328
+ raise ArgumentError, "Empty list of attributes to change" if updates.blank?
329
+
330
+ stmt = Arel::UpdateManager.new(arel.engine)
331
+
332
+ stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
333
+ stmt.table(table)
334
+ stmt.key = table[primary_key]
335
+
336
+ if joins_values.any?
337
+ @klass.connection.join_to_update(stmt, arel)
338
+ else
339
+ stmt.take(arel.limit)
340
+ stmt.order(*arel.orders)
341
+ stmt.wheres = arel.constraints
342
+ end
343
+
344
+ bvs = arel.bind_values + bind_values
345
+ @klass.connection.update stmt, 'SQL', bvs
346
+ end
347
+
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.
350
+ #
351
+ # ==== Parameters
352
+ #
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.
355
+ #
356
+ # ==== Examples
357
+ #
358
+ # # Updates one record
359
+ # Person.update(15, user_name: 'Samuel', group: 'expert')
360
+ #
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
372
+ end
373
+
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
378
+ # reflect that no changes should be made (since they can't be persisted).
379
+ #
380
+ # Note: Instantiation, callback execution, and deletion of each
381
+ # record can be time consuming when you're removing many records at
382
+ # once. It generates at least one SQL +DELETE+ query per record (or
383
+ # possibly more, to enforce your callbacks). If you want to delete many
384
+ # 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.
393
+ #
394
+ # ==== Examples
395
+ #
396
+ # Person.destroy_all("last_login < '2004-04-04'")
397
+ # Person.destroy_all(status: "inactive")
398
+ # Person.where(age: 0..18).destroy_all
399
+ def destroy_all(conditions = nil)
400
+ if conditions
401
+ where(conditions).destroy_all
402
+ else
403
+ to_a.each {|object| object.destroy }.tap { reset }
404
+ end
405
+ end
406
+
407
+ # Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
408
+ # therefore all callbacks and filters are fired off before the object is deleted. This method is
409
+ # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
410
+ #
411
+ # This essentially finds the object (or multiple objects) with the given id, creates a new object
412
+ # from the attributes, and then calls destroy on it.
413
+ #
414
+ # ==== Parameters
415
+ #
416
+ # * +id+ - Can be either an Integer or an Array of Integers.
417
+ #
418
+ # ==== Examples
419
+ #
420
+ # # Destroy a single object
421
+ # Todo.destroy(1)
422
+ #
423
+ # # Destroy multiple objects
424
+ # todos = [1,2,3]
425
+ # Todo.destroy(todos)
426
+ def destroy(id)
427
+ if id.is_a?(Array)
428
+ id.map { |one_id| destroy(one_id) }
429
+ else
430
+ find(id).destroy
431
+ end
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
438
+ # <tt>:dependent</tt> rules defined on associations are not honored. Returns the
439
+ # number of rows affected.
440
+ #
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
+ # Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
444
+ #
445
+ # Both calls delete the affected posts all at once with a single DELETE statement.
446
+ # If you need to destroy dependent associations or call your <tt>before_*</tt> or
447
+ # +after_destroy+ callbacks, use the +destroy_all+ method instead.
448
+ #
449
+ # If an invalid method is supplied, +delete_all+ raises an ActiveRecord error:
450
+ #
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
+ }
461
+ if invalid_methods.any?
462
+ raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
463
+ end
464
+
465
+ if conditions
466
+ where(conditions).delete_all
467
+ else
468
+ stmt = Arel::DeleteManager.new(arel.engine)
469
+ stmt.from(table)
470
+
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
476
+
477
+ affected = @klass.connection.delete(stmt, 'SQL', bind_values)
478
+
479
+ reset
480
+ affected
481
+ end
482
+ end
483
+
484
+ # Deletes the row with a primary key matching the +id+ argument, using a
485
+ # SQL +DELETE+ statement, and returns the number of rows deleted. Active
486
+ # Record objects are not instantiated, so the object's callbacks are not
487
+ # executed, including any <tt>:dependent</tt> association options.
488
+ #
489
+ # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
490
+ #
491
+ # Note: Although it is often much faster than the alternative,
492
+ # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
493
+ # your application that ensures referential integrity or performs other
494
+ # essential jobs.
495
+ #
496
+ # ==== Examples
497
+ #
498
+ # # Delete a single row
499
+ # Todo.delete(1)
500
+ #
501
+ # # Delete multiple rows
502
+ # Todo.delete([2,3,4])
503
+ def delete(id_or_array)
504
+ where(primary_key => id_or_array).delete_all
505
+ end
506
+
507
+ # Causes the records to be loaded from the database if they have not
508
+ # been loaded already. You can use this if for some reason you need
509
+ # to explicitly load some records before actually using them. The
510
+ # return value is the relation itself, not the records.
511
+ #
512
+ # Post.where(published: true).load # => #<ActiveRecord::Relation>
513
+ def load
514
+ exec_queries unless loaded?
515
+
516
+ self
517
+ end
518
+
519
+ # Forces reloading of relation.
520
+ def reload
521
+ reset
522
+ load
523
+ end
524
+
525
+ def reset
526
+ @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
527
+ @should_eager_load = @join_dependency = nil
528
+ @records = []
529
+ @offsets = {}
530
+ self
531
+ end
532
+
533
+ # Returns sql statement for the relation.
534
+ #
535
+ # User.where(name: 'Oscar').to_sql
536
+ # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
537
+ def to_sql
538
+ @to_sql ||= begin
539
+ relation = self
540
+ connection = klass.connection
541
+ visitor = connection.visitor
542
+
543
+ if eager_loading?
544
+ find_with_associations { |rel| relation = rel }
545
+ end
546
+
547
+ arel = relation.arel
548
+ binds = (arel.bind_values + relation.bind_values).dup
549
+ binds.map! { |bv| connection.quote(*bv.reverse) }
550
+ collect = visitor.accept(arel.ast, Arel::Collectors::Bind.new)
551
+ collect.substitute_binds(binds).join
552
+ end
553
+ end
554
+
555
+ # Returns a hash of where conditions.
556
+ #
557
+ # User.where(name: 'Oscar').where_values_hash
558
+ # # => {name: "Oscar"}
559
+ def where_values_hash(relation_table_name = table_name)
560
+ equalities = where_values.grep(Arel::Nodes::Equality).find_all { |node|
561
+ node.left.relation.name == relation_table_name
562
+ }
563
+
564
+ binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
565
+
566
+ Hash[equalities.map { |where|
567
+ name = where.left.name
568
+ [name, binds.fetch(name.to_s) {
569
+ case where.right
570
+ when Array then where.right.map(&:val)
571
+ else
572
+ where.right.val
573
+ end
574
+ }]
575
+ }]
576
+ end
577
+
578
+ def scope_for_create
579
+ @scope_for_create ||= where_values_hash.merge(create_with_value)
580
+ end
581
+
582
+ # Returns true if relation needs eager loading.
583
+ def eager_loading?
584
+ @should_eager_load ||=
585
+ eager_load_values.any? ||
586
+ includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
587
+ end
588
+
589
+ # Joins that are also marked for preloading. In which case we should just eager load them.
590
+ # Note that this is a naive implementation because we could have strings and symbols which
591
+ # represent the same association, but that aren't matched by this. Also, we could have
592
+ # nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
593
+ def joined_includes_values
594
+ includes_values & joins_values
595
+ end
596
+
597
+ # +uniq+ and +uniq!+ are silently deprecated. +uniq_value+ delegates to +distinct_value+
598
+ # to maintain backwards compatibility. Use +distinct_value+ instead.
599
+ def uniq_value
600
+ distinct_value
601
+ end
602
+
603
+ # Compares two relations for equality.
604
+ def ==(other)
605
+ case other
606
+ when Associations::CollectionProxy, AssociationRelation
607
+ self == other.to_a
608
+ when Relation
609
+ other.to_sql == to_sql
610
+ when Array
611
+ to_a == other
612
+ end
613
+ end
614
+
615
+ def pretty_print(q)
616
+ q.pp(self.to_a)
617
+ end
618
+
619
+ # Returns true if relation is blank.
620
+ def blank?
621
+ to_a.blank?
622
+ end
623
+
624
+ def values
625
+ Hash[@values]
626
+ end
627
+
628
+ def inspect
629
+ entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
630
+ entries[10] = '...' if entries.size == 11
631
+
632
+ "#<#{self.class.name} [#{entries.join(', ')}]>"
633
+ end
634
+
635
+ private
636
+
637
+ def exec_queries
638
+ @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, arel.bind_values + bind_values)
639
+
640
+ preload = preload_values
641
+ preload += includes_values unless eager_loading?
642
+ preloader = build_preloader
643
+ preload.each do |associations|
644
+ preloader.preload @records, associations
645
+ end
646
+
647
+ @records.each { |record| record.readonly! } if readonly_value
648
+
649
+ @loaded = true
650
+ @records
651
+ end
652
+
653
+ def build_preloader
654
+ ActiveRecord::Associations::Preloader.new
655
+ end
656
+
657
+ def references_eager_loaded_tables?
658
+ joined_tables = arel.join_sources.map do |join|
659
+ if join.is_a?(Arel::Nodes::StringJoin)
660
+ tables_in_string(join.left)
661
+ else
662
+ [join.left.table_name, join.left.table_alias]
663
+ end
664
+ end
665
+
666
+ joined_tables += [table.name, table.table_alias]
667
+
668
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
669
+ joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
670
+
671
+ (references_values - joined_tables).any?
672
+ end
673
+
674
+ def tables_in_string(string)
675
+ return [] if string.blank?
676
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
677
+ # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
678
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
679
+ end
680
+ end
681
+ end