finder_methods.rb 13.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 54 55 56 57 58 59 60 61 62
    # 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)
      where(*args).first
    end

    # Like <tt>find_by</tt>, except that if no record is found, raises
    # an <tt>ActiveRecord::RecordNotFound</tt> error.
    def find_by!(*args)
      where(*args).first!
    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 91
    # 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
    def first(limit = nil)
92 93 94 95 96 97 98 99 100
      if limit
        if order_values.empty? && primary_key
          order("#{quoted_table_name}.#{quoted_primary_key} ASC").limit(limit).to_a
        else
          limit(limit).to_a
        end
      else
        find_first
      end
101 102
    end

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

109 110 111
    # Find the last record (or last N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
112 113 114 115 116 117 118
    # 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
    def last(limit = nil)
      if limit
119 120
        if order_values.empty? && primary_key
          order("#{quoted_table_name}.#{quoted_primary_key} DESC").limit(limit).reverse
121
        else
122
          to_a.last(limit)
123 124 125 126
        end
      else
        find_last
      end
127 128
    end

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

135 136 137 138 139 140 141 142 143 144
    # 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 已提交
145 146
    end

P
Pratik Naik 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    # 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 => "David")
    #   Person.exists?(['name LIKE ?', "%#{query}%"])
    #   Person.exists?
172 173 174
    def exists?(id = false)
      return false if id.nil?

J
Jon Leighton 已提交
175
      id = id.id if ActiveRecord::Model === id
176

177 178
      join_dependency = construct_join_dependency_for_association_find
      relation = construct_relation_for_association_find(join_dependency)
179
      relation = relation.except(:select, :order).select("1").limit(1)
A
Aaron Patterson 已提交
180

P
Pratik Naik 已提交
181 182
      case id
      when Array, Hash
A
Aaron Patterson 已提交
183
        relation = relation.where(id)
P
Pratik Naik 已提交
184
      else
185
        relation = relation.where(table[primary_key].eq(id)) if id
P
Pratik Naik 已提交
186
      end
187

188
      connection.select_value(relation, "#{name} Exists", relation.bind_values)
189 190 191 192
    end

    protected

193
    def find_with_associations
194
      join_dependency = construct_join_dependency_for_association_find
195
      relation = construct_relation_for_association_find(join_dependency)
196
      rows = connection.select_all(relation, 'SQL', relation.bind_values.dup)
197 198 199 200 201
      join_dependency.instantiate(rows)
    rescue ThrowResult
      []
    end

202
    def construct_join_dependency_for_association_find
203
      including = (eager_load_values + includes_values).uniq
204 205 206
      ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
    end

207
    def construct_relation_for_association_calculations
208
      including = (eager_load_values + includes_values).uniq
209
      join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
P
Pratik Naik 已提交
210 211
      relation = except(:includes, :eager_load, :preload)
      apply_join_dependency(relation, join_dependency)
212 213
    end

214
    def construct_relation_for_association_find(join_dependency)
215
      relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
P
Pratik Naik 已提交
216 217
      apply_join_dependency(relation, join_dependency)
    end
218

P
Pratik Naik 已提交
219
    def apply_join_dependency(relation, join_dependency)
220
      join_dependency.join_associations.each do |association|
221 222 223
        relation = association.join_relation(relation)
      end

224
      limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
225 226 227 228 229 230 231 232 233 234 235 236

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

240 241
      relation = relation.dup

242 243
      ids_array = relation.select(values).collect {|row| row[primary_key]}
      ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
244 245
    end

246
    def find_by_attributes(match, attributes, *args)
247
      conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]
248 249 250 251 252
      result = where(conditions).send(match.finder)

      if match.bang? && result.blank?
        raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"
      else
253 254 255 256 257
        if block_given? && result
          yield(result)
        else
          result
        end
258 259 260 261
      end
    end

    def find_or_instantiator_by_attributes(match, attributes, *args)
262
      options = args.size > 1 && args.last(2).all?{ |a| a.is_a?(Hash) } ? args.extract_options! : {}
263
      protected_attributes_for_create, unprotected_attributes_for_create = {}, {}
264 265 266 267 268 269
      args.each_with_index do |arg, i|
        if arg.is_a?(Hash)
          protected_attributes_for_create = args[i].with_indifferent_access
        else
          unprotected_attributes_for_create[attributes[i]] = args[i]
        end
270 271
      end

272 273
      conditions = (protected_attributes_for_create.merge(unprotected_attributes_for_create)).slice(*attributes).symbolize_keys

274 275 276
      record = where(conditions).first

      unless record
277
        record = @klass.new(protected_attributes_for_create, options) do |r|
278
          r.assign_attributes(unprotected_attributes_for_create, :without_protection => true)
279
        end
280
        yield(record) if block_given?
281
        record.send(match.save_method) if match.save_record?
282 283 284 285 286
      end

      record
    end

287 288
    def find_with_ids(*ids)
      return to_a.find { |*block_args| yield(*block_args) } if block_given?
P
Pratik Naik 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

      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

306
    def find_one(id)
A
Aaron Patterson 已提交
307 308
      id = id.id if ActiveRecord::Base === id

309
      column = columns_hash[primary_key]
310
      substitute = connection.substitute_at(column, bind_values.length)
311
      relation = where(table[primary_key].eq(substitute))
312
      relation.bind_values += [[column, id]]
313
      record = relation.first
314 315

      unless record
A
Aaron Patterson 已提交
316 317
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
318
        raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
319 320 321 322 323 324
      end

      record
    end

    def find_some(ids)
325
      result = where(table[primary_key].in(ids)).all
326 327

      expected_size =
328 329
        if limit_value && ids.size > limit_value
          limit_value
330 331 332 333 334
        else
          ids.size
        end

      # 11 ids with limit 3, offset 9 should give 2 results.
335 336
      if offset_value && (ids.size - offset_value < expected_size)
        expected_size = ids.size - offset_value
337 338 339 340 341
      end

      if result.size == expected_size
        result
      else
342 343
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
344 345 346 347 348 349 350

        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

351 352
    def find_take
      if loaded?
353
        @records.take(1).first
354
      else
355
        @take ||= limit(1).to_a.first
356 357 358
      end
    end

P
Pratik Naik 已提交
359 360 361 362
    def find_first
      if loaded?
        @records.first
      else
363 364
        @first ||=
          if order_values.empty? && primary_key
365
            order("#{quoted_table_name}.#{quoted_primary_key} ASC").limit(1).to_a.first
366
          else
367
            limit(1).to_a.first
368
          end
P
Pratik Naik 已提交
369 370 371 372 373 374 375
      end
    end

    def find_last
      if loaded?
        @records.last
      else
N
Nick Howard 已提交
376 377 378 379
        @last ||=
          if offset_value || limit_value
            to_a.last
          else
380
            reverse_order.limit(1).to_a.first
N
Nick Howard 已提交
381
          end
P
Pratik Naik 已提交
382 383 384
      end
    end

385
    def using_limitable_reflections?(reflections)
386
      reflections.none? { |r| r.collection? }
387
    end
388 389
  end
end