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)
261
      args.compact.blank? ? self : spawn.joins!(*args.flatten)
262
    end
263

264
    # Like #joins, but modifies relation in place.
265
    def joins!(*args)
266 267
      self.joins_values += args
      self
P
Pratik Naik 已提交
268 269
    end

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

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

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

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

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

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

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

412 413
      self.having_values += build_where(opts, rest)
      self
414 415
    end

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

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

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

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

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

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

463
      self
464 465
    end

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

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

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

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

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

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

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

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

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

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

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

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

636
      self
637 638
    end

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

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

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

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

661
      build_joins(arel, joins_values) unless joins_values.empty?
662

663
      collapse_wheres(arel, (where_values - ['']).uniq)
664

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

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

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

672
      build_order(arel)
673

674
      build_select(arel, select_values.uniq)
675

676
      arel.distinct(uniq_value)
677
      arel.from(build_from) if from_value
678
      arel.lock(lock_value) if lock_value
679 680

      arel
681 682
    end

683 684
    private

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

688
      return [] if joins.empty?
689 690 691

      @implicit_readonly = true

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

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

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

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

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

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

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

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

760
      join_list = join_nodes + custom_join_ast(manager, string_joins)
761

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

      join_dependency.graft(*stashed_association_joins)

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

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

777
      manager.join_sources.concat join_list
778 779

      manager
780 781
    end

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

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

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

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

819 820 821
    def build_order(arel)
      orders = order_values
      orders = reverse_sql_order(orders) if reverse_order_value
822

823 824 825 826 827 828
      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) }
829
        else
830 831 832
          order
        end
      end.flatten
833

834 835
      arel.order(*orders) unless orders.empty?
    end
836

837 838 839 840 841 842 843
    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 已提交
844

845 846
  end
end