finder_methods.rb 11.5 KB
Newer Older
1
require 'active_support/core_ext/hash/indifferent_access'
2

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

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

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

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    # 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

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

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

102 103 104
    # Find the last record (or last N records if a parameter is supplied).
    # If no order is defined it will order by primary key.
    #
105 106 107
    #   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
108
    #   Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
109
    #
110
    # Take note that in that last case, the results are sorted in ascending order:
111
    #
112
    #   [#<Person id:2>, #<Person id:3>, #<Person id:4>]
113
    #
114
    # and not:
115
    #
116
    #   [#<Person id:4>, #<Person id:3>, #<Person id:2>]
117 118
    def last(limit = nil)
      if limit
119
        if order_values.empty? && primary_key
120
          order(arel_table[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
    # 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 已提交
137 138 139 140 141 142 143
    #
    # * 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
144 145 146
    #   (such as <tt>{color: 'red'}</tt>).
    # * +false+ - Returns always +false+.
    # * No args - Returns +false+ if the table is empty, +true+ otherwise.
P
Pratik Naik 已提交
147 148 149 150 151 152 153 154 155 156 157
    #
    # 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}%"])
158 159
    #   Person.exists?(name: 'David')
    #   Person.exists?(false)
P
Pratik Naik 已提交
160
    #   Person.exists?
E
Egor Lynko 已提交
161
    def exists?(conditions = :none)
J
Jon Leighton 已提交
162
      conditions = conditions.id if Base === conditions
E
Egor Lynko 已提交
163
      return false if !conditions
164

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

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

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

    protected

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

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

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

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

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

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

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

230 231
      relation = relation.dup

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

236
    def find_with_ids(*ids)
P
Pratik Naik 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
      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

253
    def find_one(id)
A
Aaron Patterson 已提交
254 255
      id = id.id if ActiveRecord::Base === id

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

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

      record
    end

    def find_some(ids)
J
Jon Leighton 已提交
272
      result = where(table[primary_key].in(ids)).to_a
273 274

      expected_size =
275 276
        if limit_value && ids.size > limit_value
          limit_value
277 278 279 280 281
        else
          ids.size
        end

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

      if result.size == expected_size
        result
      else
289 290
        conditions = arel.where_sql
        conditions = " [#{conditions}]" if conditions
291 292 293 294 295 296 297

        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

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

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

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

332
    def using_limitable_reflections?(reflections)
333
      reflections.none? { |r| r.collection? }
334
    end
335 336
  end
end