activerecord 3.2.14.rc2 → 3.2.14

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.

@@ -1,405 +0,0 @@
1
- require 'active_support/core_ext/object/blank'
2
- require 'active_support/core_ext/hash/indifferent_access'
3
-
4
- module ActiveRecord
5
- module FinderMethods
6
- # Find operates with four different retrieval approaches:
7
- #
8
- # * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
9
- # If no record can be found for all of the listed ids, then RecordNotFound will be raised.
10
- # * Find first - This will return the first record matched by the options used. These options can either be specific
11
- # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
12
- # <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
13
- # * Find last - This will return the last record matched by the options used. These options can either be specific
14
- # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
15
- # <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
16
- # * Find all - This will return all the records matched by the options used.
17
- # If no records are found, an empty array is returned. Use
18
- # <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
19
- #
20
- # All approaches accept an options hash as their last parameter.
21
- #
22
- # ==== Options
23
- #
24
- # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>["user_name = ?", username]</tt>,
25
- # or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
26
- # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
27
- # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
28
- # * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
29
- # <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
30
- # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
31
- # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
32
- # it would skip rows 0 through 4.
33
- # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
34
- # named associations in the same form used for the <tt>:include</tt> option, which will perform an
35
- # <tt>INNER JOIN</tt> on the associated table(s),
36
- # or an array containing a mixture of both strings and named associations.
37
- # If the value is a string, then the records will be returned read-only since they will
38
- # have attributes that do not correspond to the table's columns.
39
- # Pass <tt>:readonly => false</tt> to override.
40
- # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
41
- # to already defined associations. See eager loading under Associations.
42
- # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
43
- # for example, want to do a join but not include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
44
- # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
45
- # to an alternate table name (or even the name of a database view).
46
- # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
47
- # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
48
- # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
49
- #
50
- # ==== Examples
51
- #
52
- # # find by id
53
- # Person.find(1) # returns the object for ID = 1
54
- # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
55
- # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
56
- # Person.find([1]) # returns an array for the object with ID = 1
57
- # Person.where("administrator = 1").order("created_on DESC").find(1)
58
- #
59
- # Note that returned records may not be in the same order as the ids you
60
- # provide since database rows are unordered. Give an explicit <tt>:order</tt>
61
- # to ensure the results are sorted.
62
- #
63
- # ==== Examples
64
- #
65
- # # find first
66
- # Person.first # returns the first object fetched by SELECT * FROM people
67
- # Person.where(["user_name = ?", user_name]).first
68
- # Person.where(["user_name = :u", { :u => user_name }]).first
69
- # Person.order("created_on DESC").offset(5).first
70
- #
71
- # # find last
72
- # Person.last # returns the last object fetched by SELECT * FROM people
73
- # Person.where(["user_name = ?", user_name]).last
74
- # Person.order("created_on DESC").offset(5).last
75
- #
76
- # # find all
77
- # Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
78
- # Person.where(["category IN (?)", categories]).limit(50).all
79
- # Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
80
- # Person.offset(10).limit(10).all
81
- # Person.includes([:account, :friends]).all
82
- # Person.group("category").all
83
- #
84
- # Example for find with a lock: Imagine two concurrent transactions:
85
- # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
86
- # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
87
- # transaction has to wait until the first is finished; we get the
88
- # expected <tt>person.visits == 4</tt>.
89
- #
90
- # Person.transaction do
91
- # person = Person.lock(true).find(1)
92
- # person.visits += 1
93
- # person.save!
94
- # end
95
- def find(*args)
96
- return to_a.find { |*block_args| yield(*block_args) } if block_given?
97
-
98
- options = args.extract_options!
99
-
100
- if options.present?
101
- apply_finder_options(options).find(*args)
102
- else
103
- case args.first
104
- when :first, :last, :all
105
- send(args.first)
106
- else
107
- find_with_ids(*args)
108
- end
109
- end
110
- end
111
-
112
- # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
113
- # same arguments to this method as you can to <tt>find(:first)</tt>.
114
- def first(*args)
115
- if args.any?
116
- if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
117
- limit(*args).to_a
118
- else
119
- apply_finder_options(args.first).first
120
- end
121
- else
122
- find_first
123
- end
124
- end
125
-
126
- # Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
127
- # is found. Note that <tt>first!</tt> accepts no arguments.
128
- def first!
129
- first or raise RecordNotFound
130
- end
131
-
132
- # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
133
- # same arguments to this method as you can to <tt>find(:last)</tt>.
134
- def last(*args)
135
- if args.any?
136
- if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
137
- if order_values.empty?
138
- order("#{primary_key} DESC").limit(*args).reverse
139
- else
140
- to_a.last(*args)
141
- end
142
- else
143
- apply_finder_options(args.first).last
144
- end
145
- else
146
- find_last
147
- end
148
- end
149
-
150
- # Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
151
- # is found. Note that <tt>last!</tt> accepts no arguments.
152
- def last!
153
- last or raise RecordNotFound
154
- end
155
-
156
- # A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the
157
- # same arguments to this method as you can to <tt>find(:all)</tt>.
158
- def all(*args)
159
- args.any? ? apply_finder_options(args.first).to_a : to_a
160
- end
161
-
162
- # Returns true if a record exists in the table that matches the +id+ or
163
- # conditions given, or false otherwise. The argument can take five forms:
164
- #
165
- # * Integer - Finds the record with this primary key.
166
- # * String - Finds the record with a primary key corresponding to this
167
- # string (such as <tt>'5'</tt>).
168
- # * Array - Finds the record that matches these +find+-style conditions
169
- # (such as <tt>['color = ?', 'red']</tt>).
170
- # * Hash - Finds the record that matches these +find+-style conditions
171
- # (such as <tt>{:color => 'red'}</tt>).
172
- # * No args - Returns false if the table is empty, true otherwise.
173
- #
174
- # For more information about specifying conditions as a Hash or Array,
175
- # see the Conditions section in the introduction to ActiveRecord::Base.
176
- #
177
- # Note: You can't pass in a condition as a string (like <tt>name =
178
- # 'Jamie'</tt>), since it would be sanitized and then queried against
179
- # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
180
- #
181
- # ==== Examples
182
- # Person.exists?(5)
183
- # Person.exists?('5')
184
- # Person.exists?(:name => "David")
185
- # Person.exists?(['name LIKE ?', "%#{query}%"])
186
- # Person.exists?
187
- def exists?(id = false)
188
- id = id.id if ActiveRecord::Base === id
189
- return false if id.nil?
190
-
191
- join_dependency = construct_join_dependency_for_association_find
192
- relation = construct_relation_for_association_find(join_dependency)
193
- relation = relation.except(:select, :order).select("1 AS one").limit(1)
194
-
195
- case id
196
- when Array, Hash
197
- relation = relation.where(id)
198
- else
199
- relation = relation.where(table[primary_key].eq(id)) if id
200
- end
201
-
202
- connection.select_value(relation, "#{name} Exists") ? true : false
203
- rescue ThrowResult
204
- false
205
- end
206
-
207
- protected
208
-
209
- def find_with_associations
210
- join_dependency = construct_join_dependency_for_association_find
211
- relation = construct_relation_for_association_find(join_dependency)
212
- rows = connection.select_all(relation, 'SQL', relation.bind_values.dup)
213
- join_dependency.instantiate(rows)
214
- rescue ThrowResult
215
- []
216
- end
217
-
218
- def construct_join_dependency_for_association_find
219
- including = (@eager_load_values + @includes_values).uniq
220
- ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
221
- end
222
-
223
- def construct_relation_for_association_calculations
224
- including = (@eager_load_values + @includes_values).uniq
225
- join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
226
- relation = except(:includes, :eager_load, :preload)
227
- apply_join_dependency(relation, join_dependency)
228
- end
229
-
230
- def construct_relation_for_association_find(join_dependency)
231
- relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
232
- apply_join_dependency(relation, join_dependency)
233
- end
234
-
235
- def apply_join_dependency(relation, join_dependency)
236
- join_dependency.join_associations.each do |association|
237
- relation = association.join_relation(relation)
238
- end
239
-
240
- limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
241
-
242
- if !limitable_reflections && relation.limit_value
243
- limited_id_condition = construct_limited_ids_condition(relation.except(:select))
244
- relation = relation.where(limited_id_condition)
245
- end
246
-
247
- relation = relation.except(:limit, :offset) unless limitable_reflections
248
-
249
- relation
250
- end
251
-
252
- def construct_limited_ids_condition(relation)
253
- orders = relation.order_values.map { |val| val.presence }.compact
254
- <<<<<<< HEAD
255
- values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
256
- =======
257
- values = @klass.connection.columns_for_distinct("#{quoted_table_name}.#{quoted_primary_key}", orders)
258
- >>>>>>> 1b02299... Merge pull request #6792 from Empact/postgres-distinct
259
-
260
- relation = relation.dup.select(values).distinct!
261
-
262
- id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
263
- ids_array = id_rows.map {|row| row[primary_key]}
264
-
265
- ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
266
- end
267
-
268
- def find_by_attributes(match, attributes, *args)
269
- conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]
270
- result = where(conditions).send(match.finder)
271
-
272
- if match.bang? && result.nil?
273
- raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"
274
- else
275
- yield(result) if block_given?
276
- result
277
- end
278
- end
279
-
280
- def find_or_instantiator_by_attributes(match, attributes, *args)
281
- options = args.size > 1 && args.last(2).all?{ |a| a.is_a?(Hash) } ? args.extract_options! : {}
282
- protected_attributes_for_create, unprotected_attributes_for_create = {}, {}
283
- args.each_with_index do |arg, i|
284
- if arg.is_a?(Hash)
285
- protected_attributes_for_create = args[i].with_indifferent_access
286
- else
287
- unprotected_attributes_for_create[attributes[i]] = args[i]
288
- end
289
- end
290
-
291
- conditions = (protected_attributes_for_create.merge(unprotected_attributes_for_create)).slice(*attributes).symbolize_keys
292
-
293
- record = where(conditions).first
294
-
295
- unless record
296
- record = @klass.new(protected_attributes_for_create, options) do |r|
297
- r.assign_attributes(unprotected_attributes_for_create, :without_protection => true)
298
- end
299
- yield(record) if block_given?
300
- record.send(match.save_method) if match.save_record?
301
- end
302
-
303
- record
304
- end
305
-
306
- def find_with_ids(*ids)
307
- return to_a.find { |*block_args| yield(*block_args) } if block_given?
308
-
309
- expects_array = ids.first.kind_of?(Array)
310
- return ids.first if expects_array && ids.first.empty?
311
-
312
- ids = ids.flatten.compact.uniq
313
-
314
- case ids.size
315
- when 0
316
- raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
317
- when 1
318
- result = find_one(ids.first)
319
- expects_array ? [ result ] : result
320
- else
321
- find_some(ids)
322
- end
323
- end
324
-
325
- def find_one(id)
326
- id = id.id if ActiveRecord::Base === id
327
-
328
- if IdentityMap.enabled? && where_values.blank? &&
329
- limit_value.blank? && order_values.blank? &&
330
- includes_values.blank? && preload_values.blank? &&
331
- readonly_value.nil? && joins_values.blank? &&
332
- !@klass.locking_enabled? &&
333
- record = IdentityMap.get(@klass, id)
334
- return record
335
- end
336
-
337
- column = columns_hash[primary_key]
338
-
339
- substitute = connection.substitute_at(column, @bind_values.length)
340
- relation = where(table[primary_key].eq(substitute))
341
- relation.bind_values = [[column, id]]
342
- record = relation.first
343
-
344
- unless record
345
- conditions = arel.where_sql
346
- conditions = " [#{conditions}]" if conditions
347
- raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
348
- end
349
-
350
- record
351
- end
352
-
353
- def find_some(ids)
354
- result = where(table[primary_key].in(ids)).all
355
-
356
- expected_size =
357
- if @limit_value && ids.size > @limit_value
358
- @limit_value
359
- else
360
- ids.size
361
- end
362
-
363
- # 11 ids with limit 3, offset 9 should give 2 results.
364
- if @offset_value && (ids.size - @offset_value < expected_size)
365
- expected_size = ids.size - @offset_value
366
- end
367
-
368
- if result.size == expected_size
369
- result
370
- else
371
- conditions = arel.where_sql
372
- conditions = " [#{conditions}]" if conditions
373
-
374
- error = "Couldn't find all #{@klass.name.pluralize} with IDs "
375
- error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
376
- raise RecordNotFound, error
377
- end
378
- end
379
-
380
- def find_first
381
- if loaded?
382
- @records.first
383
- else
384
- @first ||= limit(1).to_a[0]
385
- end
386
- end
387
-
388
- def find_last
389
- if loaded?
390
- @records.last
391
- else
392
- @last ||=
393
- if offset_value || limit_value
394
- to_a.last
395
- else
396
- reverse_order.limit(1).to_a[0]
397
- end
398
- end
399
- end
400
-
401
- def using_limitable_reflections?(reflections)
402
- reflections.none? { |r| r.collection? }
403
- end
404
- end
405
- end
@@ -1,15 +0,0 @@
1
- require 'rails/generators/active_record'
2
-
3
- module ActiveRecord
4
- module Generators # :nodoc:
5
- class ObserverGenerator < Base # :nodoc:
6
- check_class_collision :suffix => "Observer"
7
-
8
- def create_observer_file
9
- template 'observer.rb', File.join('app/models', class_path, "#{file_name}_observer.rb")
10
- end
11
-
12
- hook_for :test_framework
13
- end
14
- end
15
- end