Class: BatchAgg::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/batchagg.rb

Instance Method Summary collapse

Constructor Details

#initialize(model, aggs) ⇒ Query

Returns a new instance of Query.



146
147
148
149
# File 'lib/batchagg.rb', line 146

def initialize(model, aggs)
  @model = model
  @aggs = aggs
end

Instance Method Details

#build(scope) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/batchagg.rb', line 151

def build(scope)
  outer = @model.arel_table.alias("batchagg_outer_#{@model.table_name}")
  corr = AssocMagic.new(@model, outer)
  colproj = ColumnProj.new(outer, @model)
  arel = Arel::SelectManager.new(scope.klass.connection)
  arel.from(outer)
  arel.project(outer[@model.primary_key].as(@model.primary_key.to_s))
  @aggs.reject(&:computed?).each do |agg|
    proj = agg.column_based? ? colproj.build(agg, corr) : Arel.sql("(#{AggSQL.sql(agg.block.call(corr), agg)})").as(agg.name.to_s)
    arel.project(proj)
  end
  arel.where(
    outer[@model.primary_key].in(
      Arel.sql("(#{scope.select(@model.primary_key).to_sql})")
    )
  )
  arel
end