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

    # Like <tt>find_by</tt>, except that if no record is found, raises
    # an <tt>ActiveRecord::RecordNotFound</tt> error.
    def find_by!(*args)
86
      where(*args).take!
87 88
    end

89 90 91 92
    # 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.
    #
93
    #   Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
94 95 96 97 98 99 100 101 102 103 104 105
    #   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

106 107 108
    # Find the first record (or first N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
109 110
    #   Person.first # returns the first object fetched by SELECT * FROM people
    #   Person.where(["user_name = ?", user_name]).first
A
AvnerCohen 已提交
111
    #   Person.where(["user_name = :u", { u: user_name }]).first
112
    #   Person.order("created_on DESC").offset(5).first
113
    #   Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
114 115 116
    #
    # ==== Rails 3
    #
117
    #   Person.first # SELECT "people".* FROM "people" LIMIT 1
118
    #
V
Vijay Dev 已提交
119 120 121
    # 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.
122 123 124
    #
    # ==== Rails 4
    #
125
    #   Person.first # SELECT "people".* FROM "people" ORDER BY "people"."id" ASC LIMIT 1
126
    #
127
    def first(limit = nil)
128
      if limit
129
        find_first_with_limit(limit)
130 131 132
      else
        find_first
      end
133 134
    end

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

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

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

174 175
    # 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 已提交
176 177 178 179 180
    #
    # * 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
181
    #   (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
P
Pratik Naik 已提交
182
    # * Hash - Finds the record that matches these +find+-style conditions
183
    #   (such as <tt>{name: 'David'}</tt>).
184 185
    # * +false+ - Returns always +false+.
    # * No args - Returns +false+ if the table is empty, +true+ otherwise.
P
Pratik Naik 已提交
186
    #
187 188
    # 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 已提交
189 190 191 192 193 194 195 196
    #
    # 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}%"])
197 198
    #   Person.exists?(name: 'David')
    #   Person.exists?(false)
P
Pratik Naik 已提交
199
    #   Person.exists?
E
Egor Lynko 已提交
200
    def exists?(conditions = :none)
J
Jon Leighton 已提交
201
      conditions = conditions.id if Base === conditions
E
Egor Lynko 已提交
202
      return false if !conditions
203

204
      relation = apply_join_dependency(self, construct_join_dependency)
205 206
      return false if ActiveRecord::NullRelation === relation

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

E
Egor Lynko 已提交
209
      case conditions
P
Pratik Naik 已提交
210
      when Array, Hash
E
Egor Lynko 已提交
211
        relation = relation.where(conditions)
P
Pratik Naik 已提交
212
      else
E
Egor Lynko 已提交
213
        relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
P
Pratik Naik 已提交
214
      end
215

216
      connection.select_value(relation, "#{name} Exists", relation.bind_values) ? true : false
217 218
    end

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    # 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
        error = "Couldn't find #{@klass.name} with #{primary_key}=#{ids}#{conditions}"
      else
        error = "Couldn't find all #{@klass.name.pluralize} with IDs "
        error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
      end

      raise RecordNotFound, error
    end

241
    private
242

243
    def find_with_associations
244
      join_dependency = construct_join_dependency
A
Aaron Patterson 已提交
245 246
      relation = except :select
      relation = construct_relation_for_association_find(join_dependency, relation)
247 248
      if block_given?
        yield relation
249
      else
250 251 252 253 254 255
        if ActiveRecord::NullRelation === relation
          []
        else
          rows = connection.select_all(relation.arel, 'SQL', relation.bind_values.dup)
          join_dependency.instantiate(rows)
        end
256
      end
257 258
    end

259
    def construct_join_dependency(joins = [])
260
      including = eager_load_values + includes_values
261
      ActiveRecord::Associations::JoinDependency.new(@klass, including, joins)
262 263
    end

264
    def construct_relation_for_association_calculations
265
      apply_join_dependency(self, construct_join_dependency(arel.froms.first))
266 267
    end

A
Aaron Patterson 已提交
268 269
    def construct_relation_for_association_find(join_dependency, relation = self)
      relation = relation.select(join_dependency.columns)
P
Pratik Naik 已提交
270 271
      apply_join_dependency(relation, join_dependency)
    end
272

P
Pratik Naik 已提交
273
    def apply_join_dependency(relation, join_dependency)
274
      relation = relation.except(:includes, :eager_load, :preload)
275
      relation = relation.joins join_dependency
276

277 278 279
      if using_limitable_reflections?(join_dependency.reflections)
        relation
      else
280 281 282 283
        if relation.limit_value
          limited_ids = limited_ids_for(relation)
          limited_ids.empty? ? relation.none! : relation.where!(table[primary_key].in(limited_ids))
        end
284
        relation.except(:limit, :offset)
285 286 287
      end
    end

288
    def limited_ids_for(relation)
289 290
      values = @klass.connection.columns_for_distinct(
        "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
291

292
      relation = relation.except(:select).select(values).distinct!
293 294

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

298 299 300 301 302 303
    def using_limitable_reflections?(reflections)
      reflections.none? { |r| r.collection? }
    end

    protected

304
    def find_with_ids(*ids)
P
Pratik Naik 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
      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

321
    def find_one(id)
A
Aaron Patterson 已提交
322 323
      id = id.id if ActiveRecord::Base === id

324
      column = columns_hash[primary_key]
325
      substitute = connection.substitute_at(column, bind_values.length)
326
      relation = where(table[primary_key].eq(substitute))
327
      relation.bind_values += [[column, id]]
328
      record = relation.take
329

330
      raise_record_not_found_exception!(id, 0, 1) unless record
331 332 333 334 335

      record
    end

    def find_some(ids)
J
Jon Leighton 已提交
336
      result = where(table[primary_key].in(ids)).to_a
337 338

      expected_size =
339 340
        if limit_value && ids.size > limit_value
          limit_value
341 342 343 344 345
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
346 347
      if offset_value && (ids.size - offset_value < expected_size)
        expected_size = ids.size - offset_value
348 349 350 351 352
      end

      if result.size == expected_size
        result
      else
353
        raise_record_not_found_exception!(ids, result.size, expected_size)
354 355 356
      end
    end

357 358
    def find_take
      if loaded?
359
        @records.first
360
      else
361
        @take ||= limit(1).to_a.first
362 363 364
      end
    end

P
Pratik Naik 已提交
365 366 367 368
    def find_first
      if loaded?
        @records.first
      else
369
        @first ||= find_first_with_limit(1).first
370 371 372
      end
    end

373
    def find_first_with_limit(limit)
374 375 376 377
      if order_values.empty? && primary_key
        order(arel_table[primary_key].asc).limit(limit).to_a
      else
        limit(limit).to_a
P
Pratik Naik 已提交
378 379 380 381 382 383 384
      end
    end

    def find_last
      if loaded?
        @records.last
      else
N
Nick Howard 已提交
385 386 387 388
        @last ||=
          if offset_value || limit_value
            to_a.last
          else
389
            reverse_order.limit(1).to_a.first
N
Nick Howard 已提交
390
          end
P
Pratik Naik 已提交
391 392
      end
    end
393 394
  end
end