relation.rb 22.5 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
require 'arel/collectors/bind'
3

4
module ActiveRecord
R
Rizwan Reza 已提交
5
  # = Active Record Relation
6
  class Relation
7
    MULTI_VALUE_METHODS  = [:includes, :eager_load, :preload, :select, :group,
8
                            :order, :joins, :where, :having, :bind, :references,
J
Jon Leighton 已提交
9
                            :extending, :unscope]
10 11

    SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
12
                            :reverse_order, :distinct, :create_with, :uniq]
13
    INVALID_METHODS_FOR_DELETE_ALL = [:limit, :distinct, :offset, :group, :having]
14

J
Jon Leighton 已提交
15 16
    VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS

17
    include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
18

19
    attr_reader :table, :klass, :loaded, :predicate_builder
20
    alias :model :klass
21
    alias :loaded? :loaded
22

23
    def initialize(klass, table, predicate_builder, values = {})
24 25 26
      @klass  = klass
      @table  = table
      @values = values
27
      @offsets = {}
28
      @loaded = false
29
      @predicate_builder = predicate_builder
30 31
    end

32 33 34 35 36 37 38 39
    def initialize_copy(other)
      # This method is a hot spot, so for now, use Hash[] to dup the hash.
      #   https://bugs.ruby-lang.org/issues/7166
      @values        = Hash[@values]
      @values[:bind] = @values[:bind].dup if @values.key? :bind
      reset
    end

N
Noemj 已提交
40
    def insert(values) # :nodoc:
41 42
      primary_key_value = nil

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

        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

N
Noemj 已提交
57
      substitutes, binds = substitute_values values
58

59
      if values.empty? # empty insert
60
        im.values = Arel.sql(connection.empty_insert_statement_value)
61
      else
62
        im.insert substitutes
63
      end
64

N
Noemj 已提交
65
      @klass.connection.insert(
66
        im,
67
        'SQL',
68
        primary_key,
69 70 71
        primary_key_value,
        nil,
        binds)
72
    end
73

74
    def _update_record(values, id, id_was) # :nodoc:
N
Noemj 已提交
75
      substitutes, binds = substitute_values values
E
Edo Balvers 已提交
76 77 78 79 80 81 82

      scope = @klass.unscoped

      if @klass.finder_needs_type_condition?
        scope.unscope!(where: @klass.inheritance_column)
      end

83 84 85 86 87
      relation = scope.where(@klass.primary_key => (id_was || id))
      bvs = binds + relation.bind_values
      um = relation
        .arel
        .compile_update(substitutes, @klass.primary_key)
88

N
Noemj 已提交
89
      @klass.connection.update(
90 91
        um,
        'SQL',
92 93
        bvs,
      )
N
Noemj 已提交
94 95
    end

N
Noemj 已提交
96
    def substitute_values(values) # :nodoc:
97
      binds = values.map do |arel_attr, value|
N
Noemj 已提交
98 99 100
        [@klass.columns_hash[arel_attr.name], value]
      end

101
      substitutes = values.each_with_index.map do |(arel_attr, _), i|
102
        [arel_attr, @klass.connection.substitute_at(binds[i][0])]
N
Noemj 已提交
103 104 105
      end

      [substitutes, binds]
106
    end
N
Noemj 已提交
107

O
Oscar Del Ben 已提交
108
    # Initializes new record from relation while maintaining the current
109 110 111 112 113 114 115 116 117 118 119
    # scope.
    #
    # Expects arguments in the same format as +Base.new+.
    #
    #   users = User.where(name: 'DHH')
    #   user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
    #
    # You can also pass a block to new with the new record as argument:
    #
    #   user = users.new { |user| user.name = 'Oscar' }
    #   user.name # => Oscar
P
Pratik Naik 已提交
120
    def new(*args, &block)
121
      scoping { @klass.new(*args, &block) }
122 123
    end

124 125
    alias build new

O
Oscar Del Ben 已提交
126
    # Tries to create a new record with the same scoped attributes
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    # defined in the relation. Returns the initialized object if validation fails.
    #
    # Expects arguments in the same format as +Base.create+.
    #
    # ==== Examples
    #   users = User.where(name: 'Oscar')
    #   users.create # #<User id: 3, name: "oscar", ...>
    #
    #   users.create(name: 'fxn')
    #   users.create # #<User id: 4, name: "fxn", ...>
    #
    #   users.create { |user| user.name = 'tenderlove' }
    #   # #<User id: 5, name: "tenderlove", ...>
    #
    #   users.create(name: nil) # validation on name
    #   # #<User id: nil, name: nil, ...>
143
    def create(*args, &block)
144
      scoping { @klass.create(*args, &block) }
145 146
    end

147 148 149 150
    # Similar to #create, but calls +create!+ on the base class. Raises
    # an exception if a validation error occurs.
    #
    # Expects arguments in the same format as <tt>Base.create!</tt>.
151
    def create!(*args, &block)
152
      scoping { @klass.create!(*args, &block) }
P
Pratik Naik 已提交
153 154
    end

155 156 157 158 159 160 161 162 163 164 165 166
    def first_or_create(attributes = nil, &block) # :nodoc:
      first || create(attributes, &block)
    end

    def first_or_create!(attributes = nil, &block) # :nodoc:
      first || create!(attributes, &block)
    end

    def first_or_initialize(attributes = nil, &block) # :nodoc:
      first || new(attributes, &block)
    end

167 168
    # Finds the first record with the given attributes, or creates a record
    # with the attributes if one is not found:
169
    #
170
    #   # Find the first user named "Penélope" or create a new one.
171
    #   User.find_or_create_by(first_name: 'Penélope')
172
    #   # => #<User id: 1, first_name: "Penélope", last_name: nil>
173
    #
174
    #   # Find the first user named "Penélope" or create a new one.
175
    #   # We already have one so the existing record will be returned.
176
    #   User.find_or_create_by(first_name: 'Penélope')
177
    #   # => #<User id: 1, first_name: "Penélope", last_name: nil>
178
    #
179 180
    #   # Find the first user named "Scarlett" or create a new one with
    #   # a particular last name.
181
    #   User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
182
    #   # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
183
    #
184 185 186 187 188
    # This method accepts a block, which is passed down to +create+. The last example
    # above can be alternatively written this way:
    #
    #   # Find the first user named "Scarlett" or create a new one with a
    #   # different last name.
189
    #   User.find_or_create_by(first_name: 'Scarlett') do |user|
190
    #     user.last_name = 'Johansson'
191
    #   end
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    #   # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
    #
    # This method always returns a record, but if creation was attempted and
    # failed due to validation errors it won't be persisted, you get what
    # +create+ returns in such situation.
    #
    # Please note *this method is not atomic*, it runs first a SELECT, and if
    # there are no results an INSERT is attempted. If there are other threads
    # or processes there is a race condition between both calls and it could
    # be the case that you end up with two similar records.
    #
    # Whether that is a problem or not depends on the logic of the
    # application, but in the particular case in which rows have a UNIQUE
    # constraint an exception may be raised, just retry:
    #
    #  begin
    #    CreditAccount.find_or_create_by(user_id: user.id)
    #  rescue ActiveRecord::RecordNotUnique
    #    retry
    #  end
    #
213 214 215 216
    def find_or_create_by(attributes, &block)
      find_by(attributes) || create(attributes, &block)
    end

217 218
    # Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception
    # is raised if the created record is invalid.
219 220 221 222 223 224 225 226 227
    def find_or_create_by!(attributes, &block)
      find_by(attributes) || create!(attributes, &block)
    end

    # Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
    def find_or_initialize_by(attributes, &block)
      find_by(attributes) || new(attributes, &block)
    end

228 229 230 231 232 233 234 235
    # Runs EXPLAIN on the query or queries triggered by this relation and
    # returns the result as a string. The string is formatted imitating the
    # ones printed by the database shell.
    #
    # Note that this method actually runs the queries, since the results of some
    # are needed by the next ones when eager loading is going on.
    #
    # Please see further details in the
O
Oscar Del Ben 已提交
236
    # {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
A
Arun Agrawal 已提交
237
    def explain
238
      #TODO: Fix for binds.
A
Aaron Patterson 已提交
239
      exec_explain(collecting_queries_for_explain { exec_queries })
240
    end
X
Xavier Noria 已提交
241

O
Oscar Del Ben 已提交
242
    # Converts relation objects to Array.
243
    def to_a
J
Jon Leighton 已提交
244
      load
P
Pratik Naik 已提交
245 246 247
      @records
    end

248 249 250 251 252
    # Serializes the relation objects Array.
    def encode_with(coder)
      coder.represent_seq(nil, to_a)
    end

253 254 255
    def as_json(options = nil) #:nodoc:
      to_a.as_json(options)
    end
256

R
Rizwan Reza 已提交
257
    # Returns size of the records.
258
    def size
259
      loaded? ? @records.length : count(:all)
260 261
    end

R
Rizwan Reza 已提交
262
    # Returns true if there are no records.
263
    def empty?
264 265
      return @records.empty? if loaded?

266 267 268
      if limit_value == 0
        true
      else
269
        c = count(:all)
270 271
        c.respond_to?(:zero?) ? c.zero? : c.empty?
      end
272 273
    end

O
Oscar Del Ben 已提交
274
    # Returns true if there are any records.
P
Pratik Naik 已提交
275 276 277 278 279 280 281 282
    def any?
      if block_given?
        to_a.any? { |*block_args| yield(*block_args) }
      else
        !empty?
      end
    end

V
Vijay Dev 已提交
283
    # Returns true if there is more than one record.
P
Pratik Naik 已提交
284 285 286 287
    def many?
      if block_given?
        to_a.many? { |*block_args| yield(*block_args) }
      else
288
        limit_value ? to_a.many? : size > 1
P
Pratik Naik 已提交
289 290 291
      end
    end

292 293
    # Scope all queries to the current scope.
    #
294
    #   Comment.where(post_id: 1).scoping do
295
    #     Comment.first
296
    #   end
297
    #   # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
298 299 300 301
    #
    # Please check unscoped if you want to remove all previous scopes (including
    # the default_scope) during the execution of a block.
    def scoping
302 303 304 305
      previous, klass.current_scope = klass.current_scope, self
      yield
    ensure
      klass.current_scope = previous
306 307
    end

308
    # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
309 310 311 312
    # 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. Values passed to `update_all` will not go through
    # ActiveRecord's type-casting behavior. It should receive only values that can be passed as-is to the SQL
    # database.
313 314 315 316 317 318 319 320
    #
    # ==== Parameters
    #
    # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
    #
    # ==== Examples
    #
    #   # Update all customers with the given attributes
O
Oscar Del Ben 已提交
321
    #   Customer.update_all wants_email: true
322 323
    #
    #   # Update all books with 'Rails' in their title
O
Oscar Del Ben 已提交
324
    #   Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
325
    #
326
    #   # Update all books that match conditions, but limit it to 5 ordered by date
327
    #   Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
328
    def update_all(updates)
329 330
      raise ArgumentError, "Empty list of attributes to change" if updates.blank?

331
      stmt = Arel::UpdateManager.new
332 333 334 335

      stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
      stmt.table(table)
      stmt.key = table[primary_key]
A
Aaron Patterson 已提交
336

337
      if joins_values.any?
338 339 340 341 342
        @klass.connection.join_to_update(stmt, arel)
      else
        stmt.take(arel.limit)
        stmt.order(*arel.orders)
        stmt.wheres = arel.constraints
343
      end
344

345
      bvs = arel.bind_values + bind_values
346
      @klass.connection.update stmt, 'SQL', bvs
347 348 349 350 351 352 353 354
    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.
355
    # * +attributes+ - This should be a hash of attributes or an array of hashes.
356 357 358
    #
    # ==== Examples
    #
359
    #   # Updates one record
O
Oscar Del Ben 已提交
360
    #   Person.update(15, user_name: 'Samuel', group: 'expert')
361
    #
362
    #   # Updates multiple records
363 364 365 366
    #   people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
    #   Person.update(people.keys, people.values)
    def update(id, attributes)
      if id.is_a?(Array)
367
        id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) }
368 369
      else
        object = find(id)
370
        object.update(attributes)
371 372 373 374
        object
      end
    end

375 376
    # Destroys the records matching +conditions+ by instantiating each
    # record and calling its +destroy+ method. Each object's callbacks are
377
    # executed (including <tt>:dependent</tt> association options). Returns the
378
    # collection of objects that were destroyed; each will be frozen, to
379
    # reflect that no changes should be made (since they can't be persisted).
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    #
    # 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'")
O
Oscar Del Ben 已提交
398
    #   Person.destroy_all(status: "inactive")
399
    #   Person.where(age: 0..18).destroy_all
400 401 402 403
    def destroy_all(conditions = nil)
      if conditions
        where(conditions).destroy_all
      else
404
        to_a.each(&:destroy).tap { reset }
405
      end
P
Pratik Naik 已提交
406 407
    end

J
typo  
Jo Liss 已提交
408
    # Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
409
    # therefore all callbacks and filters are fired off before the object is deleted. This method is
P
Pratik Naik 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    # 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

435 436 437 438 439 440
    # 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 though, in particular
    # <tt>:dependent</tt> rules defined on associations are not honored. Returns the
    # number of rows affected.
P
Pratik Naik 已提交
441 442 443
    #
    #   Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
    #   Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
444
    #   Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
P
Pratik Naik 已提交
445
    #
446 447
    # 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 已提交
448
    # +after_destroy+ callbacks, use the +destroy_all+ method instead.
449
    #
450
    # If an invalid method is supplied, +delete_all+ raises an ActiveRecord error:
451 452
    #
    #   Post.limit(100).delete_all
453
    #   # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit
P
Pratik Naik 已提交
454
    def delete_all(conditions = nil)
455 456 457 458 459 460 461 462 463 464
      invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select { |method|
        if MULTI_VALUE_METHODS.include?(method)
          send("#{method}_values").any?
        else
          send("#{method}_value")
        end
      }
      if invalid_methods.any?
        raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}")
      end
465

A
Aaron Patterson 已提交
466 467 468
      if conditions
        where(conditions).delete_all
      else
469
        stmt = Arel::DeleteManager.new
470 471
        stmt.from(table)

472
        if joins_values.any?
473 474 475 476 477 478
          @klass.connection.join_to_delete(stmt, arel, table[primary_key])
        else
          stmt.wheres = arel.constraints
        end

        affected = @klass.connection.delete(stmt, 'SQL', bind_values)
479

A
Aaron Patterson 已提交
480 481 482
        reset
        affected
      end
P
Pratik Naik 已提交
483 484
    end

485 486 487
    # 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
488
    # executed, including any <tt>:dependent</tt> association options.
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    #
    # 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])
504
    def delete(id_or_array)
505
      where(primary_key => id_or_array).delete_all
506 507
    end

J
Jon Leighton 已提交
508 509 510 511 512 513 514
    # Causes the records to be loaded from the database if they have not
    # been loaded already. You can use this if for some reason you need
    # to explicitly load some records before actually using them. The
    # return value is the relation itself, not the records.
    #
    #   Post.where(published: true).load # => #<ActiveRecord::Relation>
    def load
515
      exec_queries unless loaded?
J
Jon Leighton 已提交
516

J
Jon Leighton 已提交
517 518 519
      self
    end

O
Oscar Del Ben 已提交
520
    # Forces reloading of relation.
521
    def reload
P
Pratik Naik 已提交
522
      reset
J
Jon Leighton 已提交
523
      load
P
Pratik Naik 已提交
524 525 526
    end

    def reset
527
      @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
528
      @should_eager_load = @join_dependency = nil
P
Pratik Naik 已提交
529
      @records = []
530
      @offsets = {}
531 532 533
      self
    end

O
Oscar Del Ben 已提交
534 535
    # Returns sql statement for the relation.
    #
536
    #   User.where(name: 'Oscar').to_sql
537
    #   # => SELECT "users".* FROM "users"  WHERE "users"."name" = 'Oscar'
P
Pratik Naik 已提交
538
    def to_sql
539
      @to_sql ||= begin
540 541
                    relation   = self
                    connection = klass.connection
542
                    visitor    = connection.visitor
543

544
                    if eager_loading?
545
                      find_with_associations { |rel| relation = rel }
546 547
                    end

548
                    arel  = relation.arel
549 550 551 552
                    binds = (arel.bind_values + relation.bind_values).dup
                    binds.map! { |bv| connection.quote(*bv.reverse) }
                    collect = visitor.accept(arel.ast, Arel::Collectors::Bind.new)
                    collect.substitute_binds(binds).join
553
                  end
P
Pratik Naik 已提交
554 555
    end

556
    # Returns a hash of where conditions.
O
Oscar Del Ben 已提交
557
    #
558 559
    #   User.where(name: 'Oscar').where_values_hash
    #   # => {name: "Oscar"}
560
    def where_values_hash(relation_table_name = table_name)
561
      equalities = where_values.grep(Arel::Nodes::Equality).find_all { |node|
562
        node.left.relation.name == relation_table_name
A
Aaron Patterson 已提交
563 564
      }

565
      binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
566 567 568

      Hash[equalities.map { |where|
        name = where.left.name
569 570 571 572 573 574 575
        [name, binds.fetch(name.to_s) {
          case where.right
          when Array then where.right.map(&:val)
          else
            where.right.val
          end
        }]
576
      }]
577 578 579
    end

    def scope_for_create
580
      @scope_for_create ||= where_values_hash.merge(create_with_value)
P
Pratik Naik 已提交
581 582
    end

O
Oscar Del Ben 已提交
583
    # Returns true if relation needs eager loading.
584
    def eager_loading?
585
      @should_eager_load ||=
586 587
        eager_load_values.any? ||
        includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
588 589 590 591 592
    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
593
    # nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
594
    def joined_includes_values
595
      includes_values & joins_values
596 597
    end

598 599 600 601 602 603
    # +uniq+ and +uniq!+ are silently deprecated. +uniq_value+ delegates to +distinct_value+
    # to maintain backwards compatibility. Use +distinct_value+ instead.
    def uniq_value
      distinct_value
    end

O
Oscar Del Ben 已提交
604
    # Compares two relations for equality.
605 606
    def ==(other)
      case other
607
      when Associations::CollectionProxy, AssociationRelation
608
        self == other.to_a
609 610 611
      when Relation
        other.to_sql == to_sql
      when Array
612
        to_a == other
613 614 615
      end
    end

616 617 618 619
    def pretty_print(q)
      q.pp(self.to_a)
    end

620
    # Returns true if relation is blank.
621 622 623 624
    def blank?
      to_a.blank?
    end

625
    def values
626
      Hash[@values]
627 628
    end

629
    def inspect
630
      entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
J
Jon Leighton 已提交
631
      entries[10] = '...' if entries.size == 11
632

J
Jon Leighton 已提交
633
      "#<#{self.class.name} [#{entries.join(', ')}]>"
634 635
    end

636 637
    private

J
Jon Leighton 已提交
638
    def exec_queries
639
      @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, arel.bind_values + bind_values)
J
Jon Leighton 已提交
640

641 642
      preload = preload_values
      preload +=  includes_values unless eager_loading?
643
      preloader = build_preloader
644
      preload.each do |associations|
645
        preloader.preload @records, associations
J
Jon Leighton 已提交
646 647
      end

648
      @records.each(&:readonly!) if readonly_value
649

J
Jon Leighton 已提交
650 651 652 653
      @loaded = true
      @records
    end

654 655 656 657
    def build_preloader
      ActiveRecord::Associations::Preloader.new
    end

658
    def references_eager_loaded_tables?
659
      joined_tables = arel.join_sources.map do |join|
660 661 662
        if join.is_a?(Arel::Nodes::StringJoin)
          tables_in_string(join.left)
        else
663 664 665 666 667 668
          [join.left.table_name, join.left.table_alias]
        end
      end

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

669
      # always convert table names to downcase as in Oracle quoted table names are in uppercase
670
      joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
671

672
      (references_values - joined_tables).any?
673
    end
674 675 676 677 678

    def tables_in_string(string)
      return [] if string.blank?
      # always convert table names to downcase as in Oracle quoted table names are in uppercase
      # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
679
      string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ['raw_sql_']
680
    end
681 682
  end
end