finder_methods.rb 20.3 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
    #
V
Vijay Dev 已提交
21
    # NOTE: The returned records may not be in the same order as the ids you
22 23
    # provide since database rows are unordered. You will need to provide an explicit QueryMethods#order
    # option if you want the results to be 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.find_or_initialize_by(name: 'Spartacus', rating: 4)
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.find_or_create_by(name: 'Spartacus', rating: 4)
51
    #   # returns the first item or creates it and returns it.
52
    #
53
    # ==== Alternatives for #find
54 55
    #
    #   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
62
    #   # returns an Array of ids.
63 64
    #
    #   Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
65
    #   # returns an Array of the required fields.
66
    def find(*args)
67 68
      return super if block_given?
      find_with_ids(*args)
69 70
    end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      relation = self unless eager_loading?
      relation ||= apply_join_dependency(self, construct_join_dependency(eager_loading: false))
315

316
      return false if ActiveRecord::NullRelation === relation
317

318
      relation = construct_relation_for_exists(relation, conditions)
319

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

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

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

349
        raise RecordNotFound.new(error, name, primary_key, ids)
350
      end
351 352
    end

353
    private
354

355 356 357
      def offset_index
        offset_value || 0
      end
358

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
      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).
        #
        join_dependency = construct_join_dependency(joins_values)

        aliases  = join_dependency.aliases
        relation = select aliases.columns
        relation = apply_join_dependency(relation, join_dependency)

        if block_given?
          yield relation
377
        else
378 379 380
          if ActiveRecord::NullRelation === relation
            []
          else
381
            rows = skip_query_cache_if_necessary { connection.select_all(relation.arel, "SQL", relation.bound_attributes) }
382 383
            join_dependency.instantiate(rows, aliases)
          end
384
        end
385
      end
386

387
      def construct_relation_for_exists(relation, conditions)
388
        relation = relation.except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1)
389 390 391 392 393 394 395 396 397 398 399

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

        relation
      end

400 401
      def construct_join_dependency(joins = [], eager_loading: true)
        including = eager_load_values + includes_values
402
        ActiveRecord::Associations::JoinDependency.new(klass, table, including, joins, eager_loading: eager_loading)
403
      end
404

405 406 407
      def construct_relation_for_association_calculations
        apply_join_dependency(self, construct_join_dependency(joins_values))
      end
408

409
      def apply_join_dependency(relation, join_dependency)
410
        relation = relation.except(:includes, :eager_load, :preload).joins!(join_dependency)
411

412 413 414 415 416 417 418 419
        if using_limitable_reflections?(join_dependency.reflections)
          relation
        else
          if relation.limit_value
            limited_ids = limited_ids_for(relation)
            limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids)
          end
          relation.except(:limit, :offset)
420
        end
421 422
      end

423 424 425
      def limited_ids_for(relation)
        values = @klass.connection.columns_for_distinct(
          "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
426

427
        relation = relation.except(:select).select(values).distinct!
428

429
        id_rows = skip_query_cache_if_necessary { @klass.connection.select_all(relation.arel, "SQL", relation.bound_attributes) }
430
        id_rows.map { |row| row[primary_key] }
431
      end
432

433 434 435
      def using_limitable_reflections?(reflections)
        reflections.none?(&:collection?)
      end
436

K
kami-zh 已提交
437 438
      def find_with_ids(*ids)
        raise UnknownPrimaryKey.new(@klass) if primary_key.nil?
439

K
kami-zh 已提交
440 441
        expects_array = ids.first.kind_of?(Array)
        return ids.first if expects_array && ids.first.empty?
442

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

K
kami-zh 已提交
445 446 447 448 449 450 451 452
        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)
453
        end
K
kami-zh 已提交
454 455 456
      rescue ::RangeError
        raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID"
      end
P
Pratik Naik 已提交
457

K
kami-zh 已提交
458 459 460 461 462 463
      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
464
        end
465

K
kami-zh 已提交
466 467 468 469
        relation = where(primary_key => id)
        record = relation.take

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

K
kami-zh 已提交
471 472
        record
      end
473

K
kami-zh 已提交
474 475
      def find_some(ids)
        return find_some_ordered(ids) unless order_values.present?
476

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

K
kami-zh 已提交
479 480 481
        expected_size =
          if limit_value && ids.size > limit_value
            limit_value
482
          else
K
kami-zh 已提交
483
            ids.size
484
          end
K
kami-zh 已提交
485 486 487 488

        # 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
489
        end
490

K
kami-zh 已提交
491 492 493 494 495 496
        if result.size == expected_size
          result
        else
          raise_record_not_found_exception!(ids, result.size, expected_size)
        end
      end
497

K
kami-zh 已提交
498 499
      def find_some_ordered(ids)
        ids = ids.slice(offset_value || 0, limit_value || ids.size) || []
500

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

K
kami-zh 已提交
503 504
        if result.size == ids.size
          pk_type = @klass.type_for_attribute(primary_key)
505

K
kami-zh 已提交
506 507 508 509
          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)
510
        end
K
kami-zh 已提交
511
      end
512

K
kami-zh 已提交
513 514 515 516 517
      def find_take
        if loaded?
          records.first
        else
          @take ||= limit(1).records.first
518
        end
K
kami-zh 已提交
519
      end
520

K
kami-zh 已提交
521 522 523 524 525
      def find_take_with_limit(limit)
        if loaded?
          records.take(limit)
        else
          limit(limit).to_a
526
        end
K
kami-zh 已提交
527
      end
528

K
kami-zh 已提交
529 530 531 532 533 534 535 536
      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
537
          relation = ordered_relation
K
kami-zh 已提交
538

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

K
kami-zh 已提交
548 549 550 551
      def find_nth_from_last(index)
        if loaded?
          records[-index]
        else
552
          relation = ordered_relation
553

K
kami-zh 已提交
554 555 556 557 558 559
          relation.to_a[-index]
          # TODO: can be made more performant on large result sets by
          # for instance, last(index)[-index] (which would require
          # refactoring the last(n) finder method to make test suite pass),
          # or by using a combination of reverse_order, limit, and offset,
          # e.g., reverse_order.offset(index-1).first
560
        end
K
kami-zh 已提交
561 562 563 564 565
      end

      def find_last(limit)
        limit ? records.last(limit) : records.last
      end
566 567 568 569 570 571 572 573

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