query_methods.rb 7.2 KB
Newer Older
1
require 'active_support/core_ext/array/wrap'
2 3
require 'active_support/core_ext/object/blank'

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

8
    attr_accessor :includes_values, :eager_load_values, :preload_values,
A
Aaron Patterson 已提交
9 10
                  :select_values, :group_values, :order_values, :joins_values,
                  :where_values, :having_values, :bind_values,
11
                  :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, :from_value
12

13
    def includes(*args)
14 15
      args.reject! {|a| a.blank? }

16
      return self if args.empty?
A
Aaron Patterson 已提交
17

18
      relation = clone
A
Aaron Patterson 已提交
19
      relation.includes_values = (relation.includes_values + args).flatten.uniq
20
      relation
21
    end
22

23
    def eager_load(*args)
24 25
      return self if args.blank?

26
      relation = clone
27
      relation.eager_load_values += args
28
      relation
29 30 31
    end

    def preload(*args)
32 33
      return self if args.blank?

34
      relation = clone
35
      relation.preload_values += args
36
      relation
37
    end
38

39
    def select(value = Proc.new)
40
      if block_given?
41
        to_a.select {|*block_args| value.call(*block_args) }
42
      else
43
        relation = clone
44
        relation.select_values += Array.wrap(value)
45
        relation
S
Santiago Pastorino 已提交
46
      end
47
    end
S
Santiago Pastorino 已提交
48

49
    def group(*args)
50 51
      return self if args.blank?

52
      relation = clone
53
      relation.group_values += args.flatten
54
      relation
55
    end
56

57
    def order(*args)
58 59
      return self if args.blank?

60
      relation = clone
61
      relation.order_values += args.flatten
62
      relation
63
    end
64

65
    def joins(*args)
66 67
      return self if args.blank?

68 69
      relation = clone

A
Aaron Patterson 已提交
70
      args.flatten!
71
      relation.joins_values += args
72 73

      relation
P
Pratik Naik 已提交
74 75
    end

A
Aaron Patterson 已提交
76 77 78 79 80 81
    def bind(value)
      relation = clone
      relation.bind_values += [value]
      relation
    end

82
    def where(opts, *rest)
83 84
      return self if opts.blank?

85
      relation = clone
86
      relation.where_values += build_where(opts, rest)
87
      relation
88
    end
P
Pratik Naik 已提交
89

90
    def having(*args)
91 92
      return self if args.blank?

93
      relation = clone
94
      relation.having_values += build_where(*args)
95
      relation
96 97
    end

98
    def limit(value)
99 100 101
      relation = clone
      relation.limit_value = value
      relation
102 103
    end

104
    def offset(value)
105 106 107
      relation = clone
      relation.offset_value = value
      relation
108 109 110
    end

    def lock(locks = true)
111 112
      relation = clone

113
      case locks
114
      when String, TrueClass, NilClass
115
        relation.lock_value = locks || true
116
      else
117
        relation.lock_value = false
118
      end
119 120

      relation
121 122
    end

123
    def readonly(value = true)
124 125 126
      relation = clone
      relation.readonly_value = value
      relation
127 128
    end

129
    def create_with(value)
130 131 132
      relation = clone
      relation.create_with_value = value
      relation
133 134
    end

135
    def from(value)
136 137 138
      relation = clone
      relation.from_value = value
      relation
139 140
    end

141 142
    def extending(*modules)
      modules << Module.new(&Proc.new) if block_given?
143

144 145
      return self if modules.empty?

146
      relation = clone
147
      relation.send(:apply_modules, modules.flatten)
148
      relation
149 150
    end

151
    def reverse_order
N
Neeraj Singh 已提交
152
      order_clause = arel.order_clauses
153

N
Neeraj Singh 已提交
154
      order = order_clause.empty? ?
155
        "#{@klass.table_name}.#{@klass.primary_key} DESC" :
N
Neeraj Singh 已提交
156
        reverse_sql_order(order_clause).join(', ')
157

158
      except(:order).order(Arel.sql(order))
159 160
    end

161 162
    def arel
      @arel ||= build_arel
163 164
    end

165
    def build_arel
166
      arel = table.from table
167

A
Aaron Patterson 已提交
168
      build_joins(arel, @joins_values) unless @joins_values.empty?
169

A
Aaron Patterson 已提交
170
      collapse_wheres(arel, (@where_values - ['']).uniq)
171

A
Aaron Patterson 已提交
172
      arel.having(*@having_values.uniq.reject{|h| h.blank?}) unless @having_values.empty?
173

A
Aaron Patterson 已提交
174 175
      arel.take(@limit_value) if @limit_value
      arel.skip(@offset_value) if @offset_value
A
Aaron Patterson 已提交
176

A
Aaron Patterson 已提交
177
      arel.group(*@group_values.uniq.reject{|g| g.blank?}) unless @group_values.empty?
178

A
Aaron Patterson 已提交
179
      arel.order(*@order_values.uniq.reject{|o| o.blank?}) unless @order_values.empty?
180

A
Aaron Patterson 已提交
181
      build_select(arel, @select_values.uniq)
182

A
Aaron Patterson 已提交
183 184
      arel.from(@from_value) if @from_value
      arel.lock(@lock_value) if @lock_value
185 186

      arel
187 188
    end

189 190
    private

191
    def custom_join_ast(table, joins)
192 193 194 195 196 197
      joins = joins.reject { |join| join.blank? }

      return if joins.empty?

      @implicit_readonly = true

198 199 200 201 202 203 204 205 206 207
      joins.map! do |join|
        case join
        when Array
          join = Arel.sql(join.join(' ')) if array_of_strings?(join)
        when String
          join = Arel.sql(join)
        end
        join
      end

208 209 210 211 212
      head = table.create_string_join(table, joins.shift)

      joins.inject(head) do |ast, join|
        ast.right = table.create_string_join(ast.right, join)
      end
213 214

      head
215 216
    end

217 218 219 220
    def collapse_wheres(arel, wheres)
      equalities = wheres.grep(Arel::Nodes::Equality)

      groups = equalities.group_by do |equality|
221
        equality.left
222 223 224
      end

      groups.each do |_, eqls|
225 226
        test = eqls.inject(eqls.shift) do |memo, expr|
          memo.or(expr)
227
        end
228
        arel.where(test)
229 230 231 232
      end

      (wheres - equalities).each do |where|
        where = Arel.sql(where) if String === where
233
        arel.where(Arel::Nodes::Grouping.new(where))
234 235 236
      end
    end

237
    def build_where(opts, other = [])
A
Aaron Patterson 已提交
238 239
      case opts
      when String, Array
240
        [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
A
Aaron Patterson 已提交
241 242
      when Hash
        attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
243
        PredicateBuilder.build_from_hash(table.engine, attributes, table)
244
      else
245
        [opts]
246 247 248
      end
    end

249
    def build_joins(manager, joins)
250
      joins = joins.map {|j| j.respond_to?(:strip) ? j.strip : j}.uniq
251

252 253
      association_joins = joins.find_all do |join|
        [Hash, Array, Symbol].include?(join.class) && !array_of_strings?(join)
254 255
      end

256
      stashed_association_joins = joins.grep(ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation)
257

S
Santiago Pastorino 已提交
258
      non_association_joins = (joins - association_joins - stashed_association_joins)
259
      join_ast = custom_join_ast(manager.froms.first, non_association_joins)
260

261
      join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, join_ast)
262 263 264 265 266

      join_dependency.graft(*stashed_association_joins)

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

A
Aaron Patterson 已提交
267
      # FIXME: refactor this to build an AST
268
      join_dependency.join_associations.each do |association|
269
        manager = association.join_to(manager)
270 271
      end

272 273 274 275 276
      return manager unless join_ast

      join_ast.left = manager.froms.first
      manager.from join_ast
      manager
277 278
    end

279
    def build_select(arel, selects)
280
      unless selects.empty?
281
        @implicit_readonly = false
282
        arel.project(*selects)
283
      else
284
        arel.project(Arel.sql(@klass.quoted_table_name + '.*'))
285 286 287
      end
    end

P
Pratik Naik 已提交
288
    def apply_modules(modules)
289
      unless modules.empty?
290
        @extensions += modules
291
        modules.each {|extension| extend(extension) }
N
Neeraj Singh 已提交
292
      end
P
Pratik Naik 已提交
293 294
    end

295
    def reverse_sql_order(order_query)
296 297 298
      order_query.join(', ').split(',').collect do |s|
        s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
      end
299 300
    end

P
Pratik Naik 已提交
301 302 303 304
    def array_of_strings?(o)
      o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
    end

305 306
  end
end