query_methods.rb 8.0 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 9 10
    attr_accessor :includes_values, :eager_load_values, :preload_values,
                  :select_values, :group_values, :order_values, :joins_values, :where_values, :having_values,
                  :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, :from_value
11

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

      relation = clone
      relation.includes_values = (relation.includes_values + args).flatten.uniq if args.present?
      relation
18
    end
19

20
    def eager_load(*args)
21 22 23
      relation = clone
      relation.eager_load_values += args if args.present?
      relation
24 25 26
    end

    def preload(*args)
27 28 29
      relation = clone
      relation.preload_values += args if args.present?
      relation
30
    end
31

32 33
    def select(*args)
      if block_given?
P
Pratik Naik 已提交
34
        to_a.select {|*block_args| yield(*block_args) }
35
      else
36 37 38
        relation = clone
        relation.select_values += args if args.present?
        relation
S
Santiago Pastorino 已提交
39
      end
40
    end
S
Santiago Pastorino 已提交
41

42
    def group(*args)
43 44 45
      relation = clone
      relation.group_values += args.flatten if args.present?
      relation
46
    end
47

48
    def order(*args)
49 50 51
      relation = clone
      relation.order_values += args.flatten if args.present?
      relation
52
    end
53

54
    def reorder(*args)
55 56 57
      relation = clone
      relation.order_values = args if args.present?
      relation
58 59
    end

60
    def joins(*args)
61 62
      relation = clone

63 64
      if args.present?
        args.flatten!
65
        relation.joins_values += args if args.present?
66
      end
67 68

      relation
P
Pratik Naik 已提交
69 70
    end

71
    def where(opts, *rest)
72 73
      relation = clone

74
      if opts.present? && value = build_where(opts, rest)
75
        relation.where_values += Array.wrap(value)
76
      end
77 78

      relation
79
    end
P
Pratik Naik 已提交
80

81
    def having(*args)
82 83 84 85
      relation = clone

      if args.present? && value = build_where(*args)
        relation.having_values += Array.wrap(value)
86
      end
87 88

      relation
89 90
    end

91
    def limit(value)
92 93 94
      relation = clone
      relation.limit_value = value
      relation
95 96
    end

97
    def offset(value)
98 99 100
      relation = clone
      relation.offset_value = value
      relation
101 102 103
    end

    def lock(locks = true)
104 105
      relation = clone

106
      case locks
107
      when String, TrueClass, NilClass
108
        relation.lock_value = locks || true
109
      else
110
        relation.lock_value = false
111
      end
112 113

      relation
114 115
    end

116
    def readonly(value = true)
117 118 119
      relation = clone
      relation.readonly_value = value
      relation
120 121
    end

122
    def create_with(value)
123 124 125
      relation = clone
      relation.create_with_value = value
      relation
126 127
    end

128
    def from(value)
129 130 131
      relation = clone
      relation.from_value = value
      relation
132 133
    end

134 135
    def extending(*modules, &block)
      modules << Module.new(&block) if block_given?
136 137 138 139

      relation = clone
      relation.send(:apply_modules, *modules)
      relation
140 141
    end

142
    def reverse_order
143
      order_clause = arel.order_clauses.join(', ')
144 145
      relation = except(:order)

146 147 148 149
      order = order_clause.blank? ?
        "#{@klass.table_name}.#{@klass.primary_key} DESC" :
        reverse_sql_order(order_clause)

150
      relation.order(Arel::SqlLiteral.new(order))
151 152
    end

153 154
    def arel
      @arel ||= build_arel
155 156
    end

157 158
    def custom_join_sql(*joins)
      arel = table
159

160 161 162 163 164 165 166 167 168
      joins.each do |join|
        next if join.blank?

        @implicit_readonly = true

        case join
        when Hash, Array, Symbol
          if array_of_strings?(join)
            join_string = join.join(' ')
169
            arel = arel.join(Arel::SqlLiteral.new(join_string))
170
          end
171 172
        when String
          arel = arel.join(Arel::SqlLiteral.new(join))
173 174 175 176
        else
          arel = arel.join(join)
        end
      end
177

178 179 180
      arel.joins(arel)
    end

181 182
    def build_arel
      arel = table
183

184
      arel = build_joins(arel, @joins_values) unless @joins_values.empty?
185

186
      (@where_values - ['']).uniq.each do |where|
187
        case where
188 189
        when Arel::SqlLiteral
          arel = arel.where(where)
190
        else
191 192
          sql = where.is_a?(String) ? where : where.to_sql
          arel = arel.where(Arel::SqlLiteral.new("(#{sql})"))
193
        end
194 195
      end

196
      arel = arel.having(*@having_values.uniq.select{|h| h.present?}) unless @having_values.empty?
197

198
      arel = arel.take(@limit_value) if @limit_value
199
      arel = arel.skip(@offset_value) if @offset_value
200

201
      arel = arel.group(*@group_values.uniq.select{|g| g.present?}) unless @group_values.empty?
202

203
      arel = arel.order(*@order_values.uniq.select{|o| o.present?}) unless @order_values.empty?
204

205
      arel = build_select(arel, @select_values.uniq)
206

207
      arel = arel.from(@from_value) if @from_value
208
      arel = arel.lock(@lock_value) if @lock_value
209 210

      arel
211 212
    end

213
    def build_where(opts, other = [])
A
Aaron Patterson 已提交
214 215
      case opts
      when String, Array
216
        @klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))
A
Aaron Patterson 已提交
217 218
      when Hash
        attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
219
        PredicateBuilder.new(table.engine).build_from_hash(attributes, table)
220
      else
A
Aaron Patterson 已提交
221
        opts
222 223 224 225 226
      end
    end

    private

227 228 229 230 231 232 233 234 235 236
    def build_joins(relation, joins)
      joined_associations = []
      association_joins = []

      joins = @joins_values.map {|j| j.respond_to?(:strip) ? j.strip : j}.uniq

      joins.each do |join|
        association_joins << join if [Hash, Array, Symbol].include?(join.class) && !array_of_strings?(join)
      end

237
      stashed_association_joins = joins.grep(ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation)
238

S
Santiago Pastorino 已提交
239
      non_association_joins = (joins - association_joins - stashed_association_joins)
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
      custom_joins = custom_join_sql(*non_association_joins)

      join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, custom_joins)

      join_dependency.graft(*stashed_association_joins)

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

      to_join = []

      join_dependency.join_associations.each do |association|
        if (association_relation = association.relation).is_a?(Array)
          to_join << [association_relation.first, association.join_class, association.association_join.first]
          to_join << [association_relation.last, association.join_class, association.association_join.last]
        else
          to_join << [association_relation, association.join_class, association.association_join]
        end
      end

      to_join.each do |tj|
        unless joined_associations.detect {|ja| ja[0] == tj[0] && ja[1] == tj[1] && ja[2] == tj[2] }
          joined_associations << tj
          relation = relation.join(tj[0], tj[1]).on(*tj[2])
        end
      end

      relation.join(custom_joins)
    end

269
    def build_select(arel, selects)
270
      unless selects.empty?
271
        @implicit_readonly = false
272 273
        # TODO: fix this ugly hack, we should refactor the callers to get an ARel compatible array.
        # Before this change we were passing to ARel the last element only, and ARel is capable of handling an array
P
Pratik Naik 已提交
274
        if selects.all? {|s| s.is_a?(String) || !s.is_a?(Arel::Expression) } && !(selects.last =~ /^COUNT\(/)
275 276 277
          arel.project(*selects)
        else
          arel.project(selects.last)
278 279
        end
      else
280
        arel.project(Arel::SqlLiteral.new(@klass.quoted_table_name + '.*'))
281 282 283
      end
    end

P
Pratik Naik 已提交
284 285 286 287 288 289
    def apply_modules(modules)
      values = Array.wrap(modules)
      @extensions += values if values.present?
      values.each {|extension| extend(extension) }
    end

290
    def reverse_sql_order(order_query)
291
      order_query.split(',').each { |s|
292 293 294 295 296 297 298 299 300 301
        if s.match(/\s(asc|ASC)$/)
          s.gsub!(/\s(asc|ASC)$/, ' DESC')
        elsif s.match(/\s(desc|DESC)$/)
          s.gsub!(/\s(desc|DESC)$/, ' ASC')
        else
          s.concat(' DESC')
        end
      }.join(',')
    end

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

306 307
  end
end