finder_methods.rb 11.6 KB
Newer Older
1
require 'active_support/core_ext/object/blank'
2
require 'active_support/core_ext/hash/indifferent_access'
3

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

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

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

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

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

97 98
    # 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 已提交
99
    def first!
100
      first or raise RecordNotFound
101 102
    end

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

130 131
    # 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 已提交
132
    def last!
133
      last or raise RecordNotFound
134 135
    end

136 137
    # 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 已提交
138 139 140 141 142 143 144
    #
    # * 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
145 146 147
    #   (such as <tt>{color: 'red'}</tt>).
    # * +false+ - Returns always +false+.
    # * No args - Returns +false+ if the table is empty, +true+ otherwise.
P
Pratik Naik 已提交
148 149 150 151 152 153 154 155 156 157 158
    #
    # 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}%"])
159 160
    #   Person.exists?(name: 'David')
    #   Person.exists?(false)
P
Pratik Naik 已提交
161
    #   Person.exists?
E
Egor Lynko 已提交
162 163 164
    def exists?(conditions = :none)
      conditions = conditions.id if ActiveRecord::Model === conditions
      return false if !conditions
165

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

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

177
      connection.select_value(relation, "#{name} Exists", relation.bind_values)
178 179
    rescue ThrowResult
      false
180 181 182 183
    end

    protected

184
    def find_with_associations
185
      join_dependency = construct_join_dependency_for_association_find
186
      relation = construct_relation_for_association_find(join_dependency)
187
      rows = connection.select_all(relation, 'SQL', relation.bind_values.dup)
188 189 190 191 192
      join_dependency.instantiate(rows)
    rescue ThrowResult
      []
    end

193
    def construct_join_dependency_for_association_find
194
      including = (eager_load_values + includes_values).uniq
195 196 197
      ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
    end

198
    def construct_relation_for_association_calculations
199
      including = (eager_load_values + includes_values).uniq
200
      join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
P
Pratik Naik 已提交
201 202
      relation = except(:includes, :eager_load, :preload)
      apply_join_dependency(relation, join_dependency)
203 204
    end

205
    def construct_relation_for_association_find(join_dependency)
206
      relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
P
Pratik Naik 已提交
207 208
      apply_join_dependency(relation, join_dependency)
    end
209

P
Pratik Naik 已提交
210
    def apply_join_dependency(relation, join_dependency)
211
      join_dependency.join_associations.each do |association|
212 213 214
        relation = association.join_relation(relation)
      end

215
      limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
216 217 218 219 220 221 222 223 224 225 226 227

      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)
228
      orders = relation.order_values.map { |val| val.presence }.compact
229
      values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
230

231 232
      relation = relation.dup

233 234
      ids_array = relation.select(values).collect {|row| row[primary_key]}
      ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
235 236
    end

237 238
    def find_with_ids(*ids)
      return to_a.find { |*block_args| yield(*block_args) } if block_given?
P
Pratik Naik 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

      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

256
    def find_one(id)
A
Aaron Patterson 已提交
257 258
      id = id.id if ActiveRecord::Base === id

259
      column = columns_hash[primary_key]
260
      substitute = connection.substitute_at(column, bind_values.length)
261
      relation = where(table[primary_key].eq(substitute))
262
      relation.bind_values += [[column, id]]
263
      record = relation.take
264 265

      unless record
A
Aaron Patterson 已提交
266 267
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
268
        raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
269 270 271 272 273 274
      end

      record
    end

    def find_some(ids)
J
Jon Leighton 已提交
275
      result = where(table[primary_key].in(ids)).to_a
276 277

      expected_size =
278 279
        if limit_value && ids.size > limit_value
          limit_value
280 281 282 283 284
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
285 286
      if offset_value && (ids.size - offset_value < expected_size)
        expected_size = ids.size - offset_value
287 288 289 290 291
      end

      if result.size == expected_size
        result
      else
292 293
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
294 295 296 297 298 299 300

        error = "Couldn't find all #{@klass.name.pluralize} with IDs "
        error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
        raise RecordNotFound, error
      end
    end

301 302
    def find_take
      if loaded?
303
        @records.first
304
      else
305
        @take ||= limit(1).to_a.first
306 307 308
      end
    end

P
Pratik Naik 已提交
309 310 311 312
    def find_first
      if loaded?
        @records.first
      else
313 314
        @first ||=
          if order_values.empty? && primary_key
315
            order(arel_table[primary_key].asc).limit(1).to_a.first
316
          else
317
            limit(1).to_a.first
318
          end
P
Pratik Naik 已提交
319 320 321 322 323 324 325
      end
    end

    def find_last
      if loaded?
        @records.last
      else
N
Nick Howard 已提交
326 327 328 329
        @last ||=
          if offset_value || limit_value
            to_a.last
          else
330
            reverse_order.limit(1).to_a.first
N
Nick Howard 已提交
331
          end
P
Pratik Naik 已提交
332 333 334
      end
    end

335
    def using_limitable_reflections?(reflections)
336
      reflections.none? { |r| r.collection? }
337
    end
338 339
  end
end