finder_methods.rb 16.6 KB
Newer Older
1 2
module ActiveRecord
  module FinderMethods
V
Vipul A M 已提交
3 4
    ONE_AS_ONE = '1 AS one'

5 6 7
    # 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 已提交
8
    #
9 10 11 12 13 14
    #   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 已提交
15
    #   Person.where("administrator = 1").order("created_on DESC").find(1)
P
Pratik Naik 已提交
16
    #
V
Vijay Dev 已提交
17
    # <tt>ActiveRecord::RecordNotFound</tt> will be raised if one or more ids are not found.
18
    #
V
Vijay Dev 已提交
19 20 21
    # 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 已提交
22
    #
23
    # ==== Find with lock
P
Pratik Naik 已提交
24 25 26
    #
    # 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
27
    # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
P
Pratik Naik 已提交
28 29 30 31
    # transaction has to wait until the first is finished; we get the
    # expected <tt>person.visits == 4</tt>.
    #
    #   Person.transaction do
E
Emilio Tagua 已提交
32
    #     person = Person.lock(true).find(1)
P
Pratik Naik 已提交
33 34 35
    #     person.visits += 1
    #     person.save!
    #   end
36 37
    #
    # ==== Variations of +find+
38
    #
39
    #   Person.where(name: 'Spartacus', rating: 4)
V
Vijay Dev 已提交
40
    #   # returns a chainable list (which can be empty).
41 42
    #
    #   Person.find_by(name: 'Spartacus', rating: 4)
V
Vijay Dev 已提交
43
    #   # returns the first item or nil.
44 45
    #
    #   Person.where(name: 'Spartacus', rating: 4).first_or_initialize
V
Vijay Dev 已提交
46
    #   # returns the first item or returns a new instance (requires you call .save to persist against the database).
47 48
    #
    #   Person.where(name: 'Spartacus', rating: 4).first_or_create
V
Vijay Dev 已提交
49
    #   # returns the first item or creates it and returns it, available since Rails 3.2.1.
50 51 52 53
    #
    # ==== Alternatives for +find+
    #
    #   Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
V
Vijay Dev 已提交
54
    #   # returns a boolean indicating if any record with the given conditions exist.
55
    #
56
    #   Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
V
Vijay Dev 已提交
57
    #   # returns a chainable list of instances with only the mentioned fields.
58 59
    #
    #   Person.where(name: 'Spartacus', rating: 4).ids
V
Vijay Dev 已提交
60
    #   # returns an Array of ids, available since Rails 3.2.1.
61 62
    #
    #   Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
V
Vijay Dev 已提交
63
    #   # returns an Array of the required fields, available since Rails 3.1.
64
    def find(*args)
65 66
      if block_given?
        to_a.find { |*block_args| yield(*block_args) }
67
      else
68
        find_with_ids(*args)
69 70 71
      end
    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 80
    # 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)
81
      where(*args).take
82 83 84 85 86
    end

    # Like <tt>find_by</tt>, except that if no record is found, raises
    # an <tt>ActiveRecord::RecordNotFound</tt> error.
    def find_by!(*args)
87
      where(*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 98 99 100 101 102 103 104 105 106
    #   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!
      take or raise RecordNotFound
    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 111
    #   Person.first # returns the first object fetched by SELECT * FROM people
    #   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 LIMIT 3
115 116 117
    #
    # ==== Rails 3
    #
118
    #   Person.first # SELECT "people".* FROM "people" LIMIT 1
119
    #
V
Vijay Dev 已提交
120 121 122
    # 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.
123 124 125
    #
    # ==== Rails 4
    #
126
    #   Person.first # SELECT "people".* FROM "people" ORDER BY "people"."id" ASC LIMIT 1
127
    #
128
    def first(limit = nil)
129
      if limit
130
        find_nth_with_limit(offset_value, limit)
131
      else
132
        find_nth(:first, offset_value)
133
      end
134 135
    end

136 137
    # 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 已提交
138
    def first!
139
      first or raise RecordNotFound
140 141
    end

142 143 144
    # Find the last record (or last N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
145 146 147
    #   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
148
    #   Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
149
    #
150
    # Take note that in that last case, the results are sorted in ascending order:
151
    #
152
    #   [#<Person id:2>, #<Person id:3>, #<Person id:4>]
153
    #
154
    # and not:
155
    #
156
    #   [#<Person id:4>, #<Person id:3>, #<Person id:2>]
157 158
    def last(limit = nil)
      if limit
159
        if order_values.empty? && primary_key
160
          order(arel_table[primary_key].desc).limit(limit).reverse
161
        else
162
          to_a.last(limit)
163 164 165 166
        end
      else
        find_last
      end
167 168
    end

169 170
    # 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 已提交
171
    def last!
172
      last or raise RecordNotFound
173 174
    end

175 176 177 178 179 180 181
    # 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
182
      find_nth(:second, offset_value ? offset_value + 1 : 1)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    end

    # Same as +second+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def second!
      second or raise RecordNotFound
    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
198
      find_nth(:third, offset_value ? offset_value + 2 : 2)
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    end

    # Same as +third+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def third!
      third or raise RecordNotFound
    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
214
      find_nth(:fourth, offset_value ? offset_value + 3 : 3)
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    end

    # Same as +fourth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def fourth!
      fourth or raise RecordNotFound
    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
230
      find_nth(:fifth, offset_value ? offset_value + 4 : 4)
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    end

    # Same as +fifth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def fifth!
      fifth or raise RecordNotFound
    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
    #   Person.offset(3).forty_two # returns the fifth object from OFFSET 3 (which is OFFSET 44)
    #   Person.where(["user_name = :u", { u: user_name }]).forty_two
    def forty_two
246
      find_nth(:forty_two, offset_value ? offset_value + 41 : 41)
247 248 249 250 251 252 253 254
    end

    # Same as +forty_two+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
    # is found.
    def forty_two!
      forty_two or raise RecordNotFound
    end

255 256
    # 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 已提交
257 258 259 260 261
    #
    # * 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
262
    #   (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
P
Pratik Naik 已提交
263
    # * Hash - Finds the record that matches these +find+-style conditions
264
    #   (such as <tt>{name: 'David'}</tt>).
265 266
    # * +false+ - Returns always +false+.
    # * No args - Returns +false+ if the table is empty, +true+ otherwise.
P
Pratik Naik 已提交
267
    #
268 269
    # 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 已提交
270 271 272 273 274 275 276 277
    #
    # 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}%"])
278
    #   Person.exists?(id: [1, 4, 8])
279 280
    #   Person.exists?(name: 'David')
    #   Person.exists?(false)
P
Pratik Naik 已提交
281
    #   Person.exists?
E
Egor Lynko 已提交
282
    def exists?(conditions = :none)
J
Jon Leighton 已提交
283
      conditions = conditions.id if Base === conditions
E
Egor Lynko 已提交
284
      return false if !conditions
285

286
      relation = apply_join_dependency(self, construct_join_dependency)
287 288
      return false if ActiveRecord::NullRelation === relation

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

E
Egor Lynko 已提交
291
      case conditions
P
Pratik Naik 已提交
292
      when Array, Hash
E
Egor Lynko 已提交
293
        relation = relation.where(conditions)
P
Pratik Naik 已提交
294
      else
E
Egor Lynko 已提交
295
        relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
P
Pratik Naik 已提交
296
      end
297

298
      connection.select_value(relation, "#{name} Exists", relation.bind_values) ? true : false
299 300
    end

301 302 303 304 305 306 307 308 309 310 311 312 313
    # 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:
      conditions = arel.where_sql
      conditions = " [#{conditions}]" if conditions

      if Array(ids).size == 1
314
        error = "Couldn't find #{@klass.name} with '#{primary_key}'=#{ids}#{conditions}"
315
      else
316
        error = "Couldn't find all #{@klass.name.pluralize} with '#{primary_key}': "
317 318 319 320 321 322
        error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
      end

      raise RecordNotFound, error
    end

323
    private
324

325
    def find_with_associations
326
      join_dependency = construct_join_dependency
327 328

      aliases  = join_dependency.aliases
329
      relation = select aliases.columns
A
Aaron Patterson 已提交
330 331
      relation = apply_join_dependency(relation, join_dependency)

332 333
      if block_given?
        yield relation
334
      else
335 336 337 338
        if ActiveRecord::NullRelation === relation
          []
        else
          rows = connection.select_all(relation.arel, 'SQL', relation.bind_values.dup)
A
Aaron Patterson 已提交
339
          join_dependency.instantiate(rows, aliases)
340
        end
341
      end
342 343
    end

344
    def construct_join_dependency(joins = [])
345
      including = eager_load_values + includes_values
346
      ActiveRecord::Associations::JoinDependency.new(@klass, including, joins)
347 348
    end

349
    def construct_relation_for_association_calculations
350
      apply_join_dependency(self, construct_join_dependency(arel.froms.first))
351 352
    end

P
Pratik Naik 已提交
353
    def apply_join_dependency(relation, join_dependency)
354
      relation = relation.except(:includes, :eager_load, :preload)
355
      relation = relation.joins join_dependency
356

357 358 359
      if using_limitable_reflections?(join_dependency.reflections)
        relation
      else
360 361 362 363
        if relation.limit_value
          limited_ids = limited_ids_for(relation)
          limited_ids.empty? ? relation.none! : relation.where!(table[primary_key].in(limited_ids))
        end
364
        relation.except(:limit, :offset)
365 366 367
      end
    end

368
    def limited_ids_for(relation)
369 370
      values = @klass.connection.columns_for_distinct(
        "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
371

372
      relation = relation.except(:select).select(values).distinct!
373 374

      id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
375
      id_rows.map {|row| row[primary_key]}
376 377
    end

378 379 380 381 382 383
    def using_limitable_reflections?(reflections)
      reflections.none? { |r| r.collection? }
    end

    protected

384
    def find_with_ids(*ids)
385 386
      raise UnknownPrimaryKey.new(@klass) if primary_key.nil?

P
Pratik Naik 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
      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
    end

403
    def find_one(id)
A
Aaron Patterson 已提交
404 405
      id = id.id if ActiveRecord::Base === id

406
      column = columns_hash[primary_key]
407
      substitute = connection.substitute_at(column, bind_values.length)
408
      relation = where(table[primary_key].eq(substitute))
409
      relation.bind_values += [[column, id]]
410
      record = relation.take
411

412
      raise_record_not_found_exception!(id, 0, 1) unless record
413 414 415 416 417

      record
    end

    def find_some(ids)
J
Jon Leighton 已提交
418
      result = where(table[primary_key].in(ids)).to_a
419 420

      expected_size =
421 422
        if limit_value && ids.size > limit_value
          limit_value
423 424 425 426 427
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
428 429
      if offset_value && (ids.size - offset_value < expected_size)
        expected_size = ids.size - offset_value
430 431 432 433 434
      end

      if result.size == expected_size
        result
      else
435
        raise_record_not_found_exception!(ids, result.size, expected_size)
436 437 438
      end
    end

439 440
    def find_take
      if loaded?
441
        @records.first
442
      else
443
        @take ||= limit(1).to_a.first
444 445 446
      end
    end

447
    def find_nth(ordinal, offset)
P
Pratik Naik 已提交
448
      if loaded?
449
        @records.send(ordinal)
P
Pratik Naik 已提交
450
      else
451
        @offsets[offset] ||= find_nth_with_limit(offset, 1).first
452 453 454
      end
    end

455
    def find_nth_with_limit(offset, limit)
456
      if order_values.empty? && primary_key
457
        order(arel_table[primary_key].asc).limit(limit).offset(offset).to_a
458
      else
459
        limit(limit).offset(offset).to_a
P
Pratik Naik 已提交
460 461 462 463 464 465 466
      end
    end

    def find_last
      if loaded?
        @records.last
      else
N
Nick Howard 已提交
467
        @last ||=
L
Lauro Caetano 已提交
468
          if limit_value
N
Nick Howard 已提交
469 470
            to_a.last
          else
471
            reverse_order.limit(1).to_a.first
N
Nick Howard 已提交
472
          end
P
Pratik Naik 已提交
473 474
      end
    end
475 476
  end
end