finder_methods.rb 18.3 KB
Newer Older
X
Xavier Noria 已提交
1
require 'active_support/core_ext/string/filters'
2

3 4
module ActiveRecord
  module FinderMethods
V
Vipul A M 已提交
5 6
    ONE_AS_ONE = '1 AS one'

7 8 9
    # 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]).
    # If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
    # is an integer, find by id coerces its arguments using +to_i+.
P
Pratik Naik 已提交
10
    #
11 12 13 14 15 16
    #   Person.find(1)          # returns the object for ID = 1
    #   Person.find("1")        # returns the object for ID = 1
    #   Person.find("31-sarah") # returns the object for ID = 31
    #   Person.find(1, 2, 6)    # returns an array for objects with IDs in (1, 2, 6)
    #   Person.find([7, 17])    # returns an array for objects with IDs in (7, 17)
    #   Person.find([1])        # returns an array for the object with ID = 1
E
Emilio Tagua 已提交
17
    #   Person.where("administrator = 1").order("created_on DESC").find(1)
P
Pratik Naik 已提交
18
    #
V
Vijay Dev 已提交
19
    # <tt>ActiveRecord::RecordNotFound</tt> will be raised if one or more ids are not found.
20
    #
V
Vijay Dev 已提交
21 22 23
    # NOTE: The returned records may not be in the same order as the ids you
    # provide since database rows are unordered. You'd need to provide an explicit <tt>order</tt>
    # option if you want the results are sorted.
P
Pratik Naik 已提交
24
    #
25
    # ==== Find with lock
P
Pratik Naik 已提交
26 27 28
    #
    # Example for find with a lock: Imagine two concurrent transactions:
    # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
29
    # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
P
Pratik Naik 已提交
30 31 32 33
    # transaction has to wait until the first is finished; we get the
    # expected <tt>person.visits == 4</tt>.
    #
    #   Person.transaction do
E
Emilio Tagua 已提交
34
    #     person = Person.lock(true).find(1)
P
Pratik Naik 已提交
35 36 37
    #     person.visits += 1
    #     person.save!
    #   end
38 39
    #
    # ==== Variations of +find+
40
    #
41
    #   Person.where(name: 'Spartacus', rating: 4)
V
Vijay Dev 已提交
42
    #   # returns a chainable list (which can be empty).
43 44
    #
    #   Person.find_by(name: 'Spartacus', rating: 4)
V
Vijay Dev 已提交
45
    #   # returns the first item or nil.
46 47
    #
    #   Person.where(name: 'Spartacus', rating: 4).first_or_initialize
V
Vijay Dev 已提交
48
    #   # returns the first item or returns a new instance (requires you call .save to persist against the database).
49 50
    #
    #   Person.where(name: 'Spartacus', rating: 4).first_or_create
V
Vijay Dev 已提交
51
    #   # returns the first item or creates it and returns it, available since Rails 3.2.1.
52 53 54 55
    #
    # ==== Alternatives for +find+
    #
    #   Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
V
Vijay Dev 已提交
56
    #   # returns a boolean indicating if any record with the given conditions exist.
57
    #
58
    #   Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
V
Vijay Dev 已提交
59
    #   # returns a chainable list of instances with only the mentioned fields.
60 61
    #
    #   Person.where(name: 'Spartacus', rating: 4).ids
V
Vijay Dev 已提交
62
    #   # returns an Array of ids, available since Rails 3.2.1.
63 64
    #
    #   Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
V
Vijay Dev 已提交
65
    #   # returns an Array of the required fields, available since Rails 3.1.
66
    def find(*args)
67
      if block_given?
68
        to_a.find(*args) { |*block_args| yield(*block_args) }
69
      else
70
        find_with_ids(*args)
71 72 73
      end
    end

74
    # Finds the first record matching the specified conditions. There
75
    # is no implied ordering so if order matters, you should specify it
76 77 78 79 80 81 82
    # yourself.
    #
    # If no record is found, returns <tt>nil</tt>.
    #
    #   Post.find_by name: 'Spartacus', rating: 4
    #   Post.find_by "published_at < ?", 2.weeks.ago
    def find_by(*args)
83
      where(*args).take
84 85
    rescue RangeError
      nil
86 87 88 89 90
    end

    # Like <tt>find_by</tt>, except that if no record is found, raises
    # an <tt>ActiveRecord::RecordNotFound</tt> error.
    def find_by!(*args)
91
      where(*args).take!
92 93
    rescue RangeError
      raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range value"
94 95
    end

96 97 98 99
    # Gives a record (or N records if a parameter is supplied) without any implied
    # order. The order will depend on the database implementation.
    # If an order is supplied it will be respected.
    #
100
    #   Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
101 102 103 104 105 106 107 108 109
    #   Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
    #   Person.where(["name LIKE '%?'", name]).take
    def take(limit = nil)
      limit ? limit(limit).to_a : find_take
    end

    # Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found. Note that <tt>take!</tt> accepts no arguments.
    def take!
110
      take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
111 112
    end

113 114 115
    # Find the first record (or first N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
116 117
    #   Person.first # returns the first object fetched by SELECT * FROM people
    #   Person.where(["user_name = ?", user_name]).first
A
AvnerCohen 已提交
118
    #   Person.where(["user_name = :u", { u: user_name }]).first
119
    #   Person.order("created_on DESC").offset(5).first
120
    #   Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
121 122 123
    #
    # ==== Rails 3
    #
124
    #   Person.first # SELECT "people".* FROM "people" LIMIT 1
125
    #
V
Vijay Dev 已提交
126 127 128
    # NOTE: Rails 3 may not order this query by the primary key and the order
    # will depend on the database implementation. In order to ensure that behavior,
    # use <tt>User.order(:id).first</tt> instead.
129 130 131
    #
    # ==== Rails 4
    #
132
    #   Person.first # SELECT "people".* FROM "people" ORDER BY "people"."id" ASC LIMIT 1
133
    #
134
    def first(limit = nil)
135
      if limit
136
        find_nth_with_limit(offset_index, limit)
137
      else
138
        find_nth(0, offset_index)
139
      end
140 141
    end

142 143
    # Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found. Note that <tt>first!</tt> accepts no arguments.
P
Pratik Naik 已提交
144
    def first!
145
      find_nth! 0
146 147
    end

148 149 150
    # Find the last record (or last N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
151 152 153
    #   Person.last # returns the last object fetched by SELECT * FROM people
    #   Person.where(["user_name = ?", user_name]).last
    #   Person.order("created_on DESC").offset(5).last
154
    #   Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
155
    #
156
    # Take note that in that last case, the results are sorted in ascending order:
157
    #
158
    #   [#<Person id:2>, #<Person id:3>, #<Person id:4>]
159
    #
160
    # and not:
161
    #
162
    #   [#<Person id:4>, #<Person id:3>, #<Person id:2>]
163 164
    def last(limit = nil)
      if limit
165
        if order_values.empty? && primary_key
166
          order(arel_table[primary_key].desc).limit(limit).reverse
167
        else
168
          to_a.last(limit)
169 170 171 172
        end
      else
        find_last
      end
173 174
    end

175 176
    # Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found. Note that <tt>last!</tt> accepts no arguments.
P
Pratik Naik 已提交
177
    def last!
178
      last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
179 180
    end

181 182 183 184 185 186 187
    # Find the second record.
    # If no order is defined it will order by primary key.
    #
    #   Person.second # returns the second object fetched by SELECT * FROM people
    #   Person.offset(3).second # returns the second object from OFFSET 3 (which is OFFSET 4)
    #   Person.where(["user_name = :u", { u: user_name }]).second
    def second
188
      find_nth(1, offset_index)
189 190 191 192 193
    end

    # Same as +second+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def second!
194
      find_nth! 1
195 196 197 198 199 200 201 202 203
    end

    # Find the third record.
    # If no order is defined it will order by primary key.
    #
    #   Person.third # returns the third object fetched by SELECT * FROM people
    #   Person.offset(3).third # returns the third object from OFFSET 3 (which is OFFSET 5)
    #   Person.where(["user_name = :u", { u: user_name }]).third
    def third
204
      find_nth(2, offset_index)
205 206 207 208 209
    end

    # Same as +third+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def third!
210
      find_nth! 2
211 212 213 214 215 216 217 218 219
    end

    # Find the fourth record.
    # If no order is defined it will order by primary key.
    #
    #   Person.fourth # returns the fourth object fetched by SELECT * FROM people
    #   Person.offset(3).fourth # returns the fourth object from OFFSET 3 (which is OFFSET 6)
    #   Person.where(["user_name = :u", { u: user_name }]).fourth
    def fourth
220
      find_nth(3, offset_index)
221 222 223 224 225
    end

    # Same as +fourth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def fourth!
226
      find_nth! 3
227 228 229 230 231 232 233 234 235
    end

    # Find the fifth record.
    # If no order is defined it will order by primary key.
    #
    #   Person.fifth # returns the fifth object fetched by SELECT * FROM people
    #   Person.offset(3).fifth # returns the fifth object from OFFSET 3 (which is OFFSET 7)
    #   Person.where(["user_name = :u", { u: user_name }]).fifth
    def fifth
236
      find_nth(4, offset_index)
237 238 239 240 241
    end

    # Same as +fifth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def fifth!
242
      find_nth! 4
243 244 245 246 247 248
    end

    # Find the forty-second record. Also known as accessing "the reddit".
    # If no order is defined it will order by primary key.
    #
    #   Person.forty_two # returns the forty-second object fetched by SELECT * FROM people
249
    #   Person.offset(3).forty_two # returns the forty-second object from OFFSET 3 (which is OFFSET 44)
250 251
    #   Person.where(["user_name = :u", { u: user_name }]).forty_two
    def forty_two
252
      find_nth(41, offset_index)
253 254 255 256 257
    end

    # Same as +forty_two+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def forty_two!
258
      find_nth! 41
259 260
    end

261 262
    # Returns +true+ if a record exists in the table that matches the +id+ or
    # conditions given, or +false+ otherwise. The argument can take six forms:
P
Pratik Naik 已提交
263 264 265 266 267
    #
    # * Integer - Finds the record with this primary key.
    # * String - Finds the record with a primary key corresponding to this
    #   string (such as <tt>'5'</tt>).
    # * Array - Finds the record that matches these +find+-style conditions
268
    #   (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
P
Pratik Naik 已提交
269
    # * Hash - Finds the record that matches these +find+-style conditions
270
    #   (such as <tt>{name: 'David'}</tt>).
271 272
    # * +false+ - Returns always +false+.
    # * No args - Returns +false+ if the table is empty, +true+ otherwise.
P
Pratik Naik 已提交
273
    #
274 275
    # For more information about specifying conditions as a hash or array,
    # see the Conditions section in the introduction to <tt>ActiveRecord::Base</tt>.
P
Pratik Naik 已提交
276 277 278 279 280 281 282 283
    #
    # Note: You can't pass in a condition as a string (like <tt>name =
    # 'Jamie'</tt>), since it would be sanitized and then queried against
    # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
    #
    #   Person.exists?(5)
    #   Person.exists?('5')
    #   Person.exists?(['name LIKE ?', "%#{query}%"])
284
    #   Person.exists?(id: [1, 4, 8])
285 286
    #   Person.exists?(name: 'David')
    #   Person.exists?(false)
P
Pratik Naik 已提交
287
    #   Person.exists?
E
Egor Lynko 已提交
288
    def exists?(conditions = :none)
289 290
      if Base === conditions
        conditions = conditions.id
X
Xavier Noria 已提交
291 292 293 294
        ActiveSupport::Deprecation.warn(<<-MSG.squish)
          You are passing an instance of ActiveRecord::Base to `exists?`.
          Please pass the id of the object by calling `.id`
        MSG
295 296
      end

E
Egor Lynko 已提交
297
      return false if !conditions
298

299
      relation = apply_join_dependency(self, construct_join_dependency)
300 301
      return false if ActiveRecord::NullRelation === relation

V
Vipul A M 已提交
302
      relation = relation.except(:select, :order).select(ONE_AS_ONE).limit(1)
A
Aaron Patterson 已提交
303

E
Egor Lynko 已提交
304
      case conditions
P
Pratik Naik 已提交
305
      when Array, Hash
E
Egor Lynko 已提交
306
        relation = relation.where(conditions)
P
Pratik Naik 已提交
307
      else
308
        unless conditions == :none
309
          relation = relation.where(primary_key => conditions)
310
        end
P
Pratik Naik 已提交
311
      end
312

S
Sean Griffin 已提交
313
      connection.select_value(relation, "#{name} Exists", relation.bound_attributes) ? true : false
314 315
    end

316 317 318 319 320 321 322 323 324
    # This method is called whenever no records are found with either a single
    # id or multiple ids and raises a +ActiveRecord::RecordNotFound+ exception.
    #
    # The error message is different depending on whether a single id or
    # multiple ids are provided. If multiple ids are provided, then the number
    # of results obtained should be provided in the +result_size+ argument and
    # the expected number of results should be provided in the +expected_size+
    # argument.
    def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
325
      conditions = arel.where_sql(@klass.arel_engine)
326 327 328
      conditions = " [#{conditions}]" if conditions

      if Array(ids).size == 1
329
        error = "Couldn't find #{@klass.name} with '#{primary_key}'=#{ids}#{conditions}"
330
      else
331
        error = "Couldn't find all #{@klass.name.pluralize} with '#{primary_key}': "
332 333 334 335 336 337
        error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
      end

      raise RecordNotFound, error
    end

338
    private
339

340 341 342 343
    def offset_index
      offset_value || 0
    end

344
    def find_with_associations
345 346 347 348 349 350 351 352 353 354
      # NOTE: the JoinDependency constructed here needs to know about
      #       any joins already present in `self`, so pass them in
      #
      # failing to do so means that in cases like activerecord/test/cases/associations/inner_join_association_test.rb:136
      # incorrect SQL is generated. In that case, the join dependency for
      # SpecialCategorizations is constructed without knowledge of the
      # preexisting join in joins_values to categorizations (by way of
      # the `has_many :through` for categories).
      #
      join_dependency = construct_join_dependency(joins_values)
355 356

      aliases  = join_dependency.aliases
357
      relation = select aliases.columns
A
Aaron Patterson 已提交
358 359
      relation = apply_join_dependency(relation, join_dependency)

360 361
      if block_given?
        yield relation
362
      else
363 364 365
        if ActiveRecord::NullRelation === relation
          []
        else
366
          arel = relation.arel
S
Sean Griffin 已提交
367
          rows = connection.select_all(arel, 'SQL', relation.bound_attributes)
A
Aaron Patterson 已提交
368
          join_dependency.instantiate(rows, aliases)
369
        end
370
      end
371 372
    end

373
    def construct_join_dependency(joins = [])
374
      including = eager_load_values + includes_values
375
      ActiveRecord::Associations::JoinDependency.new(@klass, including, joins)
376 377
    end

378
    def construct_relation_for_association_calculations
379 380 381 382 383 384 385 386 387
      from = arel.froms.first
      if Arel::Table === from
        apply_join_dependency(self, construct_join_dependency)
      else
        # FIXME: as far as I can tell, `from` will always be an Arel::Table.
        # There are no tests that test this branch, but presumably it's
        # possible for `from` to be a list?
        apply_join_dependency(self, construct_join_dependency(from))
      end
388 389
    end

P
Pratik Naik 已提交
390
    def apply_join_dependency(relation, join_dependency)
391
      relation = relation.except(:includes, :eager_load, :preload)
392
      relation = relation.joins join_dependency
393

394 395 396
      if using_limitable_reflections?(join_dependency.reflections)
        relation
      else
397 398
        if relation.limit_value
          limited_ids = limited_ids_for(relation)
399
          limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids)
400
        end
401
        relation.except(:limit, :offset)
402 403 404
      end
    end

405
    def limited_ids_for(relation)
406 407
      values = @klass.connection.columns_for_distinct(
        "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
408

409
      relation = relation.except(:select).select(values).distinct!
410
      arel = relation.arel
411

S
Sean Griffin 已提交
412
      id_rows = @klass.connection.select_all(arel, 'SQL', relation.bound_attributes)
413
      id_rows.map {|row| row[primary_key]}
414 415
    end

416
    def using_limitable_reflections?(reflections)
417
      reflections.none?(&:collection?)
418 419 420 421
    end

    protected

422
    def find_with_ids(*ids)
423 424
      raise UnknownPrimaryKey.new(@klass) if primary_key.nil?

P
Pratik Naik 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438
      expects_array = ids.first.kind_of?(Array)
      return ids.first if expects_array && ids.first.empty?

      ids = ids.flatten.compact.uniq

      case ids.size
      when 0
        raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
      when 1
        result = find_one(ids.first)
        expects_array ? [ result ] : result
      else
        find_some(ids)
      end
439 440
    rescue RangeError
      raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID"
P
Pratik Naik 已提交
441 442
    end

443
    def find_one(id)
444 445
      if ActiveRecord::Base === id
        id = id.id
X
Xavier Noria 已提交
446 447 448 449
        ActiveSupport::Deprecation.warn(<<-MSG.squish)
          You are passing an instance of ActiveRecord::Base to `find`.
          Please pass the id of the object by calling `.id`
        MSG
450
      end
A
Aaron Patterson 已提交
451

452
      relation = where(primary_key => id)
453
      record = relation.take
454

455
      raise_record_not_found_exception!(id, 0, 1) unless record
456 457 458 459 460

      record
    end

    def find_some(ids)
461
      result = where(primary_key => ids).to_a
462 463

      expected_size =
464 465
        if limit_value && ids.size > limit_value
          limit_value
466 467 468 469 470
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
471 472
      if offset_value && (ids.size - offset_value < expected_size)
        expected_size = ids.size - offset_value
473 474 475 476 477
      end

      if result.size == expected_size
        result
      else
478
        raise_record_not_found_exception!(ids, result.size, expected_size)
479 480 481
      end
    end

482 483
    def find_take
      if loaded?
484
        @records.first
485
      else
486
        @take ||= limit(1).to_a.first
487 488 489
      end
    end

490
    def find_nth(index, offset)
P
Pratik Naik 已提交
491
      if loaded?
492
        @records[index]
P
Pratik Naik 已提交
493
      else
494
        offset += index
495
        @offsets[offset] ||= find_nth_with_limit(offset, 1).first
496 497 498
      end
    end

499
    def find_nth!(index)
500
      find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
501 502
    end

503
    def find_nth_with_limit(offset, limit)
504 505 506 507 508 509 510 511
      relation = if order_values.empty? && primary_key
                   order(arel_table[primary_key].asc)
                 else
                   self
                 end

      relation = relation.offset(offset) unless offset.zero?
      relation.limit(limit).to_a
P
Pratik Naik 已提交
512 513 514 515 516 517
    end

    def find_last
      if loaded?
        @records.last
      else
N
Nick Howard 已提交
518
        @last ||=
L
Lauro Caetano 已提交
519
          if limit_value
N
Nick Howard 已提交
520 521
            to_a.last
          else
522
            reverse_order.limit(1).to_a.first
N
Nick Howard 已提交
523
          end
P
Pratik Naik 已提交
524 525
      end
    end
526 527
  end
end