relation.rb 16.1 KB
Newer Older
1
require 'active_support/core_ext/object/blank'
2
require 'active_support/core_ext/module/delegation'
3

4
module ActiveRecord
R
Rizwan Reza 已提交
5
  # = Active Record Relation
6
  class Relation
7 8
    JoinOperation = Struct.new(:relation, :join_class, :on)
    ASSOCIATION_METHODS = [:includes, :eager_load, :preload]
A
Aaron Patterson 已提交
9
    MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind]
10
    SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order]
11

P
Pratik Naik 已提交
12
    include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches
13

14
    # These are explicitly delegated to improve performance (avoids method_missing)
15
    delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a
16
    delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, :connection, :column_hash,:to => :klass
17

18
    attr_reader :table, :klass, :loaded
19
    attr_accessor :extensions, :default_scoped
20
    alias :loaded? :loaded
21
    alias :default_scoped? :default_scoped
22

23
    def initialize(klass, table)
24
      @klass, @table = klass, table
A
Aaron Patterson 已提交
25 26

      @implicit_readonly = nil
27
      @loaded            = false
28
      @default_scoped    = false
A
Aaron Patterson 已提交
29

30
      SINGLE_VALUE_METHODS.each {|v| instance_variable_set(:"@#{v}_value", nil)}
31
      (ASSOCIATION_METHODS + MULTI_VALUE_METHODS).each {|v| instance_variable_set(:"@#{v}_values", [])}
P
Pratik Naik 已提交
32
      @extensions = []
33
      @create_with_value = {}
34 35
    end

36
    def insert(values)
37 38 39 40 41 42
      primary_key_value = nil

      if primary_key && Hash === values
        primary_key_value = values[values.keys.find { |k|
          k.name == primary_key
        }]
43 44 45 46 47 48 49 50 51 52

        if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
          primary_key_value = connection.next_sequence_value(klass.sequence_name)
          values[klass.arel_table[klass.primary_key]] = primary_key_value
        end
      end

      im = arel.create_insert
      im.into @table

53 54
      conn = @klass.connection

55
      substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
56 57 58 59 60
      binds       = substitutes.map do |arel_attr, value|
        [@klass.columns_hash[arel_attr.name], value]
      end

      substitutes.each_with_index do |tuple, i|
61
        tuple[1] = conn.substitute_at(binds[i][0], i)
62 63
      end

64
      if values.empty? # empty insert
65
        im.values = Arel.sql(connection.empty_insert_statement_value)
66
      else
67
        im.insert substitutes
68
      end
69

70 71 72 73 74 75 76
      conn.insert(
        im.to_sql,
        'SQL',
        primary_key,
        primary_key_value,
        nil,
        binds)
77
    end
78

P
Pratik Naik 已提交
79
    def new(*args, &block)
80
      scoping { @klass.new(*args, &block) }
81 82
    end

83 84 85 86
    def initialize_copy(other)
      reset
    end

87 88
    alias build new

89
    def create(*args, &block)
90
      scoping { @klass.create(*args, &block) }
91 92 93
    end

    def create!(*args, &block)
94
      scoping { @klass.create!(*args, &block) }
P
Pratik Naik 已提交
95 96
    end

97
    def respond_to?(method, include_private = false)
98 99 100
      arel.respond_to?(method, include_private)     ||
        Array.method_defined?(method)               ||
        @klass.respond_to?(method, include_private) ||
101
        super
102 103
    end

P
Pratik Naik 已提交
104 105 106
    def to_a
      return @records if loaded?

107 108 109 110
      default_scoped = with_default_scope

      if default_scoped.equal?(self)
        @records = if @readonly_value.nil? && !@klass.locking_enabled?
111
          eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
112 113 114 115
        else
          IdentityMap.without do
            eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
          end
116
        end
P
Pratik Naik 已提交
117

118 119 120 121 122
        preload = @preload_values
        preload +=  @includes_values unless eager_loading?
        preload.each do |associations|
          ActiveRecord::Associations::Preloader.new(@records, associations).run
        end
123

124 125 126 127 128 129 130
        # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
        # are JOINS and no explicit SELECT.
        readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
        @records.each { |record| record.readonly! } if readonly
      else
        @records = default_scoped.to_a
      end
P
Pratik Naik 已提交
131 132 133 134 135

      @loaded = true
      @records
    end

136 137 138
    def as_json(options = nil) #:nodoc:
      to_a.as_json(options)
    end
139

R
Rizwan Reza 已提交
140
    # Returns size of the records.
141 142 143 144
    def size
      loaded? ? @records.length : count
    end

R
Rizwan Reza 已提交
145
    # Returns true if there are no records.
146
    def empty?
147 148 149 150
      return @records.empty? if loaded?

      c = count
      c.respond_to?(:zero?) ? c.zero? : c.empty?
151 152
    end

P
Pratik Naik 已提交
153 154 155 156 157 158 159 160 161 162 163 164
    def any?
      if block_given?
        to_a.any? { |*block_args| yield(*block_args) }
      else
        !empty?
      end
    end

    def many?
      if block_given?
        to_a.many? { |*block_args| yield(*block_args) }
      else
165
        @limit_value ? to_a.many? : size > 1
P
Pratik Naik 已提交
166 167 168
      end
    end

169 170 171 172 173
    # Scope all queries to the current scope.
    #
    # ==== Example
    #
    #   Comment.where(:post_id => 1).scoping do
174
    #     Comment.first # SELECT * FROM comments WHERE post_id = 1
175 176 177 178 179
    #   end
    #
    # Please check unscoped if you want to remove all previous scopes (including
    # the default_scope) during the execution of a block.
    def scoping
180
      @klass.send(:with_scope, self, :overwrite) { yield }
181 182
    end

183 184 185 186 187 188 189 190
    # Updates all records with details given if they match a set of conditions supplied, limits and order can
    # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
    # database. It does not instantiate the involved models and it does not trigger Active Record callbacks
    # or validations.
    #
    # ==== Parameters
    #
    # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
191
    # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
192
    #   See conditions in the intro.
193 194 195 196 197 198 199 200 201 202 203 204 205
    # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
    #
    # ==== Examples
    #
    #   # Update all customers with the given attributes
    #   Customer.update_all :wants_email => true
    #
    #   # Update all books with 'Rails' in their title
    #   Book.update_all "author = 'David'", "title LIKE '%Rails%'"
    #
    #   # Update all avatars migrated more than a week ago
    #   Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]
    #
206
    #   # Update all books that match conditions, but limit it to 5 ordered by date
207
    #   Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
208 209 210 211 212 213
    #
    #   # Conditions from the current relation also works
    #   Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
    #
    #   # The same idea applies to limit and order
    #   Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
214
    def update_all(updates, conditions = nil, options = {})
215
      IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled?
216 217 218
      if conditions || options.present?
        where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
      else
219 220 221 222
        stmt = arel.compile_update(Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)))

        if limit = arel.limit
          stmt.take limit
223
        end
A
Aaron Patterson 已提交
224

225
        stmt.order(*arel.orders)
226
        stmt.key = table[primary_key]
227
        @klass.connection.update stmt.to_sql, 'SQL', bind_values
228 229 230 231 232 233 234 235 236
      end
    end

    # Updates an object (or multiple objects) and saves it to the database, if validations pass.
    # The resulting object is returned whether the object was saved successfully to the database or not.
    #
    # ==== Parameters
    #
    # * +id+ - This should be the id or an array of ids to be updated.
237
    # * +attributes+ - This should be a hash of attributes or an array of hashes.
238 239 240
    #
    # ==== Examples
    #
241
    #   # Updates one record
242 243
    #   Person.update(15, :user_name => 'Samuel', :group => 'expert')
    #
244
    #   # Updates multiple records
245 246 247 248
    #   people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
    #   Person.update(people.keys, people.values)
    def update(id, attributes)
      if id.is_a?(Array)
249
        id.each.with_index.map {|one_id, idx| update(one_id, attributes[idx])}
250 251 252 253 254 255 256
      else
        object = find(id)
        object.update_attributes(attributes)
        object
      end
    end

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    # Destroys the records matching +conditions+ by instantiating each
    # record and calling its +destroy+ method. Each object's callbacks are
    # executed (including <tt>:dependent</tt> association options and
    # +before_destroy+/+after_destroy+ Observer methods). Returns the
    # collection of objects that were destroyed; each will be frozen, to
    # reflect that no changes should be made (since they can't be
    # persisted).
    #
    # Note: Instantiation, callback execution, and deletion of each
    # record can be time consuming when you're removing many records at
    # once. It generates at least one SQL +DELETE+ query per record (or
    # possibly more, to enforce your callbacks). If you want to delete many
    # rows quickly, without concern for their associations or callbacks, use
    # +delete_all+ instead.
    #
    # ==== Parameters
    #
    # * +conditions+ - A string, array, or hash that specifies which records
    #   to destroy. If omitted, all records are destroyed. See the
    #   Conditions section in the introduction to ActiveRecord::Base for
    #   more information.
    #
    # ==== Examples
    #
    #   Person.destroy_all("last_login < '2004-04-04'")
    #   Person.destroy_all(:status => "inactive")
R
Rodrigo Navarro 已提交
283
    #   Person.where(:age => 0..18).destroy_all
284 285 286 287
    def destroy_all(conditions = nil)
      if conditions
        where(conditions).destroy_all
      else
288
        to_a.each {|object| object.destroy }.tap { reset }
289
      end
P
Pratik Naik 已提交
290 291
    end

P
Pratik Naik 已提交
292
    # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
293
    # therefore all callbacks and filters are fired off before the object is deleted. This method is
P
Pratik Naik 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
    #
    # This essentially finds the object (or multiple objects) with the given id, creates a new object
    # from the attributes, and then calls destroy on it.
    #
    # ==== Parameters
    #
    # * +id+ - Can be either an Integer or an Array of Integers.
    #
    # ==== Examples
    #
    #   # Destroy a single object
    #   Todo.destroy(1)
    #
    #   # Destroy multiple objects
    #   todos = [1,2,3]
    #   Todo.destroy(todos)
    def destroy(id)
      if id.is_a?(Array)
        id.map { |one_id| destroy(one_id) }
      else
        find(id).destroy
      end
    end

P
Pratik Naik 已提交
319 320 321
    # Deletes the records matching +conditions+ without instantiating the records first, and hence not
    # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
    # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
322
    # though, in particular <tt>:dependent</tt> rules defined on associations are not honored. Returns
P
Pratik Naik 已提交
323 324 325 326 327 328 329 330 331 332
    # the number of rows affected.
    #
    # ==== Parameters
    #
    # * +conditions+ - Conditions are specified the same way as with +find+ method.
    #
    # ==== Example
    #
    #   Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
    #   Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
R
Rodrigo Navarro 已提交
333
    #   Post.where(:person_id => 5).where(:category => ['Something', 'Else']).delete_all
P
Pratik Naik 已提交
334
    #
335 336
    # Both calls delete the affected posts all at once with a single DELETE statement.
    # If you need to destroy dependent associations or call your <tt>before_*</tt> or
R
Rizwan Reza 已提交
337
    # +after_destroy+ callbacks, use the +destroy_all+ method instead.
P
Pratik Naik 已提交
338
    def delete_all(conditions = nil)
339
      IdentityMap.repository[symbolized_base_class] = {} if IdentityMap.enabled?
A
Aaron Patterson 已提交
340 341 342 343
      if conditions
        where(conditions).delete_all
      else
        statement = arel.compile_delete
344 345 346
        affected = @klass.connection.delete(
          statement.to_sql, 'SQL', bind_values)

A
Aaron Patterson 已提交
347 348 349
        reset
        affected
      end
P
Pratik Naik 已提交
350 351
    end

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    # Deletes the row with a primary key matching the +id+ argument, using a
    # SQL +DELETE+ statement, and returns the number of rows deleted. Active
    # Record objects are not instantiated, so the object's callbacks are not
    # executed, including any <tt>:dependent</tt> association options or
    # Observer methods.
    #
    # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
    #
    # Note: Although it is often much faster than the alternative,
    # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
    # your application that ensures referential integrity or performs other
    # essential jobs.
    #
    # ==== Examples
    #
    #   # Delete a single row
    #   Todo.delete(1)
    #
    #   # Delete multiple rows
    #   Todo.delete([2,3,4])
372
    def delete(id_or_array)
373
      IdentityMap.remove_by_id(self.symbolized_base_class, id_or_array) if IdentityMap.enabled?
374
      where(primary_key => id_or_array).delete_all
375 376
    end

377
    def reload
P
Pratik Naik 已提交
378
      reset
379 380
      to_a # force reload
      self
P
Pratik Naik 已提交
381 382 383
    end

    def reset
384
      @first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
385
      @should_eager_load = @join_dependency = nil
P
Pratik Naik 已提交
386
      @records = []
387 388 389
      self
    end

P
Pratik Naik 已提交
390
    def to_sql
391
      @to_sql ||= arel.to_sql
P
Pratik Naik 已提交
392 393
    end

394
    def where_values_hash
395
      equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
A
Aaron Patterson 已提交
396 397 398
        node.left.relation.name == table_name
      }

A
Aaron Patterson 已提交
399
      Hash[equalities.map { |where| [where.left.name, where.right] }]
400 401 402
    end

    def scope_for_create
403
      @scope_for_create ||= where_values_hash.merge(create_with_value)
P
Pratik Naik 已提交
404 405
    end

406
    def eager_loading?
407 408 409 410 411 412 413 414 415 416 417
      @should_eager_load ||=
        @eager_load_values.any? ||
        @includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
    end

    # Joins that are also marked for preloading. In which case we should just eager load them.
    # Note that this is a naive implementation because we could have strings and symbols which
    # represent the same association, but that aren't matched by this. Also, we could have
    # nested hashes which partially match, e.g. { :a => :b } & { :a => [:b, :c] }
    def joined_includes_values
      @includes_values & @joins_values
418 419
    end

420 421 422 423 424
    def ==(other)
      case other
      when Relation
        other.to_sql == to_sql
      when Array
425
        to_a == other
426 427 428
      end
    end

P
Pratik Naik 已提交
429 430 431 432
    def inspect
      to_a.inspect
    end

433
    def with_default_scope #:nodoc:
434
      if default_scoped? && default_scope = klass.send(:build_default_scope)
435 436 437
        default_scope = default_scope.merge(self)
        default_scope.default_scoped = false
        default_scope
438 439 440 441 442
      else
        self
      end
    end

443
    protected
444 445

    def method_missing(method, *args, &block)
446
      if Array.method_defined?(method)
447
        to_a.send(method, *args, &block)
448
      elsif @klass.respond_to?(method)
449
        scoping { @klass.send(method, *args, &block) }
450 451
      elsif arel.respond_to?(method)
        arel.send(method, *args, &block)
452 453
      else
        super
454
      end
455 456
    end

457 458
    private

459
    def references_eager_loaded_tables?
460 461 462 463 464 465 466 467 468 469
      joined_tables = arel.join_sources.map do |join|
        if join.is_a?(Arel::Nodes::StringJoin)
          tables_in_string(join.left)
        else
          [join.left.table_name, join.left.table_alias]
        end
      end

      joined_tables += [table.name, table.table_alias]

470
      # always convert table names to downcase as in Oracle quoted table names are in uppercase
471 472
      joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq

473
      (tables_in_string(to_sql) - joined_tables).any?
474 475 476 477
    end

    def tables_in_string(string)
      return [] if string.blank?
478
      # always convert table names to downcase as in Oracle quoted table names are in uppercase
479
      # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
480
      string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
481 482
    end

483 484
  end
end