query_methods.rb 26.7 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
    #
206 207
    #   User.order(:name)
    #   => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
208
    #
209 210
    #   User.order(email: :desc)
    #   => SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
211
    #
212 213
    #   User.order(:name, email: :desc)
    #   => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
214
    def order(*args)
J
Jon Leighton 已提交
215
      args.blank? ? self : spawn.order!(*args)
216
    end
217

218
    # Like #order, but modifies relation in place.
219
    def order!(*args)
220
      args.flatten!
221

222
      validate_order_args args
223

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

228
      self.order_values = args + self.order_values
229
      self
230
    end
231

232 233 234 235 236 237 238 239
    # 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')
    #
240
    # generates a query with 'ORDER BY name ASC, id ASC'.
S
Sebastian Martinez 已提交
241
    def reorder(*args)
J
Jon Leighton 已提交
242
      args.blank? ? self : spawn.reorder!(*args)
243
    end
244

245
    # Like #reorder, but modifies relation in place.
246
    def reorder!(*args)
247
      args.flatten!
248

249
      validate_order_args args
250

251
      self.reordering_value = true
252
      self.order_values = args
253
      self
S
Sebastian Martinez 已提交
254 255
    end

256 257 258 259
    # Performs a joins on +args+:
    #
    #   User.joins(:posts)
    #   => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
260
    def joins(*args)
J
Jon Leighton 已提交
261
      args.compact.blank? ? self : spawn.joins!(*args)
262
    end
263

264
    # Like #joins, but modifies relation in place.
265
    def joins!(*args)
A
Aaron Patterson 已提交
266
      args.flatten!
267

268 269
      self.joins_values += args
      self
P
Pratik Naik 已提交
270 271
    end

A
Aaron Patterson 已提交
272
    def bind(value)
J
Jon Leighton 已提交
273
      spawn.bind!(value)
274 275
    end

276
    def bind!(value)
277 278
      self.bind_values += [value]
      self
A
Aaron Patterson 已提交
279 280
    end

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 343 344 345 346 347 348 349 350 351 352 353 354 355
    # 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')
    #
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    # 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)
    #
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    # === 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.
389
    def where(opts, *rest)
J
Jon Leighton 已提交
390
      opts.blank? ? self : spawn.where!(opts, *rest)
391 392
    end

393 394 395
    # #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)
396
      references!(PredicateBuilder.references(opts)) if Hash === opts
397

398 399
      self.where_values += build_where(opts, rest)
      self
400
    end
P
Pratik Naik 已提交
401

402 403 404 405
    # 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')
406
    def having(opts, *rest)
J
Jon Leighton 已提交
407
      opts.blank? ? self : spawn.having!(opts, *rest)
408 409
    end

410
    # Like #having, but modifies relation in place.
411
    def having!(opts, *rest)
412
      references!(PredicateBuilder.references(opts)) if Hash === opts
413

414 415
      self.having_values += build_where(opts, rest)
      self
416 417
    end

418
    # Specifies a limit for the number of records to retrieve.
419 420 421 422
    #
    #   User.limit(10) # generated SQL has 'LIMIT 10'
    #
    #   User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
423
    def limit(value)
J
Jon Leighton 已提交
424
      spawn.limit!(value)
425 426
    end

427
    # Like #limit, but modifies relation in place.
428
    def limit!(value)
429 430
      self.limit_value = value
      self
431 432
    end

433 434 435 436
    # Specifies the number of rows to skip before returning rows.
    #
    #   User.offset(10) # generated SQL has "OFFSET 10"
    #
437
    # Should be used with order.
438
    #
439
    #   User.offset(10).order("name ASC")
440
    def offset(value)
J
Jon Leighton 已提交
441
      spawn.offset!(value)
442 443
    end

444
    # Like #offset, but modifies relation in place.
445
    def offset!(value)
446 447
      self.offset_value = value
      self
448 449
    end

450
    # Specifies locking settings (default to +true+). For more information
451
    # on locking, please see +ActiveRecord::Locking+.
452
    def lock(locks = true)
J
Jon Leighton 已提交
453
      spawn.lock!(locks)
454
    end
455

456
    # Like #lock, but modifies relation in place.
457
    def lock!(locks = true)
458
      case locks
459
      when String, TrueClass, NilClass
460
        self.lock_value = locks || true
461
      else
462
        self.lock_value = false
463
      end
464

465
      self
466 467
    end

468
    # Returns a chainable relation with zero records, specifically an
V
Vijay Dev 已提交
469
    # instance of the <tt>ActiveRecord::NullRelation</tt> class.
470
    #
V
Vijay Dev 已提交
471 472 473
    # 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.
474 475 476 477
    #
    # Any subsequent condition chained to the returned relation will continue
    # generating an empty relation and will not fire any query to the database.
    #
478 479
    # Used in cases where a method or scope could return zero records but the
    # result needs to be chainable.
480 481 482 483
    #
    # For example:
    #
    #   @posts = current_user.visible_posts.where(:name => params[:name])
484
    #   # => the visible_posts method is expected to return a chainable Relation
485 486 487
    #
    #   def visible_posts
    #     case role
488
    #     when 'Country Manager'
489
    #       Post.where(:country => country)
490
    #     when 'Reviewer'
491
    #       Post.published
492
    #     when 'Bad User'
493 494 495 496 497
    #       Post.none # => returning [] instead breaks the previous code
    #     end
    #   end
    #
    def none
498
      extending(NullRelation)
499 500
    end

501 502 503 504 505 506
    # 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
507
    def readonly(value = true)
J
Jon Leighton 已提交
508
      spawn.readonly!(value)
509 510
    end

511
    # Like #readonly, but modifies relation in place.
512
    def readonly!(value = true)
513 514
      self.readonly_value = value
      self
515 516
    end

517 518 519 520 521 522 523 524 525 526 527 528 529
    # 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'
530
    def create_with(value)
J
Jon Leighton 已提交
531
      spawn.create_with!(value)
532 533
    end

534 535 536
    # Like #create_with but modifies the relation in place. Raises
    # +ImmutableRelation+ if the relation has already been loaded.
    #
537
    #   users = User.all.create_with!(name: 'Oscar')
V
Vijay Dev 已提交
538
    #   users.new.name # => 'Oscar'
539
    def create_with!(value)
540 541
      self.create_with_value = value ? create_with_value.merge(value) : {}
      self
542 543
    end

544 545 546 547 548 549 550
    # 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:
    #
551
    #   Topic.select('title').from(Topic.approved)
552 553
    #   # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
    #
554
    #   Topic.select('a.title').from(Topic.approved, :a)
555 556 557 558
    #   # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
    #
    def from(value, subquery_name = nil)
      spawn.from!(value, subquery_name)
559 560
    end

561
    # Like #from, but modifies relation in place.
562
    def from!(value, subquery_name = nil)
563
      self.from_value = [value, subquery_name]
564
      self
565 566
    end

567 568 569 570 571 572 573 574 575 576 577
    # 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 已提交
578
      spawn.uniq!(value)
579 580
    end

581
    # Like #uniq, but modifies relation in place.
582
    def uniq!(value = true)
583 584
      self.uniq_value = value
      self
585 586
    end

587
    # Used to extend a scope with additional methods, either through
588 589
    # a module or through a block provided.
    #
590 591 592 593 594 595 596 597 598 599
    # 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
    #
600
    #   scope = Model.all.extending(Pagination)
601 602
    #   scope.page(params[:page])
    #
V
Vijay Dev 已提交
603
    # You can also pass a list of modules:
604
    #
605
    #   scope = Model.all.extending(Pagination, SomethingElse)
606 607 608
    #
    # === Using a block
    #
609
    #   scope = Model.all.extending do
610
    #     def page(number)
611
    #       # pagination code goes here
612 613 614 615 616 617
    #     end
    #   end
    #   scope.page(params[:page])
    #
    # You can also use a block and a module list:
    #
618
    #   scope = Model.all.extending(Pagination) do
619
    #     def per_page(number)
620
    #       # pagination code goes here
621 622
    #     end
    #   end
623 624
    def extending(*modules, &block)
      if modules.any? || block
J
Jon Leighton 已提交
625
        spawn.extending!(*modules, &block)
626 627 628 629
      else
        self
      end
    end
630

631
    # Like #extending, but modifies relation in place.
632
    def extending!(*modules, &block)
633
      modules << Module.new(&block) if block_given?
634

J
Jon Leighton 已提交
635
      self.extending_values += modules.flatten
636
      extend(*extending_values) if extending_values.any?
637

638
      self
639 640
    end

641 642 643
    # Reverse the existing order clause on the relation.
    #
    #   User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
644
    def reverse_order
J
Jon Leighton 已提交
645
      spawn.reverse_order!
646 647
    end

648
    # Like #reverse_order, but modifies relation in place.
649
    def reverse_order!
650 651
      self.reverse_order_value = !reverse_order_value
      self
652 653
    end

654
    # Returns the Arel object associated with the relation.
655
    def arel
656
      @arel ||= with_default_scope.build_arel
657 658
    end

659
    # Like #arel, but ignores the default scope of the model.
660
    def build_arel
661
      arel = Arel::SelectManager.new(table.engine, table)
662

663
      build_joins(arel, joins_values) unless joins_values.empty?
664

665
      collapse_wheres(arel, (where_values - ['']).uniq)
666

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

669 670
      arel.take(connection.sanitize_limit(limit_value)) if limit_value
      arel.skip(offset_value.to_i) if offset_value
A
Aaron Patterson 已提交
671

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

674
      build_order(arel)
675

676
      build_select(arel, select_values.uniq)
677

678
      arel.distinct(uniq_value)
679
      arel.from(build_from) if from_value
680
      arel.lock(lock_value) if lock_value
681 682

      arel
683 684
    end

685 686
    private

687
    def custom_join_ast(table, joins)
688 689
      joins = joins.reject { |join| join.blank? }

690
      return [] if joins.empty?
691 692 693

      @implicit_readonly = true

694
      joins.map do |join|
695 696 697 698 699 700
        case join
        when Array
          join = Arel.sql(join.join(' ')) if array_of_strings?(join)
        when String
          join = Arel.sql(join)
        end
701
        table.create_string_join(join)
702 703 704
      end
    end

705 706 707
    def collapse_wheres(arel, wheres)
      equalities = wheres.grep(Arel::Nodes::Equality)

A
Aaron Patterson 已提交
708
      arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
709 710 711

      (wheres - equalities).each do |where|
        where = Arel.sql(where) if String === where
712
        arel.where(Arel::Nodes::Grouping.new(where))
713 714 715
      end
    end

716
    def build_where(opts, other = [])
A
Aaron Patterson 已提交
717 718
      case opts
      when String, Array
719
        [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
A
Aaron Patterson 已提交
720
      when Hash
721
        attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
722
        PredicateBuilder.build_from_hash(klass, attributes, table)
723
      else
724
        [opts]
725 726 727
      end
    end

728 729 730 731 732 733 734 735 736 737 738
    def build_from
      opts, name = from_value
      case opts
      when Relation
        name ||= 'subquery'
        opts.arel.as(name.to_s)
      else
        opts
      end
    end

739
    def build_joins(manager, joins)
A
Aaron Patterson 已提交
740 741 742 743 744 745
      buckets = joins.group_by do |join|
        case join
        when String
          'string_join'
        when Hash, Symbol, Array
          'association_join'
746
        when ActiveRecord::Associations::JoinDependency::JoinAssociation
A
Aaron Patterson 已提交
747
          'stashed_join'
748 749
        when Arel::Nodes::Join
          'join_node'
A
Aaron Patterson 已提交
750 751 752
        else
          raise 'unknown class: %s' % join.class.name
        end
753 754
      end

A
Aaron Patterson 已提交
755 756
      association_joins         = buckets['association_join'] || []
      stashed_association_joins = buckets['stashed_join'] || []
757
      join_nodes                = (buckets['join_node'] || []).uniq
A
Aaron Patterson 已提交
758 759 760
      string_joins              = (buckets['string_join'] || []).map { |x|
        x.strip
      }.uniq
761

762
      join_list = join_nodes + custom_join_ast(manager, string_joins)
763

764
      join_dependency = ActiveRecord::Associations::JoinDependency.new(
765 766 767 768
        @klass,
        association_joins,
        join_list
      )
769 770 771 772 773

      join_dependency.graft(*stashed_association_joins)

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

A
Aaron Patterson 已提交
774
      # FIXME: refactor this to build an AST
775
      join_dependency.join_associations.each do |association|
776
        association.join_to(manager)
777 778
      end

779
      manager.join_sources.concat join_list
780 781

      manager
782 783
    end

784
    def build_select(arel, selects)
785
      unless selects.empty?
786
        @implicit_readonly = false
787
        arel.project(*selects)
788
      else
789
        arel.project(@klass.arel_table[Arel.star])
790 791 792
      end
    end

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

796
      order_query.map do |o|
797
        case o
798
        when Arel::Nodes::Ordering
799
          o.reverse
800
        when String
801 802 803 804
          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
805
        when Symbol
806
          { o => :desc }
807
        when Hash
808
          o.each_with_object({}) do |(field, dir), memo|
809 810
            memo[field] = (dir == :asc ? :desc : :asc )
          end
811 812 813
        else
          o
        end
814
      end.flatten
815 816
    end

P
Pratik Naik 已提交
817 818 819
    def array_of_strings?(o)
      o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
    end
820

821 822 823
    def build_order(arel)
      orders = order_values
      orders = reverse_sql_order(orders) if reverse_order_value
824

825 826 827 828 829 830
      orders = orders.uniq.reject(&:blank?).map do |order|
        case order
        when Symbol
          table[order].asc
        when Hash
          order.map { |field, dir| table[field].send(dir) }
831
        else
832 833 834
          order
        end
      end.flatten
835

836 837
      arel.order(*orders) unless orders.empty?
    end
838

839 840 841 842 843 844 845
    def validate_order_args(args)
      args.select { |a| Hash === a  }.each do |h|
        unless (h.values - [:asc, :desc]).empty?
          raise ArgumentError, 'Direction should be :asc or :desc'
        end
      end
    end
P
Pratik Naik 已提交
846

847 848
  end
end