query_methods.rb 25.6 KB
Newer Older
1
require 'active_support/core_ext/array/wrap'
2

3 4
module ActiveRecord
  module QueryMethods
5 6
    extend ActiveSupport::Concern

7 8
    Relation::MULTI_VALUE_METHODS.each do |name|
      class_eval <<-CODE, __FILE__, __LINE__ + 1
9 10 11 12 13 14 15 16
        def #{name}_values                   # def select_values
          @values[:#{name}] || []            #   @values[:select] || []
        end                                  # end
                                             #
        def #{name}_values=(values)          # def select_values=(values)
          raise ImmutableRelation if @loaded #   raise ImmutableRelation if @loaded
          @values[:#{name}] = values         #   @values[:select] = values
        end                                  # end
17 18 19 20 21
      CODE
    end

    (Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
      class_eval <<-CODE, __FILE__, __LINE__ + 1
22 23 24
        def #{name}_value                    # def readonly_value
          @values[:#{name}]                  #   @values[:readonly]
        end                                  # end
25 26 27
      CODE
    end

28 29 30 31 32 33 34
    Relation::SINGLE_VALUE_METHODS.each do |name|
      class_eval <<-CODE, __FILE__, __LINE__ + 1
        def #{name}_value=(value)            # def readonly_value=(value)
          raise ImmutableRelation if @loaded #   raise ImmutableRelation if @loaded
          @values[:#{name}] = value          #   @values[:readonly] = value
        end                                  # end
      CODE
35 36
    end

O
Oscar Del Ben 已提交
37
    def create_with_value # :nodoc:
38
      @values[:create_with] || {}
39
    end
40 41

    alias extensions extending_values
42

O
Oscar Del Ben 已提交
43 44 45 46 47 48 49 50 51 52
    # Specify relationships to be included in the result set. For
    # example:
    #
    #   users = User.includes(:address)
    #   users.each do |user|
    #     user.address.city
    #   end
    #
    # allows you to access the +address+ attribute of the +User+ model without
    # firing an additional query. This will often result in a
53 54 55 56 57 58 59 60 61 62 63 64
    # performance improvement over a simple +join+.
    #
    # === conditions
    #
    # If you want to add conditions to your included models you'll have
    # to explicitly reference them. For example:
    #
    #   User.includes(:posts).where('posts.name = ?', 'example')
    #
    # Will throw an error, but this will work:
    #
    #   User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
65
    def includes(*args)
J
Jon Leighton 已提交
66
      args.empty? ? self : spawn.includes!(*args)
67
    end
68

69
    # Like #includes, but modifies the relation in place.
70
    def includes!(*args)
71
      args.reject! {|a| a.blank? }
A
Aaron Patterson 已提交
72

73 74
      self.includes_values = (includes_values + args).flatten.uniq
      self
75
    end
76

77 78 79 80 81 82
    # Forces eager loading by performing a LEFT OUTER JOIN on +args+:
    #
    #   User.eager_load(:posts)
    #   => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
    #   FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
    #   "users"."id"
83
    def eager_load(*args)
J
Jon Leighton 已提交
84
      args.blank? ? self : spawn.eager_load!(*args)
85
    end
86

87
    # Like #eager_load, but modifies relation in place.
88
    def eager_load!(*args)
89 90
      self.eager_load_values += args
      self
91 92
    end

93 94 95 96
    # Allows preloading of +args+, in the same way that +includes+ does:
    #
    #   User.preload(:posts)
    #   => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
97
    def preload(*args)
J
Jon Leighton 已提交
98
      args.blank? ? self : spawn.preload!(*args)
99
    end
100

101
    # Like #preload, but modifies relation in place.
102
    def preload!(*args)
103 104
      self.preload_values += args
      self
105
    end
106

107 108 109 110 111 112 113 114 115
    # Used to indicate that an association is referenced by an SQL string, and should
    # therefore be JOINed in any query rather than loaded separately.
    #
    #   User.includes(:posts).where("posts.name = 'foo'")
    #   # => Doesn't JOIN the posts table, resulting in an error.
    #
    #   User.includes(:posts).where("posts.name = 'foo'").references(:posts)
    #   # => Query now knows the string references posts, so adds a JOIN
    def references(*args)
J
Jon Leighton 已提交
116
      args.blank? ? self : spawn.references!(*args)
117
    end
118

119
    # Like #references, but modifies relation in place.
120
    def references!(*args)
121 122 123
      args.flatten!

      self.references_values = (references_values + args.map!(&:to_s)).uniq
124
      self
125 126
    end

127
    # Works in two unique ways.
128
    #
129 130
    # First: takes a block so it can be used just like Array#select.
    #
131
    #   Model.all.select { |m| m.field == value }
132 133 134 135 136
    #
    # This will build an array of objects from the database for the scope,
    # converting them into an array and iterating through them using Array#select.
    #
    # Second: Modifies the SELECT statement for the query so that only certain
V
Vijay Dev 已提交
137
    # fields are retrieved:
138
    #
139 140
    #   Model.select(:field)
    #   # => [#<Model field:value>]
141 142
    #
    # Although in the above example it looks as though this method returns an
V
Vijay Dev 已提交
143
    # array, it actually returns a relation object and can have other query
144 145
    # methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
    #
146
    # The argument to the method can also be an array of fields.
147
    #
148 149
    #   Model.select(:field, :other_field, :and_one_more)
    #   # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
150
    #
151 152
    # Accessing attributes of an object that do not have fields retrieved by a select
    # will throw <tt>ActiveModel::MissingAttributeError</tt>:
153
    #
154 155 156
    #   Model.select(:field).first.other_field
    #   # => ActiveModel::MissingAttributeError: missing attribute: other_field
    def select(*fields)
157
      if block_given?
158
        to_a.select { |*block_args| yield(*block_args) }
159
      else
160 161
        raise ArgumentError, 'Call this with at least one field' if fields.empty?
        spawn.select!(*fields)
162 163 164
      end
    end

165
    # Like #select, but modifies relation in place.
166 167
    def select!(*fields)
      self.select_values += fields.flatten
168
      self
169
    end
S
Santiago Pastorino 已提交
170

O
Oscar Del Ben 已提交
171 172 173 174 175
    # Allows to specify a group attribute:
    #
    #   User.group(:name)
    #   => SELECT "users".* FROM "users" GROUP BY name
    #
176
    # Returns an array with distinct records based on the +group+ attribute:
O
Oscar Del Ben 已提交
177 178 179 180 181 182
    #
    #   User.select([:id, :name])
    #   => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
    #
    #   User.group(:name)
    #   => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
183
    def group(*args)
J
Jon Leighton 已提交
184
      args.blank? ? self : spawn.group!(*args)
185
    end
186

187
    # Like #group, but modifies relation in place.
188
    def group!(*args)
189 190 191
      args.flatten!

      self.group_values += args
192
      self
193
    end
194

O
Oscar Del Ben 已提交
195 196 197 198 199 200 201 202 203 204
    # Allows to specify an order attribute:
    #
    #   User.order('name')
    #   => SELECT "users".* FROM "users" ORDER BY name
    #
    #   User.order('name DESC')
    #   => SELECT "users".* FROM "users" ORDER BY name DESC
    #
    #   User.order('name DESC, email')
    #   => SELECT "users".* FROM "users" ORDER BY name DESC, email
205
    def order(*args)
J
Jon Leighton 已提交
206
      args.blank? ? self : spawn.order!(*args)
207
    end
208

209
    # Like #order, but modifies relation in place.
210
    def order!(*args)
211
      args.flatten!
212

213
      references = args.reject { |arg| Arel::Node === arg }
214
      references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
215
      references!(references) if references.any?
216

217
      self.order_values = args + self.order_values
218
      self
219
    end
220

221 222 223 224 225 226 227 228
    # Replaces any existing order defined on the relation with the specified order.
    #
    #   User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
    #
    # Subsequent calls to order on the same relation will be appended. For example:
    #
    #   User.order('email DESC').reorder('id ASC').order('name ASC')
    #
229
    # generates a query with 'ORDER BY name ASC, id ASC'.
S
Sebastian Martinez 已提交
230
    def reorder(*args)
J
Jon Leighton 已提交
231
      args.blank? ? self : spawn.reorder!(*args)
232
    end
233

234
    # Like #reorder, but modifies relation in place.
235
    def reorder!(*args)
236 237
      args.flatten!

238
      self.reordering_value = true
239
      self.order_values = args
240
      self
S
Sebastian Martinez 已提交
241 242
    end

243 244 245 246
    # Performs a joins on +args+:
    #
    #   User.joins(:posts)
    #   => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
247
    def joins(*args)
J
Jon Leighton 已提交
248
      args.compact.blank? ? self : spawn.joins!(*args)
249
    end
250

251
    # Like #joins, but modifies relation in place.
252
    def joins!(*args)
A
Aaron Patterson 已提交
253
      args.flatten!
254

255 256
      self.joins_values += args
      self
P
Pratik Naik 已提交
257 258
    end

A
Aaron Patterson 已提交
259
    def bind(value)
J
Jon Leighton 已提交
260
      spawn.bind!(value)
261 262
    end

263
    def bind!(value)
264 265
      self.bind_values += [value]
      self
A
Aaron Patterson 已提交
266 267
    end

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    # Returns a new relation, which is the result of filtering the current relation
    # according to the conditions in the arguments.
    #
    # #where accepts conditions in one of several formats. In the examples below, the resulting
    # SQL is given as an illustration; the actual query generated may be different depending
    # on the database adapter.
    #
    # === string
    #
    # A single string, without additional arguments, is passed to the query
    # constructor as a SQL fragment, and used in the where clause of the query.
    #
    #    Client.where("orders_count = '2'")
    #    # SELECT * from clients where orders_count = '2';
    #
    # Note that building your own string from user input may expose your application
    # to injection attacks if not done properly. As an alternative, it is recommended
    # to use one of the following methods.
    #
    # === array
    #
    # If an array is passed, then the first element of the array is treated as a template, and
    # the remaining elements are inserted into the template to generate the condition.
    # Active Record takes care of building the query to avoid injection attacks, and will
    # convert from the ruby type to the database type where needed. Elements are inserted
    # into the string in the order in which they appear.
    #
    #   User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
    #   # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
    #
    # Alternatively, you can use named placeholders in the template, and pass a hash as the
    # second element of the array. The names in the template are replaced with the corresponding
    # values from the hash.
    #
    #   User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
    #   # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
    #
    # This can make for more readable code in complex queries.
    #
    # Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
    # than the previous methods; you are responsible for ensuring that the values in the template
    # are properly quoted. The values are passed to the connector for quoting, but the caller
    # is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
    # the values are inserted using the same escapes as the Ruby core method <tt>Kernel::sprintf</tt>.
    #
    #   User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
    #   # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
    #
    # If #where is called with multiple arguments, these are treated as if they were passed as
    # the elements of a single array.
    #
    #   User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
    #   # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
    #
    # When using strings to specify conditions, you can use any operator available from
    # the database. While this provides the most flexibility, you can also unintentionally introduce
    # dependencies on the underlying database. If your code is intended for general consumption,
    # test with multiple database backends.
    #
    # === hash
    #
    # #where will also accept a hash condition, in which the keys are fields and the values
    # are values to be searched for.
    #
    # Fields can be symbols or strings. Values can be single values, arrays, or ranges.
    #
    #    User.where({ name: "Joe", email: "joe@example.com" })
    #    # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
    #
    #    User.where({ name: ["Alice", "Bob"]})
    #    # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
    #
    #    User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
    #    # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
    #
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    # In the case of a belongs_to relationship, an association key can be used
    # to specify the model if an ActiveRecord object is used as the value.
    #
    #    author = Author.find(1)
    #
    #    # The following queries will be equivalent:
    #    Post.where(:author => author)
    #    Post.where(:author_id => author)
    #
    # This also works with polymorphic belongs_to relationships:
    #
    #    treasure = Treasure.create(:name => 'gold coins')
    #    treasure.price_estimates << PriceEstimate.create(:price => 125)
    #
    #    # The following queries will be equivalent:
    #    PriceEstimate.where(:estimate_of => treasure)
    #    PriceEstimate.where(:estimate_of_type => 'Treasure', :estimate_of_id => treasure)
    #
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    # === Joins
    #
    # If the relation is the result of a join, you may create a condition which uses any of the
    # tables in the join. For string and array conditions, use the table name in the condition.
    #
    #    User.joins(:posts).where("posts.created_at < ?", Time.now)
    #
    # For hash conditions, you can either use the table name in the key, or use a sub-hash.
    #
    #    User.joins(:posts).where({ "posts.published" => true })
    #    User.joins(:posts).where({ :posts => { :published => true } })
    #
    # === empty condition
    #
    # If the condition returns true for blank?, then where is a no-op and returns the current relation.
376
    def where(opts, *rest)
J
Jon Leighton 已提交
377
      opts.blank? ? self : spawn.where!(opts, *rest)
378 379
    end

380 381 382
    # #where! is identical to #where, except that instead of returning a new relation, it adds
    # the condition to the existing relation.
    def where!(opts, *rest)
383
      references!(PredicateBuilder.references(opts)) if Hash === opts
384

385 386
      self.where_values += build_where(opts, rest)
      self
387
    end
P
Pratik Naik 已提交
388

389 390 391 392
    # Allows to specify a HAVING clause. Note that you can't use HAVING
    # without also specifying a GROUP clause.
    #
    #   Order.having('SUM(price) > 30').group('user_id')
393
    def having(opts, *rest)
J
Jon Leighton 已提交
394
      opts.blank? ? self : spawn.having!(opts, *rest)
395 396
    end

397
    # Like #having, but modifies relation in place.
398
    def having!(opts, *rest)
399
      references!(PredicateBuilder.references(opts)) if Hash === opts
400

401 402
      self.having_values += build_where(opts, rest)
      self
403 404
    end

405
    # Specifies a limit for the number of records to retrieve.
406 407 408 409
    #
    #   User.limit(10) # generated SQL has 'LIMIT 10'
    #
    #   User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
410
    def limit(value)
J
Jon Leighton 已提交
411
      spawn.limit!(value)
412 413
    end

414
    # Like #limit, but modifies relation in place.
415
    def limit!(value)
416 417
      self.limit_value = value
      self
418 419
    end

420 421 422 423
    # Specifies the number of rows to skip before returning rows.
    #
    #   User.offset(10) # generated SQL has "OFFSET 10"
    #
424
    # Should be used with order.
425
    #
426
    #   User.offset(10).order("name ASC")
427
    def offset(value)
J
Jon Leighton 已提交
428
      spawn.offset!(value)
429 430
    end

431
    # Like #offset, but modifies relation in place.
432
    def offset!(value)
433 434
      self.offset_value = value
      self
435 436
    end

437
    # Specifies locking settings (default to +true+). For more information
438
    # on locking, please see +ActiveRecord::Locking+.
439
    def lock(locks = true)
J
Jon Leighton 已提交
440
      spawn.lock!(locks)
441
    end
442

443
    # Like #lock, but modifies relation in place.
444
    def lock!(locks = true)
445
      case locks
446
      when String, TrueClass, NilClass
447
        self.lock_value = locks || true
448
      else
449
        self.lock_value = false
450
      end
451

452
      self
453 454
    end

455
    # Returns a chainable relation with zero records, specifically an
V
Vijay Dev 已提交
456
    # instance of the <tt>ActiveRecord::NullRelation</tt> class.
457
    #
V
Vijay Dev 已提交
458 459 460
    # The returned <tt>ActiveRecord::NullRelation</tt> inherits from Relation and implements the
    # Null Object pattern. It is an object with defined null behavior and always returns an empty
    # array of records without quering the database.
461 462 463 464
    #
    # Any subsequent condition chained to the returned relation will continue
    # generating an empty relation and will not fire any query to the database.
    #
465 466
    # Used in cases where a method or scope could return zero records but the
    # result needs to be chainable.
467 468 469 470
    #
    # For example:
    #
    #   @posts = current_user.visible_posts.where(:name => params[:name])
471
    #   # => the visible_posts method is expected to return a chainable Relation
472 473 474
    #
    #   def visible_posts
    #     case role
475
    #     when 'Country Manager'
476
    #       Post.where(:country => country)
477
    #     when 'Reviewer'
478
    #       Post.published
479
    #     when 'Bad User'
480 481 482 483 484
    #       Post.none # => returning [] instead breaks the previous code
    #     end
    #   end
    #
    def none
485
      extending(NullRelation)
486 487
    end

488 489 490 491 492 493
    # Sets readonly attributes for the returned relation. If value is
    # true (default), attempting to update a record will result in an error.
    #
    #   users = User.readonly
    #   users.first.save
    #   => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
494
    def readonly(value = true)
J
Jon Leighton 已提交
495
      spawn.readonly!(value)
496 497
    end

498
    # Like #readonly, but modifies relation in place.
499
    def readonly!(value = true)
500 501
      self.readonly_value = value
      self
502 503
    end

504 505 506 507 508 509 510 511 512 513 514 515 516
    # Sets attributes to be used when creating new records from a
    # relation object.
    #
    #   users = User.where(name: 'Oscar')
    #   users.new.name # => 'Oscar'
    #
    #   users = users.create_with(name: 'DHH')
    #   users.new.name # => 'DHH'
    #
    # You can pass +nil+ to +create_with+ to reset attributes:
    #
    #   users = users.create_with(nil)
    #   users.new.name # => 'Oscar'
517
    def create_with(value)
J
Jon Leighton 已提交
518
      spawn.create_with!(value)
519 520
    end

521 522 523
    # Like #create_with but modifies the relation in place. Raises
    # +ImmutableRelation+ if the relation has already been loaded.
    #
524
    #   users = User.all.create_with!(name: 'Oscar')
V
Vijay Dev 已提交
525
    #   users.new.name # => 'Oscar'
526
    def create_with!(value)
527 528
      self.create_with_value = value ? create_with_value.merge(value) : {}
      self
529 530
    end

531 532 533 534 535 536 537
    # Specifies table from which the records will be fetched. For example:
    #
    #   Topic.select('title').from('posts')
    #   #=> SELECT title FROM posts
    #
    # Can accept other relation objects. For example:
    #
538
    #   Topic.select('title').from(Topic.approved)
539 540
    #   # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
    #
541
    #   Topic.select('a.title').from(Topic.approved, :a)
542 543 544 545
    #   # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
    #
    def from(value, subquery_name = nil)
      spawn.from!(value, subquery_name)
546 547
    end

548
    # Like #from, but modifies relation in place.
549
    def from!(value, subquery_name = nil)
550
      self.from_value = [value, subquery_name]
551
      self
552 553
    end

554 555 556 557 558 559 560 561 562 563 564
    # Specifies whether the records should be unique or not. For example:
    #
    #   User.select(:name)
    #   # => Might return two records with the same name
    #
    #   User.select(:name).uniq
    #   # => Returns 1 record per unique name
    #
    #   User.select(:name).uniq.uniq(false)
    #   # => You can also remove the uniqueness
    def uniq(value = true)
J
Jon Leighton 已提交
565
      spawn.uniq!(value)
566 567
    end

568
    # Like #uniq, but modifies relation in place.
569
    def uniq!(value = true)
570 571
      self.uniq_value = value
      self
572 573
    end

574
    # Used to extend a scope with additional methods, either through
575 576
    # a module or through a block provided.
    #
577 578 579 580 581 582 583 584 585 586
    # The object returned is a relation, which can be further extended.
    #
    # === Using a module
    #
    #   module Pagination
    #     def page(number)
    #       # pagination code goes here
    #     end
    #   end
    #
587
    #   scope = Model.all.extending(Pagination)
588 589
    #   scope.page(params[:page])
    #
V
Vijay Dev 已提交
590
    # You can also pass a list of modules:
591
    #
592
    #   scope = Model.all.extending(Pagination, SomethingElse)
593 594 595
    #
    # === Using a block
    #
596
    #   scope = Model.all.extending do
597
    #     def page(number)
598
    #       # pagination code goes here
599 600 601 602 603 604
    #     end
    #   end
    #   scope.page(params[:page])
    #
    # You can also use a block and a module list:
    #
605
    #   scope = Model.all.extending(Pagination) do
606
    #     def per_page(number)
607
    #       # pagination code goes here
608 609
    #     end
    #   end
610 611
    def extending(*modules, &block)
      if modules.any? || block
J
Jon Leighton 已提交
612
        spawn.extending!(*modules, &block)
613 614 615 616
      else
        self
      end
    end
617

618
    # Like #extending, but modifies relation in place.
619
    def extending!(*modules, &block)
620
      modules << Module.new(&block) if block_given?
621

J
Jon Leighton 已提交
622
      self.extending_values += modules.flatten
623
      extend(*extending_values) if extending_values.any?
624

625
      self
626 627
    end

628 629 630
    # Reverse the existing order clause on the relation.
    #
    #   User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
631
    def reverse_order
J
Jon Leighton 已提交
632
      spawn.reverse_order!
633 634
    end

635
    # Like #reverse_order, but modifies relation in place.
636
    def reverse_order!
637 638
      self.reverse_order_value = !reverse_order_value
      self
639 640
    end

641
    # Returns the Arel object associated with the relation.
642
    def arel
643
      @arel ||= with_default_scope.build_arel
644 645
    end

646
    # Like #arel, but ignores the default scope of the model.
647
    def build_arel
648
      arel = Arel::SelectManager.new(table.engine, table)
649

650
      build_joins(arel, joins_values) unless joins_values.empty?
651

652
      collapse_wheres(arel, (where_values - ['']).uniq)
653

654
      arel.having(*having_values.uniq.reject{|h| h.blank?}) unless having_values.empty?
655

656 657
      arel.take(connection.sanitize_limit(limit_value)) if limit_value
      arel.skip(offset_value.to_i) if offset_value
A
Aaron Patterson 已提交
658

659
      arel.group(*group_values.uniq.reject{|g| g.blank?}) unless group_values.empty?
660

661 662
      order = order_values
      order = reverse_sql_order(order) if reverse_order_value
663
      arel.order(*order.uniq.reject{|o| o.blank?}) unless order.empty?
664

665
      build_select(arel, select_values.uniq)
666

667
      arel.distinct(uniq_value)
668
      arel.from(build_from) if from_value
669
      arel.lock(lock_value) if lock_value
670 671

      arel
672 673
    end

674 675
    private

676
    def custom_join_ast(table, joins)
677 678
      joins = joins.reject { |join| join.blank? }

679
      return [] if joins.empty?
680 681 682

      @implicit_readonly = true

683
      joins.map do |join|
684 685 686 687 688 689
        case join
        when Array
          join = Arel.sql(join.join(' ')) if array_of_strings?(join)
        when String
          join = Arel.sql(join)
        end
690
        table.create_string_join(join)
691 692 693
      end
    end

694 695 696
    def collapse_wheres(arel, wheres)
      equalities = wheres.grep(Arel::Nodes::Equality)

A
Aaron Patterson 已提交
697
      arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
698 699 700

      (wheres - equalities).each do |where|
        where = Arel.sql(where) if String === where
701
        arel.where(Arel::Nodes::Grouping.new(where))
702 703 704
      end
    end

705
    def build_where(opts, other = [])
A
Aaron Patterson 已提交
706 707
      case opts
      when String, Array
708
        [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
A
Aaron Patterson 已提交
709
      when Hash
710
        attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
711
        PredicateBuilder.build_from_hash(klass, attributes, table)
712
      else
713
        [opts]
714 715 716
      end
    end

717 718 719 720 721 722 723 724 725 726 727
    def build_from
      opts, name = from_value
      case opts
      when Relation
        name ||= 'subquery'
        opts.arel.as(name.to_s)
      else
        opts
      end
    end

728
    def build_joins(manager, joins)
A
Aaron Patterson 已提交
729 730 731 732 733 734
      buckets = joins.group_by do |join|
        case join
        when String
          'string_join'
        when Hash, Symbol, Array
          'association_join'
735
        when ActiveRecord::Associations::JoinDependency::JoinAssociation
A
Aaron Patterson 已提交
736
          'stashed_join'
737 738
        when Arel::Nodes::Join
          'join_node'
A
Aaron Patterson 已提交
739 740 741
        else
          raise 'unknown class: %s' % join.class.name
        end
742 743
      end

A
Aaron Patterson 已提交
744 745
      association_joins         = buckets['association_join'] || []
      stashed_association_joins = buckets['stashed_join'] || []
746
      join_nodes                = (buckets['join_node'] || []).uniq
A
Aaron Patterson 已提交
747 748 749
      string_joins              = (buckets['string_join'] || []).map { |x|
        x.strip
      }.uniq
750

751
      join_list = join_nodes + custom_join_ast(manager, string_joins)
752

753
      join_dependency = ActiveRecord::Associations::JoinDependency.new(
754 755 756 757
        @klass,
        association_joins,
        join_list
      )
758 759 760 761 762

      join_dependency.graft(*stashed_association_joins)

      @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?

A
Aaron Patterson 已提交
763
      # FIXME: refactor this to build an AST
764
      join_dependency.join_associations.each do |association|
765
        association.join_to(manager)
766 767
      end

768
      manager.join_sources.concat join_list
769 770

      manager
771 772
    end

773
    def build_select(arel, selects)
774
      unless selects.empty?
775
        @implicit_readonly = false
776
        arel.project(*selects)
777
      else
778
        arel.project(@klass.arel_table[Arel.star])
779 780 781
      end
    end

782
    def reverse_sql_order(order_query)
B
Brian Mathiyakom 已提交
783 784
      order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?

785
      order_query.map do |o|
786
        case o
787
        when Arel::Nodes::Ordering
788 789
          o.reverse
        when String, Symbol
790 791 792 793
          o.to_s.split(',').collect do |s|
            s.strip!
            s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
          end
794 795 796
        else
          o
        end
797
      end.flatten
798 799
    end

P
Pratik Naik 已提交
800 801 802 803
    def array_of_strings?(o)
      o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
    end

804 805
  end
end