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 cannot be found for the requested ids, then ActiveRecord::RecordNotFound will be raised.
11
    # If the primary key is an integer, find by id coerces its arguments by 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 83
    end

84 85
    # Like #find_by, except that if no record is found, raises
    # an ActiveRecord::RecordNotFound error.
86 87
    def find_by!(arg, *args)
      where(arg, *args).take!
88 89
    end

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

101 102
    # Same as #take but raises ActiveRecord::RecordNotFound if no record
    # is found. Note that #take! accepts no arguments.
103
    def take!
104
      take || raise_record_not_found_exception!
105 106
    end

107 108 109
    # Find the first record (or first N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
110
    #   Person.first # returns the first object fetched by SELECT * FROM people ORDER BY people.id LIMIT 1
111
    #   Person.where(["user_name = ?", user_name]).first
A
AvnerCohen 已提交
112
    #   Person.where(["user_name = :u", { u: user_name }]).first
113
    #   Person.order("created_on DESC").offset(5).first
114
    #   Person.first(3) # returns the first three objects fetched by SELECT * FROM people ORDER BY people.id LIMIT 3
115
    #
116
    def first(limit = nil)
117
      check_reorder_deprecation
118

119
      if limit
120
        find_nth_with_limit(0, limit)
121
      else
122
        find_nth 0
123
      end
124 125
    end

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

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

150
      result = ordered_relation.limit(limit)
151 152 153
      result = result.reverse_order!

      limit ? result.reverse : result.first
154 155
    end

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

162 163 164 165 166 167 168
    # 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
169
      find_nth 1
170 171
    end

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

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

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

220
    # Same as #fifth but raises ActiveRecord::RecordNotFound if no record
221 222
    # is found.
    def fifth!
223
      fifth || raise_record_not_found_exception!
224 225
    end

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

236
    # Same as #forty_two but raises ActiveRecord::RecordNotFound if no record
237 238
    # is found.
    def forty_two!
239
      forty_two || raise_record_not_found_exception!
240 241
    end

242 243 244
    # Find the third-to-last record.
    # If no order is defined it will order by primary key.
    #
245 246 247 248
    #   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
249
      find_nth_from_last 3
250 251
    end

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

    # Find the second-to-last record.
    # If no order is defined it will order by primary key.
    #
261 262 263 264
    #   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
265
      find_nth_from_last 2
266 267
    end

268
    # Same as #second_to_last but raises ActiveRecord::RecordNotFound if no record
269
    # is found.
270
    def second_to_last!
271
      second_to_last || raise_record_not_found_exception!
272 273
    end

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

310 311
      return false if !conditions || limit_value == 0

312
      if eager_loading?
313
        relation = apply_join_dependency(eager_loading: false)
314 315
        return relation.exists?(conditions)
      end
316

317
      relation = construct_relation_for_exists(conditions)
318

D
Dan Fitch 已提交
319
      skip_query_cache_if_necessary { connection.select_one(relation.arel, "#{name} Exists?") } ? true : false
320 321
    end

322
    # This method is called whenever no records are found with either a single
323
    # id or multiple ids and raises an ActiveRecord::RecordNotFound exception.
324 325 326 327 328 329
    #
    # 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.
330
    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 已提交
331
      conditions = arel.where_sql(@klass)
332
      conditions = " [#{conditions}]" if conditions
333
      name = @klass.name
334

335
      if ids.nil?
336
        error = +"Couldn't find #{name}"
337
        error << " with#{conditions}" if conditions
338
        raise RecordNotFound.new(error, name, key)
339
      elsif Array(ids).size == 1
340 341
        error = "Couldn't find #{name} with '#{key}'=#{ids}#{conditions}"
        raise RecordNotFound.new(error, name, key, ids)
342
      else
343
        error = +"Couldn't find all #{name.pluralize} with '#{key}': "
344 345
        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
346
        raise RecordNotFound.new(error, name, key, ids)
347
      end
348 349
    end

350
    private
351 352 353 354 355 356 357 358 359
      def check_reorder_deprecation
        if !order_values.empty? && order_values.all?(&:blank?)
          blank_value = order_values.first
          ActiveSupport::Deprecation.warn(<<~MSG.squish)
            `.reorder(#{blank_value.inspect})` with `.first` / `.first!` no longer
            takes non-deterministic result in Rails 6.2.
            To continue taking non-deterministic result, use `.take` / `.take!` instead.
          MSG
        end
360
      end
361

362
      def construct_relation_for_exists(conditions)
363 364 365
        conditions = sanitize_forbidden_attributes(conditions)

        if distinct_value && offset_value
366
          relation = except(:order).limit!(1)
367 368 369
        else
          relation = except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1)
        end
370 371 372

        case conditions
        when Array, Hash
373
          relation.where!(conditions) unless conditions.empty?
374 375 376 377 378 379 380
        else
          relation.where!(primary_key => conditions) unless conditions == :none
        end

        relation
      end

381
      def apply_join_dependency(eager_loading: group_values.empty?)
382 383 384
        join_dependency = construct_join_dependency(
          eager_load_values + includes_values, Arel::Nodes::OuterJoin
        )
385
        relation = except(:includes, :eager_load, :preload).joins!(join_dependency)
386

387 388 389 390 391 392 393 394 395 396
        if eager_loading && !(
            using_limitable_reflections?(join_dependency.reflections) &&
            using_limitable_reflections?(
              construct_join_dependency(
                select_association_list(joins_values).concat(
                  select_association_list(left_outer_joins_values)
                ), nil
              ).reflections
            )
        )
397
          if has_limit_or_offset?
398 399 400
            limited_ids = limited_ids_for(relation)
            limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids)
          end
401 402 403 404 405 406 407
          relation.limit_value = relation.offset_value = nil
        end

        if block_given?
          yield relation, join_dependency
        else
          relation
408
        end
409 410
      end

411 412
      def limited_ids_for(relation)
        values = @klass.connection.columns_for_distinct(
413
          connection.visitor.compile(arel_attribute(primary_key)),
414 415
          relation.order_values
        )
416

417
        relation = relation.except(:select).select(values).distinct!
418

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

423 424 425
      def using_limitable_reflections?(reflections)
        reflections.none?(&:collection?)
      end
426

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

K
kami-zh 已提交
430
        expects_array = ids.first.kind_of?(Array)
431
        return [] if expects_array && ids.first.empty?
432

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

435 436
        model_name = @klass.name

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

K
kami-zh 已提交
449 450 451 452 453 454
      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
455
        end
456

K
kami-zh 已提交
457 458 459 460
        relation = where(primary_key => id)
        record = relation.take

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

K
kami-zh 已提交
462 463
        record
      end
464

K
kami-zh 已提交
465 466
      def find_some(ids)
        return find_some_ordered(ids) unless order_values.present?
467

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

K
kami-zh 已提交
470 471 472
        expected_size =
          if limit_value && ids.size > limit_value
            limit_value
473
          else
K
kami-zh 已提交
474
            ids.size
475
          end
K
kami-zh 已提交
476 477 478 479

        # 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
480
        end
481

K
kami-zh 已提交
482 483 484 485 486 487
        if result.size == expected_size
          result
        else
          raise_record_not_found_exception!(ids, result.size, expected_size)
        end
      end
488

K
kami-zh 已提交
489 490
      def find_some_ordered(ids)
        ids = ids.slice(offset_value || 0, limit_value || ids.size) || []
491

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

K
kami-zh 已提交
494 495
        if result.size == ids.size
          pk_type = @klass.type_for_attribute(primary_key)
496

K
kami-zh 已提交
497 498 499 500
          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)
501
        end
K
kami-zh 已提交
502
      end
503

K
kami-zh 已提交
504 505 506 507 508
      def find_take
        if loaded?
          records.first
        else
          @take ||= limit(1).records.first
509
        end
K
kami-zh 已提交
510
      end
511

K
kami-zh 已提交
512 513 514 515 516
      def find_take_with_limit(limit)
        if loaded?
          records.take(limit)
        else
          limit(limit).to_a
517
        end
K
kami-zh 已提交
518
      end
519

K
kami-zh 已提交
520
      def find_nth(index)
521
        @offsets[index] ||= find_nth_with_limit(index, 1).first
K
kami-zh 已提交
522 523 524 525 526 527
      end

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

530 531 532 533 534
          if limit_value
            limit = [limit_value - index, limit].min
          end

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

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

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

      def find_last(limit)
        limit ? records.last(limit) : records.last
      end
560 561

      def ordered_relation
562
        if order_values.empty? && (implicit_order_column || primary_key)
563 564 565 566 567
          if implicit_order_column && primary_key && implicit_order_column != primary_key
            order(arel_attribute(implicit_order_column).asc, arel_attribute(primary_key).asc)
          else
            order(arel_attribute(implicit_order_column || primary_key).asc)
          end
568 569 570 571
        else
          self
        end
      end
572 573
  end
end