finder_methods.rb 12.0 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 11 12
    #
    # ==== Examples
    #
    #   Person.find(1)       # returns the object for ID = 1
13
    #   Person.find("1")     # returns the object for ID = 1
P
Pratik Naik 已提交
14 15 16
    #   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 已提交
17
    #   Person.where("administrator = 1").order("created_on DESC").find(1)
P
Pratik Naik 已提交
18 19
    #
    # Note that returned records may not be in the same order as the ids you
20
    # provide since database rows are unordered. Give an explicit <tt>order</tt>
P
Pratik Naik 已提交
21 22
    # to ensure the results are sorted.
    #
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
    def find(*args)
37 38
      if block_given?
        to_a.find { |*block_args| yield(*block_args) }
39
      else
40
        find_with_ids(*args)
41 42 43
      end
    end

44 45 46 47 48 49 50 51 52 53
    # 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)
54
      where(*args).take
55 56 57 58 59
    end

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

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    # 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.
    #
    # Examples:
    #
    #   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

82 83 84
    # Find the first record (or first N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
85 86 87 88 89 90
    # Examples:
    #
    #   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
91
    #   Person.first(3) # returns the first 3 objects fetched by SELECT * FROM people LIMIT 3
92
    def first(limit = nil)
93 94
      if limit
        if order_values.empty? && primary_key
95
          order(arel_table[primary_key].asc).limit(limit).to_a
96 97 98 99 100 101
        else
          limit(limit).to_a
        end
      else
        find_first
      end
102 103
    end

104 105
    # 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 已提交
106
    def first!
107
      first or raise RecordNotFound
108 109
    end

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

139 140
    # 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 已提交
141
    def last!
142
      last or raise RecordNotFound
143 144
    end

145 146 147
    # Runs the query on the database and returns records with the used query
    # methods.
    #
148 149 150 151 152 153 154 155 156 157
    # Examples:
    #
    #   Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
    #   Person.where(["category IN (?)", categories]).limit(50).all
    #   Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
    #   Person.offset(10).limit(10).all
    #   Person.includes([:account, :friends]).all
    #   Person.group("category").all
    def all
      to_a
P
Pratik Naik 已提交
158 159
    end

P
Pratik Naik 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    # Returns true if a record exists in the table that matches the +id+ or
    # conditions given, or false otherwise. The argument can take five forms:
    #
    # * 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
    #   (such as <tt>{:color => 'red'}</tt>).
    # * No args - Returns false if the table is empty, true otherwise.
    #
    # 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>.
    #
    # ==== Examples
    #   Person.exists?(5)
    #   Person.exists?('5')
    #   Person.exists?(['name LIKE ?', "%#{query}%"])
183
    #   Person.exists?(:name => "David")
P
Pratik Naik 已提交
184
    #   Person.exists?
185
    def exists?(id = false)
J
Jon Leighton 已提交
186
      id = id.id if ActiveRecord::Model === id
187
      return false if id.nil?
188

189 190
      join_dependency = construct_join_dependency_for_association_find
      relation = construct_relation_for_association_find(join_dependency)
191
      relation = relation.except(:select, :order).select("1").limit(1)
A
Aaron Patterson 已提交
192

P
Pratik Naik 已提交
193 194
      case id
      when Array, Hash
A
Aaron Patterson 已提交
195
        relation = relation.where(id)
P
Pratik Naik 已提交
196
      else
197
        relation = relation.where(table[primary_key].eq(id)) if id
P
Pratik Naik 已提交
198
      end
199

200
      connection.select_value(relation, "#{name} Exists", relation.bind_values)
201 202 203 204
    end

    protected

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

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

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

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

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

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

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

252 253
      relation = relation.dup

254 255
      ids_array = relation.select(values).collect {|row| row[primary_key]}
      ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
256 257
    end

258 259
    def find_with_ids(*ids)
      return to_a.find { |*block_args| yield(*block_args) } if block_given?
P
Pratik Naik 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

      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

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

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

      unless record
A
Aaron Patterson 已提交
287 288
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
289
        raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
290 291 292 293 294 295
      end

      record
    end

    def find_some(ids)
296
      result = where(table[primary_key].in(ids)).all
297 298

      expected_size =
299 300
        if limit_value && ids.size > limit_value
          limit_value
301 302 303 304 305
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
306 307
      if offset_value && (ids.size - offset_value < expected_size)
        expected_size = ids.size - offset_value
308 309 310 311 312
      end

      if result.size == expected_size
        result
      else
313 314
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
315 316 317 318 319 320 321

        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

322 323
    def find_take
      if loaded?
324
        @records.first
325
      else
326
        @take ||= limit(1).to_a.first
327 328 329
      end
    end

P
Pratik Naik 已提交
330 331 332 333
    def find_first
      if loaded?
        @records.first
      else
334 335
        @first ||=
          if order_values.empty? && primary_key
336
            order(arel_table[primary_key].asc).limit(1).to_a.first
337
          else
338
            limit(1).to_a.first
339
          end
P
Pratik Naik 已提交
340 341 342 343 344 345 346
      end
    end

    def find_last
      if loaded?
        @records.last
      else
N
Nick Howard 已提交
347 348 349 350
        @last ||=
          if offset_value || limit_value
            to_a.last
          else
351
            reverse_order.limit(1).to_a.first
N
Nick Howard 已提交
352
          end
P
Pratik Naik 已提交
353 354 355
      end
    end

356
    def using_limitable_reflections?(reflections)
357
      reflections.none? { |r| r.collection? }
358
    end
359 360
  end
end