finder_methods.rb 11.5 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 40 41 42 43 44 45 46 47
    # 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)
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 61 62 63 64 65 66 67 68 69 70 71 72 73
    # 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

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

133 134
    # 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 已提交
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 179 180
    end

    protected

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

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

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

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

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

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

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

228 229 230 231
      relation = relation.dup.select(values)

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

233
      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