finder_methods.rb 20.1 KB
Newer Older
1 2
# frozen_string_literal: true

3
require "active_support/core_ext/string/filters"
4

5 6
module ActiveRecord
  module FinderMethods
7
    ONE_AS_ONE = "1 AS one"
V
Vipul A M 已提交
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]).
10
    # If one or more records can not be found for the requested ids, then RecordNotFound will be raised. If the primary key
11
    # is an integer, find by id coerces its arguments using +to_i+.
P
Pratik Naik 已提交
12
    #
13 14 15 16 17 18
    #   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 已提交
19
    #   Person.where("administrator = 1").order("created_on DESC").find(1)
P
Pratik Naik 已提交
20
    #
21 22 23 24
    # NOTE: The returned records are in the same order as the ids you provide.
    # If you want the results to be sorted by database, you can use ActiveRecord::QueryMethods#where
    # method and provide an explicit ActiveRecord::QueryMethods#order option.
    # But ActiveRecord::QueryMethods#where method doesn't raise ActiveRecord::RecordNotFound.
P
Pratik Naik 已提交
25
    #
26
    # ==== Find with lock
P
Pratik Naik 已提交
27 28 29
    #
    # 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
30
    # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
P
Pratik Naik 已提交
31 32 33 34
    # transaction has to wait until the first is finished; we get the
    # expected <tt>person.visits == 4</tt>.
    #
    #   Person.transaction do
E
Emilio Tagua 已提交
35
    #     person = Person.lock(true).find(1)
P
Pratik Naik 已提交
36 37 38
    #     person.visits += 1
    #     person.save!
    #   end
39
    #
40
    # ==== Variations of #find
41
    #
42
    #   Person.where(name: 'Spartacus', rating: 4)
V
Vijay Dev 已提交
43
    #   # returns a chainable list (which can be empty).
44 45
    #
    #   Person.find_by(name: 'Spartacus', rating: 4)
V
Vijay Dev 已提交
46
    #   # returns the first item or nil.
47
    #
48
    #   Person.find_or_initialize_by(name: 'Spartacus', rating: 4)
V
Vijay Dev 已提交
49
    #   # returns the first item or returns a new instance (requires you call .save to persist against the database).
50
    #
51
    #   Person.find_or_create_by(name: 'Spartacus', rating: 4)
52
    #   # returns the first item or creates it and returns it.
53
    #
54
    # ==== Alternatives for #find
55 56
    #
    #   Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
V
Vijay Dev 已提交
57
    #   # returns a boolean indicating if any record with the given conditions exist.
58
    #
59
    #   Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
V
Vijay Dev 已提交
60
    #   # returns a chainable list of instances with only the mentioned fields.
61 62
    #
    #   Person.where(name: 'Spartacus', rating: 4).ids
63
    #   # returns an Array of ids.
64 65
    #
    #   Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
66
    #   # returns an Array of the required fields.
67
    def find(*args)
68 69
      return super if block_given?
      find_with_ids(*args)
70 71
    end

72
    # Finds the first record matching the specified conditions. There
73
    # is no implied ordering so if order matters, you should specify it
74 75 76 77 78 79
    # 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
80 81
    def find_by(arg, *args)
      where(arg, *args).take
82
    rescue ::RangeError
83
      nil
84 85
    end

86 87
    # Like #find_by, except that if no record is found, raises
    # an ActiveRecord::RecordNotFound error.
88 89
    def find_by!(arg, *args)
      where(arg, *args).take!
90
    rescue ::RangeError
91
      raise RecordNotFound.new("Couldn't find #{@klass.name} with an out of range value",
92
                               @klass.name, @klass.primary_key)
93 94
    end

95 96 97 98
    # 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.
    #
99
    #   Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
100 101 102
    #   Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
    #   Person.where(["name LIKE '%?'", name]).take
    def take(limit = nil)
103
      limit ? find_take_with_limit(limit) : find_take
104 105
    end

106 107
    # Same as #take but raises ActiveRecord::RecordNotFound if no record
    # is found. Note that #take! accepts no arguments.
108
    def take!
109
      take || raise_record_not_found_exception!
110 111
    end

112 113 114
    # Find the first record (or first N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
115
    #   Person.first # returns the first object fetched by SELECT * FROM people ORDER BY people.id LIMIT 1
116
    #   Person.where(["user_name = ?", user_name]).first
A
AvnerCohen 已提交
117
    #   Person.where(["user_name = :u", { u: user_name }]).first
118
    #   Person.order("created_on DESC").offset(5).first
119
    #   Person.first(3) # returns the first three objects fetched by SELECT * FROM people ORDER BY people.id LIMIT 3
120
    #
121
    def first(limit = nil)
122
      if limit
123
        find_nth_with_limit(0, limit)
124
      else
125
        find_nth 0
126
      end
127 128
    end

129 130
    # Same as #first but raises ActiveRecord::RecordNotFound if no record
    # is found. Note that #first! accepts no arguments.
P
Pratik Naik 已提交
131
    def first!
132
      first || raise_record_not_found_exception!
133 134
    end

135 136 137
    # Find the last record (or last N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
138 139 140
    #   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
141
    #   Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
142
    #
143
    # Take note that in that last case, the results are sorted in ascending order:
144
    #
145
    #   [#<Person id:2>, #<Person id:3>, #<Person id:4>]
146
    #
147
    # and not:
148
    #
149
    #   [#<Person id:4>, #<Person id:3>, #<Person id:2>]
150
    def last(limit = nil)
151
      return find_last(limit) if loaded? || has_limit_or_offset?
152

153
      result = ordered_relation.limit(limit)
154 155 156
      result = result.reverse_order!

      limit ? result.reverse : result.first
157 158
    end

159 160
    # Same as #last but raises ActiveRecord::RecordNotFound if no record
    # is found. Note that #last! accepts no arguments.
P
Pratik Naik 已提交
161
    def last!
162
      last || raise_record_not_found_exception!
163 164
    end

165 166 167 168 169 170 171
    # 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
172
      find_nth 1
173 174
    end

175
    # Same as #second but raises ActiveRecord::RecordNotFound if no record
176 177
    # is found.
    def second!
178
      second || raise_record_not_found_exception!
179 180 181 182 183 184 185 186 187
    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
188
      find_nth 2
189 190
    end

191
    # Same as #third but raises ActiveRecord::RecordNotFound if no record
192 193
    # is found.
    def third!
194
      third || raise_record_not_found_exception!
195 196 197 198 199 200 201 202 203
    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
204
      find_nth 3
205 206
    end

207
    # Same as #fourth but raises ActiveRecord::RecordNotFound if no record
208 209
    # is found.
    def fourth!
210
      fourth || raise_record_not_found_exception!
211 212 213 214 215 216 217 218 219
    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
220
      find_nth 4
221 222
    end

223
    # Same as #fifth but raises ActiveRecord::RecordNotFound if no record
224 225
    # is found.
    def fifth!
226
      fifth || raise_record_not_found_exception!
227 228
    end

229
    # Find the forty-second record. Also known as accessing "the reddit".
230 231 232
    # If no order is defined it will order by primary key.
    #
    #   Person.forty_two # returns the forty-second object fetched by SELECT * FROM people
233
    #   Person.offset(3).forty_two # returns the forty-second object from OFFSET 3 (which is OFFSET 44)
234 235
    #   Person.where(["user_name = :u", { u: user_name }]).forty_two
    def forty_two
236
      find_nth 41
237 238
    end

239
    # Same as #forty_two but raises ActiveRecord::RecordNotFound if no record
240 241
    # is found.
    def forty_two!
242
      forty_two || raise_record_not_found_exception!
243 244
    end

245 246 247
    # Find the third-to-last record.
    # If no order is defined it will order by primary key.
    #
248 249 250 251
    #   Person.third_to_last # returns the third-to-last object fetched by SELECT * FROM people
    #   Person.offset(3).third_to_last # returns the third-to-last object from OFFSET 3
    #   Person.where(["user_name = :u", { u: user_name }]).third_to_last
    def third_to_last
252
      find_nth_from_last 3
253 254
    end

255
    # Same as #third_to_last but raises ActiveRecord::RecordNotFound if no record
256
    # is found.
257
    def third_to_last!
258
      third_to_last || raise_record_not_found_exception!
259 260 261 262 263
    end

    # Find the second-to-last record.
    # If no order is defined it will order by primary key.
    #
264 265 266 267
    #   Person.second_to_last # returns the second-to-last object fetched by SELECT * FROM people
    #   Person.offset(3).second_to_last # returns the second-to-last object from OFFSET 3
    #   Person.where(["user_name = :u", { u: user_name }]).second_to_last
    def second_to_last
268
      find_nth_from_last 2
269 270
    end

271
    # Same as #second_to_last but raises ActiveRecord::RecordNotFound if no record
272
    # is found.
273
    def second_to_last!
274
      second_to_last || raise_record_not_found_exception!
275 276
    end

277 278
    # 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 已提交
279 280 281 282 283
    #
    # * 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
284
    #   (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
P
Pratik Naik 已提交
285
    # * Hash - Finds the record that matches these +find+-style conditions
286
    #   (such as <tt>{name: 'David'}</tt>).
287
    # * +false+ - Returns always +false+.
N
Nikolai B 已提交
288
    # * No args - Returns +false+ if the relation is empty, +true+ otherwise.
P
Pratik Naik 已提交
289
    #
290
    # For more information about specifying conditions as a hash or array,
291
    # see the Conditions section in the introduction to ActiveRecord::Base.
P
Pratik Naik 已提交
292 293 294 295 296 297 298 299
    #
    # 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}%"])
300
    #   Person.exists?(id: [1, 4, 8])
301 302
    #   Person.exists?(name: 'David')
    #   Person.exists?(false)
P
Pratik Naik 已提交
303
    #   Person.exists?
N
Nikolai B 已提交
304
    #   Person.where(name: 'Spartacus', rating: 4).exists?
E
Egor Lynko 已提交
305
    def exists?(conditions = :none)
306
      if Base === conditions
307
        raise ArgumentError, <<-MSG.squish
X
Xavier Noria 已提交
308
          You are passing an instance of ActiveRecord::Base to `exists?`.
309
          Please pass the id of the object by calling `.id`.
X
Xavier Noria 已提交
310
        MSG
311 312
      end

313 314
      return false if !conditions || limit_value == 0

315 316 317 318
      if eager_loading?
        relation = apply_join_dependency(construct_join_dependency(eager_loading: false))
        return relation.exists?(conditions)
      end
319

320
      relation = construct_relation_for_exists(conditions)
321

322
      skip_query_cache_if_necessary { connection.select_value(relation.arel, "#{name} Exists") } ? true : false
323
    rescue ::RangeError
324
      false
325 326
    end

327
    # This method is called whenever no records are found with either a single
328
    # id or multiple ids and raises an ActiveRecord::RecordNotFound exception.
329 330 331 332 333 334
    #
    # 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.
335
    def raise_record_not_found_exception!(ids = nil, result_size = nil, expected_size = nil, key = primary_key, not_found_ids = nil) # :nodoc:
R
Ryuta Kamizono 已提交
336
      conditions = arel.where_sql(@klass)
337
      conditions = " [#{conditions}]" if conditions
338
      name = @klass.name
339

340
      if ids.nil?
341
        error = "Couldn't find #{name}".dup
342
        error << " with#{conditions}" if conditions
343
        raise RecordNotFound.new(error, name, key)
344
      elsif Array(ids).size == 1
345 346
        error = "Couldn't find #{name} with '#{key}'=#{ids}#{conditions}"
        raise RecordNotFound.new(error, name, key, ids)
347
      else
348
        error = "Couldn't find all #{name.pluralize} with '#{key}': ".dup
349 350
        error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})."
        error << " Couldn't find #{name.pluralize(not_found_ids.size)} with #{key.to_s.pluralize(not_found_ids.size)} #{not_found_ids.join(', ')}." if not_found_ids
351
        raise RecordNotFound.new(error, name, key, ids)
352
      end
353 354
    end

355
    private
356

357 358 359
      def offset_index
        offset_value || 0
      end
360

361 362 363 364 365 366 367 368 369 370
      def find_with_associations
        # 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).
        #
371
        join_dependency = construct_join_dependency
372

373 374
        relation = apply_join_dependency(join_dependency)
        relation._select!(join_dependency.aliases.columns)
375

376
        yield relation, join_dependency
377
      end
378

379 380
      def construct_relation_for_exists(conditions)
        relation = except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1)
381 382 383 384 385 386 387 388 389 390 391

        case conditions
        when Array, Hash
          relation.where!(conditions)
        else
          relation.where!(primary_key => conditions) unless conditions == :none
        end

        relation
      end

392
      def construct_join_dependency(eager_loading: true)
393
        including = eager_load_values + includes_values
394
        ActiveRecord::Associations::JoinDependency.new(
395
          klass, table, including, alias_tracker(joins_values), eager_loading: eager_loading
396
        )
397
      end
398

399
      def apply_join_dependency(join_dependency = construct_join_dependency)
400
        relation = except(:includes, :eager_load, :preload).joins!(join_dependency)
401

402 403 404
        if using_limitable_reflections?(join_dependency.reflections)
          relation
        else
405
          if has_limit_or_offset?
406 407 408 409
            limited_ids = limited_ids_for(relation)
            limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids)
          end
          relation.except(:limit, :offset)
410
        end
411 412
      end

413 414
      def limited_ids_for(relation)
        values = @klass.connection.columns_for_distinct(
415 416 417
          connection.column_name_from_arel_node(arel_attribute(primary_key)),
          relation.order_values
        )
418

419
        relation = relation.except(:select).select(values).distinct!
420

421
        id_rows = skip_query_cache_if_necessary { @klass.connection.select_all(relation.arel, "SQL") }
422
        id_rows.map { |row| row[primary_key] }
423
      end
424

425 426 427
      def using_limitable_reflections?(reflections)
        reflections.none?(&:collection?)
      end
428

K
kami-zh 已提交
429 430
      def find_with_ids(*ids)
        raise UnknownPrimaryKey.new(@klass) if primary_key.nil?
431

K
kami-zh 已提交
432 433
        expects_array = ids.first.kind_of?(Array)
        return ids.first if expects_array && ids.first.empty?
434

K
kami-zh 已提交
435
        ids = ids.flatten.compact.uniq
P
Pratik Naik 已提交
436

437 438
        model_name = @klass.name

K
kami-zh 已提交
439 440
        case ids.size
        when 0
441 442
          error_message = "Couldn't find #{model_name} without an ID"
          raise RecordNotFound.new(error_message, model_name, primary_key)
K
kami-zh 已提交
443 444 445 446 447
        when 1
          result = find_one(ids.first)
          expects_array ? [ result ] : result
        else
          find_some(ids)
448
        end
K
kami-zh 已提交
449
      rescue ::RangeError
450 451
        error_message = "Couldn't find #{model_name} with an out of range ID"
        raise RecordNotFound.new(error_message, model_name, primary_key, ids)
K
kami-zh 已提交
452
      end
P
Pratik Naik 已提交
453

K
kami-zh 已提交
454 455 456 457 458 459
      def find_one(id)
        if ActiveRecord::Base === id
          raise ArgumentError, <<-MSG.squish
            You are passing an instance of ActiveRecord::Base to `find`.
            Please pass the id of the object by calling `.id`.
          MSG
460
        end
461

K
kami-zh 已提交
462 463 464 465
        relation = where(primary_key => id)
        record = relation.take

        raise_record_not_found_exception!(id, 0, 1) unless record
466

K
kami-zh 已提交
467 468
        record
      end
469

K
kami-zh 已提交
470 471
      def find_some(ids)
        return find_some_ordered(ids) unless order_values.present?
472

K
kami-zh 已提交
473
        result = where(primary_key => ids).to_a
474

K
kami-zh 已提交
475 476 477
        expected_size =
          if limit_value && ids.size > limit_value
            limit_value
478
          else
K
kami-zh 已提交
479
            ids.size
480
          end
K
kami-zh 已提交
481 482 483 484

        # 11 ids with limit 3, offset 9 should give 2 results.
        if offset_value && (ids.size - offset_value < expected_size)
          expected_size = ids.size - offset_value
485
        end
486

K
kami-zh 已提交
487 488 489 490 491 492
        if result.size == expected_size
          result
        else
          raise_record_not_found_exception!(ids, result.size, expected_size)
        end
      end
493

K
kami-zh 已提交
494 495
      def find_some_ordered(ids)
        ids = ids.slice(offset_value || 0, limit_value || ids.size) || []
496

K
kami-zh 已提交
497
        result = except(:limit, :offset).where(primary_key => ids).records
498

K
kami-zh 已提交
499 500
        if result.size == ids.size
          pk_type = @klass.type_for_attribute(primary_key)
501

K
kami-zh 已提交
502 503 504 505
          records_by_id = result.index_by(&:id)
          ids.map { |id| records_by_id.fetch(pk_type.cast(id)) }
        else
          raise_record_not_found_exception!(ids, result.size, ids.size)
506
        end
K
kami-zh 已提交
507
      end
508

K
kami-zh 已提交
509 510 511 512 513
      def find_take
        if loaded?
          records.first
        else
          @take ||= limit(1).records.first
514
        end
K
kami-zh 已提交
515
      end
516

K
kami-zh 已提交
517 518 519 520 521
      def find_take_with_limit(limit)
        if loaded?
          records.take(limit)
        else
          limit(limit).to_a
522
        end
K
kami-zh 已提交
523
      end
524

K
kami-zh 已提交
525 526 527 528 529 530 531 532
      def find_nth(index)
        @offsets[offset_index + index] ||= find_nth_with_limit(index, 1).first
      end

      def find_nth_with_limit(index, limit)
        if loaded?
          records[index, limit] || []
        else
533
          relation = ordered_relation
K
kami-zh 已提交
534

535 536 537 538 539 540
          if limit_value.nil? || index < limit_value
            relation = relation.offset(offset_index + index) unless index.zero?
            relation.limit(limit).to_a
          else
            []
          end
541
        end
K
kami-zh 已提交
542
      end
543

K
kami-zh 已提交
544 545 546 547
      def find_nth_from_last(index)
        if loaded?
          records[-index]
        else
548
          relation = ordered_relation
549

550 551 552 553 554
          if equal?(relation) || has_limit_or_offset?
            relation.records[-index]
          else
            relation.last(index)[-index]
          end
555
        end
K
kami-zh 已提交
556 557 558 559 560
      end

      def find_last(limit)
        limit ? records.last(limit) : records.last
      end
561 562 563 564 565 566 567 568

      def ordered_relation
        if order_values.empty? && primary_key
          order(arel_attribute(primary_key).asc)
        else
          self
        end
      end
569 570
  end
end