finder_methods.rb 12.1 KB
Newer Older
1 2
module ActiveRecord
  module FinderMethods
3 4 5
    # 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 已提交
6 7
    #
    #   Person.find(1)       # returns the object for ID = 1
8
    #   Person.find("1")     # returns the object for ID = 1
P
Pratik Naik 已提交
9 10 11
    #   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 已提交
12
    #   Person.where("administrator = 1").order("created_on DESC").find(1)
P
Pratik Naik 已提交
13 14
    #
    # Note that returned records may not be in the same order as the ids you
15
    # provide since database rows are unordered. Give an explicit <tt>order</tt>
P
Pratik Naik 已提交
16 17
    # to ensure the results are sorted.
    #
18
    # ==== Find with lock
P
Pratik Naik 已提交
19 20 21
    #
    # 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
22
    # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
P
Pratik Naik 已提交
23 24 25 26
    # transaction has to wait until the first is finished; we get the
    # expected <tt>person.visits == 4</tt>.
    #
    #   Person.transaction do
E
Emilio Tagua 已提交
27
    #     person = Person.lock(true).find(1)
P
Pratik Naik 已提交
28 29 30
    #     person.visits += 1
    #     person.save!
    #   end
31
    def find(*args)
32 33
      if block_given?
        to_a.find { |*block_args| yield(*block_args) }
34
      else
35
        find_with_ids(*args)
36 37 38
      end
    end

39
    # Finds the first record matching the specified conditions. There
40
    # is no implied ordering so if order matters, you should specify it
41 42 43 44 45 46 47
    # 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)
48
      where(*args).take
49 50 51 52 53
    end

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

57 58 59 60
    # 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.
    #
61
    #   Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
62 63 64 65 66 67 68 69 70 71 72 73
    #   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

74 75 76
    # Find the first record (or first N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
77 78
    #   Person.first # returns the first object fetched by SELECT * FROM people
    #   Person.where(["user_name = ?", user_name]).first
A
AvnerCohen 已提交
79
    #   Person.where(["user_name = :u", { u: user_name }]).first
80
    #   Person.order("created_on DESC").offset(5).first
81
    #   Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
82
    def first(limit = nil)
83 84
      if limit
        if order_values.empty? && primary_key
85
          order(arel_table[primary_key].asc).limit(limit).to_a
86 87 88 89 90 91
        else
          limit(limit).to_a
        end
      else
        find_first
      end
92 93
    end

94 95
    # 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 已提交
96
    def first!
97
      first or raise RecordNotFound
98 99
    end

100 101 102
    # Find the last record (or last N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
103 104 105
    #   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
106
    #   Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
107
    #
108
    # Take note that in that last case, the results are sorted in ascending order:
109
    #
110
    #   [#<Person id:2>, #<Person id:3>, #<Person id:4>]
111
    #
112
    # and not:
113
    #
114
    #   [#<Person id:4>, #<Person id:3>, #<Person id:2>]
115 116
    def last(limit = nil)
      if limit
117
        if order_values.empty? && primary_key
118
          order(arel_table[primary_key].desc).limit(limit).reverse
119
        else
120
          to_a.last(limit)
121 122 123 124
        end
      else
        find_last
      end
125 126
    end

127 128
    # 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 已提交
129
    def last!
130
      last or raise RecordNotFound
131 132
    end

S
Steve Klabnik 已提交
133 134
    # Returns truthy if a record exists in the table that matches the +id+ or
    # conditions given, or falsy otherwise. The argument can take six forms:
P
Pratik Naik 已提交
135 136 137 138 139 140 141
    #
    # * 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
    #   (such as <tt>['color = ?', 'red']</tt>).
    # * Hash - Finds the record that matches these +find+-style conditions
142 143 144
    #   (such as <tt>{color: 'red'}</tt>).
    # * +false+ - Returns always +false+.
    # * No args - Returns +false+ if the table is empty, +true+ otherwise.
P
Pratik Naik 已提交
145 146 147 148 149 150 151 152 153 154 155
    #
    # For more information about specifying conditions as a Hash or Array,
    # see the Conditions section in the introduction to ActiveRecord::Base.
    #
    # 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}%"])
156 157
    #   Person.exists?(name: 'David')
    #   Person.exists?(false)
P
Pratik Naik 已提交
158
    #   Person.exists?
E
Egor Lynko 已提交
159
    def exists?(conditions = :none)
J
Jon Leighton 已提交
160
      conditions = conditions.id if Base === conditions
E
Egor Lynko 已提交
161
      return false if !conditions
162

163 164
      join_dependency = construct_join_dependency_for_association_find
      relation = construct_relation_for_association_find(join_dependency)
165
      relation = relation.except(:select, :order).select("1 AS one").limit(1)
A
Aaron Patterson 已提交
166

E
Egor Lynko 已提交
167
      case conditions
P
Pratik Naik 已提交
168
      when Array, Hash
E
Egor Lynko 已提交
169
        relation = relation.where(conditions)
P
Pratik Naik 已提交
170
      else
E
Egor Lynko 已提交
171
        relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
P
Pratik Naik 已提交
172
      end
173

174
      connection.select_value(relation, "#{name} Exists", relation.bind_values)
175 176
    rescue ThrowResult
      false
177 178
    end

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    # 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

201 202
    protected

203
    def find_with_associations
204
      join_dependency = construct_join_dependency_for_association_find
205
      relation = construct_relation_for_association_find(join_dependency)
206
      rows = connection.select_all(relation, 'SQL', relation.bind_values.dup)
207 208 209 210 211
      join_dependency.instantiate(rows)
    rescue ThrowResult
      []
    end

212
    def construct_join_dependency_for_association_find
213
      including = (eager_load_values + includes_values).uniq
214 215 216
      ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
    end

217
    def construct_relation_for_association_calculations
218
      including = (eager_load_values + includes_values).uniq
219
      join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
P
Pratik Naik 已提交
220 221
      relation = except(:includes, :eager_load, :preload)
      apply_join_dependency(relation, join_dependency)
222 223
    end

224
    def construct_relation_for_association_find(join_dependency)
225
      relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
P
Pratik Naik 已提交
226 227
      apply_join_dependency(relation, join_dependency)
    end
228

P
Pratik Naik 已提交
229
    def apply_join_dependency(relation, join_dependency)
230
      join_dependency.join_associations.each do |association|
231 232 233
        relation = association.join_relation(relation)
      end

234
      limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
235 236 237 238 239 240 241 242 243 244 245 246

      if !limitable_reflections && relation.limit_value
        limited_id_condition = construct_limited_ids_condition(relation.except(:select))
        relation = relation.where(limited_id_condition)
      end

      relation = relation.except(:limit, :offset) unless limitable_reflections

      relation
    end

    def construct_limited_ids_condition(relation)
247 248
      values = @klass.connection.columns_for_distinct(
        "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
249

250
      relation = relation.dup.select(values).distinct!
251 252 253

      id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
      ids_array = id_rows.map {|row| row[primary_key]}
254

255
      ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
256 257
    end

258
    def find_with_ids(*ids)
P
Pratik Naik 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
      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

275
    def find_one(id)
A
Aaron Patterson 已提交
276 277
      id = id.id if ActiveRecord::Base === id

278
      column = columns_hash[primary_key]
279
      substitute = connection.substitute_at(column, bind_values.length)
280
      relation = where(table[primary_key].eq(substitute))
281
      relation.bind_values += [[column, id]]
282
      record = relation.take
283

284
      raise_record_not_found_exception!(id, 0, 1) unless record
285 286 287 288 289

      record
    end

    def find_some(ids)
J
Jon Leighton 已提交
290
      result = where(table[primary_key].in(ids)).to_a
291 292

      expected_size =
293 294
        if limit_value && ids.size > limit_value
          limit_value
295 296 297 298 299
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
300 301
      if offset_value && (ids.size - offset_value < expected_size)
        expected_size = ids.size - offset_value
302 303 304 305 306
      end

      if result.size == expected_size
        result
      else
307
        raise_record_not_found_exception!(ids, result.size, expected_size)
308 309 310
      end
    end

311 312
    def find_take
      if loaded?
313
        @records.first
314
      else
315
        @take ||= limit(1).to_a.first
316 317 318
      end
    end

P
Pratik Naik 已提交
319 320 321 322
    def find_first
      if loaded?
        @records.first
      else
323
        @first ||=
324
          if with_default_scope.order_values.empty? && primary_key
325
            order(arel_table[primary_key].asc).limit(1).to_a.first
326
          else
327
            limit(1).to_a.first
328
          end
P
Pratik Naik 已提交
329 330 331 332 333 334 335
      end
    end

    def find_last
      if loaded?
        @records.last
      else
N
Nick Howard 已提交
336 337 338 339
        @last ||=
          if offset_value || limit_value
            to_a.last
          else
340
            reverse_order.limit(1).to_a.first
N
Nick Howard 已提交
341
          end
P
Pratik Naik 已提交
342 343 344
      end
    end

345
    def using_limitable_reflections?(reflections)
346
      reflections.none? { |r| r.collection? }
347
    end
348 349
  end
end